<?php
/**
 * Update Store Customer Pricing
 */

session_start();
require_once '../config.php';
require_once '../app/classes/StoreManager.php';
require_once '../app/classes/StoreCustomerPricingManager.php';

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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit();
}

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

// CSRF Protection
function validateCSRFToken($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

// Check CSRF token (from header or POST)
$csrfToken = $_POST['csrf_token'] ?? $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
if (empty($csrfToken) || !validateCSRFToken($csrfToken)) {
    echo json_encode(['success' => false, 'message' => 'Invalid security token']);
    exit();
}

$userId = $_SESSION['user_id'];
$storeId = intval($_POST['store_id'] ?? 0);
$pricingId = intval($_POST['pricing_id'] ?? 0);
$packageSizeGb = isset($_POST['package_size_gb']) ? floatval($_POST['package_size_gb']) : null;
$packageLabel = trim($_POST['package_label'] ?? '');
$price = floatval($_POST['price'] ?? 0);
$isActive = isset($_POST['is_active']) ? intval($_POST['is_active']) : 1;

// Verify user owns this store
$storeManager = new StoreManager($conn);
$store = $storeManager->getStoreById($storeId);

if (!$store || $store['owner_id'] != $userId) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

if ($price <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid price']);
    exit();
}

// Get existing pricing
$getStmt = $conn->prepare("SELECT package_size_gb, network_type FROM store_customer_pricing WHERE id = ? AND store_id = ?");
$getStmt->bind_param("ii", $pricingId, $storeId);
$getStmt->execute();
$getResult = $getStmt->get_result();

if ($getResult->num_rows === 0) {
    $getStmt->close();
    echo json_encode(['success' => false, 'message' => 'Pricing rule not found']);
    exit();
}

$existing = $getResult->fetch_assoc();
$getStmt->close();

// Use new package size if provided, otherwise use existing
$newPackageSizeGb = $packageSizeGb !== null ? $packageSizeGb : $existing['package_size_gb'];

// Validate package size
if ($newPackageSizeGb <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid package size']);
    exit();
}

// Get maximum admin package size for validation
$customerPricingManager = new StoreCustomerPricingManager($conn);
$maxAdminSize = $customerPricingManager->getMaxAdminPackageSize($existing['network_type']);

if ($maxAdminSize && $newPackageSizeGb > $maxAdminSize) {
    echo json_encode([
        'success' => false, 
        'message' => 'Package size cannot exceed maximum admin range of ' . number_format($maxAdminSize, 2) . 'GB'
    ]);
    exit();
}

if (empty($packageLabel)) {
    $packageLabel = $newPackageSizeGb . 'GB';
}

// If package size changed, check if new size already exists (and it's not the same record)
if ($newPackageSizeGb != $existing['package_size_gb']) {
    $checkStmt = $conn->prepare("
        SELECT id FROM store_customer_pricing 
        WHERE store_id = ? 
        AND network_type = ? 
        AND ABS(package_size_gb - ?) < 0.001
        AND id != ?
        LIMIT 1
    ");
    $checkStmt->bind_param("isdi", $storeId, $existing['network_type'], $newPackageSizeGb, $pricingId);
    $checkStmt->execute();
    $checkResult = $checkStmt->get_result();
    
    if ($checkResult->num_rows > 0) {
        $checkStmt->close();
        echo json_encode([
            'success' => false, 
            'message' => 'You already have pricing set for this package size. Please use a different size or delete the existing one first.'
        ]);
        exit();
    }
    $checkStmt->close();
    
    // Delete old pricing and create new one with new size
    $customerPricingManager->deleteCustomerPricing($pricingId);
    $result = $customerPricingManager->setCustomerPricing(
        $storeId, 
        $existing['network_type'], 
        $newPackageSizeGb, 
        $packageLabel, 
        $price, 
        $isActive
    );
} else {
    // Update existing pricing (size unchanged)
    $result = $customerPricingManager->setCustomerPricing(
        $storeId, 
        $existing['network_type'], 
        $existing['package_size_gb'], 
        $packageLabel, 
        $price, 
        $isActive
    );
}

if ($result['success']) {
    echo json_encode(['success' => true, 'message' => 'Customer pricing updated successfully']);
} else {
    echo json_encode(['success' => false, 'message' => $result['message'] ?? 'Failed to update pricing']);
}
?>

