<?php
session_start();
require_once '../../config.php';
require_once '../../app/classes/AdminAuth.php';
require_once '../../app/classes/CustomPricingManager.php';


$adminAuth = new AdminAuth($conn);
$pricingManager = new CustomPricingManager($conn);

// Check if admin is authenticated
if (!$adminAuth->isAuthenticated()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit();
}

$action = $_POST['action'] ?? '';

try {
    switch ($action) {
        case 'add_pricing':
            $packageSize = trim($_POST['package_size'] ?? '');
            $cost = floatval($_POST['cost'] ?? 0);
            $networkType = trim($_POST['network_type'] ?? 'all');
            $userRole = trim($_POST['user_role'] ?? '');
            
            if (empty($packageSize) || $cost <= 0) {
                echo json_encode(['success' => false, 'message' => 'Package size and cost are required']);
                exit();
            }
            
            if (empty($userRole) || $userRole !== 'agent') {
                echo json_encode(['success' => false, 'message' => 'Please select a valid role (Agent, Super Agent, or Dealer)']);
                exit();
            }
            
            $result = $pricingManager->setCustomPricing($packageSize, $cost, $userRole, $networkType, null);
            
            if ($result['success']) {
                echo json_encode([
                    'success' => true,
                    'message' => 'Custom pricing ' . $result['action'] . ' successfully'
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => $result['message'] ?? 'Failed to add custom pricing'
                ]);
            }
            break;
            
        case 'update_pricing':
            $pricingId = intval($_POST['pricing_id'] ?? 0);
            $packageSize = trim($_POST['package_size'] ?? '');
            $cost = floatval($_POST['cost'] ?? 0);
            $networkType = trim($_POST['network_type'] ?? 'all');
            $userRole = trim($_POST['user_role'] ?? '');
            
            if ($pricingId <= 0 || empty($packageSize) || $cost <= 0) {
                echo json_encode(['success' => false, 'message' => 'Invalid pricing data']);
                exit();
            }
            
            if (empty($userRole) || $userRole !== 'agent') {
                echo json_encode(['success' => false, 'message' => 'Please select a valid role (Agent, Super Agent, or Dealer)']);
                exit();
            }
            
            // Update the pricing
            $stmt = $conn->prepare("
                UPDATE custom_pricing 
                SET package_size = ?, package_size_gb = ?, cost = ?, network_type = ?, user_role = ?, updated_at = NOW()
                WHERE id = ?
            ");
            $packageSizeGb = $pricingManager->parsePackageSizeToGb($packageSize);
            $stmt->bind_param("sddssi", $packageSize, $packageSizeGb, $cost, $networkType, $userRole, $pricingId);
            
            if ($stmt->execute()) {
                echo json_encode([
                    'success' => true,
                    'message' => 'Custom pricing updated successfully'
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => 'Failed to update custom pricing'
                ]);
            }
            $stmt->close();
            break;
            
        case 'delete_pricing':
            $pricingId = intval($_POST['pricing_id'] ?? 0);
            
            if ($pricingId <= 0) {
                echo json_encode(['success' => false, 'message' => 'Invalid pricing ID']);
                exit();
            }
            
            // Check if the pricing exists first
            $existingPricing = $pricingManager->getCustomPricingById($pricingId);
            if (!$existingPricing) {
                echo json_encode([
                    'success' => false,
                    'message' => 'Pricing entry not found'
                ]);
                exit();
            }
            
            $success = $pricingManager->deleteCustomPricing($pricingId);
            
            if ($success) {
                echo json_encode([
                    'success' => true,
                    'message' => 'Custom pricing deleted successfully'
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => 'Failed to delete custom pricing. Please check the error logs.'
                ]);
            }
            break;
            
            
        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
            break;
    }
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>
