<?php
/**
 * Add New Customer Pricing Rule to Store
 */

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);
$packageSizeGb = floatval($_POST['package_size_gb'] ?? 0);
$packageLabel = trim($_POST['package_label'] ?? '');
$price = floatval($_POST['price'] ?? 0);
$network = $_POST['network'] ?? 'mtn';

// 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 - You do not own this store']);
    exit();
}

// Validation
if ($packageSizeGb <= 0 || $price <= 0) {
    echo json_encode(['success' => false, 'message' => 'Package size and price must be greater than 0']);
    exit();
}

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

// Get maximum admin package size for validation
$customerPricingManager = new StoreCustomerPricingManager($conn);
$maxAdminSize = $customerPricingManager->getMaxAdminPackageSize($network);

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

// Check if pricing already exists for this package size
$existingCheckStmt = $conn->prepare("
    SELECT id FROM store_customer_pricing 
    WHERE store_id = ? 
    AND network_type = ? 
    AND ABS(package_size_gb - ?) < 0.001
    LIMIT 1
");
$existingCheckStmt->bind_param("isd", $storeId, $network, $packageSizeGb);
$existingCheckStmt->execute();
$existingCheckResult = $existingCheckStmt->get_result();

if ($existingCheckResult->num_rows > 0) {
    $existingCheckStmt->close();
    echo json_encode([
        'success' => false, 
        'message' => 'You already have pricing set for this package size. Please use the edit function to update it.'
    ]);
    exit();
}
$existingCheckStmt->close();

// Add pricing rule
$result = $customerPricingManager->setCustomerPricing($storeId, $network, $packageSizeGb, $packageLabel, $price, 1);

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

