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

session_start();
require_once '../config.php';
require_once '../app/classes/StoreManager.php';
require_once '../app/classes/StorePricingManager.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();
}

$userId = $_SESSION['user_id'];
$storeId = intval($_POST['store_id'] ?? 0);
$minSizeGb = floatval($_POST['min_size_gb'] ?? 0);
$maxSizeGb = floatval($_POST['max_size_gb'] ?? 0);
$pricePerGb = floatval($_POST['price_per_gb'] ?? 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 ($minSizeGb <= 0 || $maxSizeGb <= 0 || $pricePerGb <= 0) {
    echo json_encode(['success' => false, 'message' => 'All values must be greater than 0']);
    exit();
}

if ($minSizeGb >= $maxSizeGb) {
    echo json_encode(['success' => false, 'message' => 'Min size must be less than max size']);
    exit();
}

// CRITICAL: Verify that this range matches an admin-defined range exactly
$adminCheckStmt = $conn->prepare("
    SELECT id, min_size_gb, max_size_gb, price_per_gb 
    FROM agent_pricing_rules 
    WHERE network_type = ? 
    AND role = 'agent' 
    AND is_active = 1
    AND ABS(min_size_gb - ?) < 0.001 
    AND ABS(max_size_gb - ?) < 0.001
    LIMIT 1
");
$adminCheckStmt->bind_param("sdd", $network, $minSizeGb, $maxSizeGb);
$adminCheckStmt->execute();
$adminCheckResult = $adminCheckStmt->get_result();

if ($adminCheckResult->num_rows === 0) {
    $adminCheckStmt->close();
    echo json_encode([
        'success' => false, 
        'message' => 'This range does not match any admin-defined range. You can only set prices for ranges defined by the administrator.'
    ]);
    exit();
}

// Get the exact admin rule values to ensure precision match
$adminRule = $adminCheckResult->fetch_assoc();
$adminCheckStmt->close();

// Use the exact admin rule values to ensure perfect match
$minSizeGb = floatval($adminRule['min_size_gb']);
$maxSizeGb = floatval($adminRule['max_size_gb']);

// Check if store already has pricing for this exact range
$existingCheckStmt = $conn->prepare("
    SELECT id, min_size_gb, max_size_gb 
    FROM store_pricing 
    WHERE store_id = ? 
    AND network_type = ? 
    AND ABS(min_size_gb - ?) < 0.001 
    AND ABS(max_size_gb - ?) < 0.001
    LIMIT 1
");
$existingCheckStmt->bind_param("isdd", $storeId, $network, $minSizeGb, $maxSizeGb);
$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 range. Please use the edit function to update it.'
    ]);
    exit();
}
$existingCheckStmt->close();

// Add pricing rule
$pricingManager = new StorePricingManager($conn);
$result = $pricingManager->setStorePricing($storeId, $network, $minSizeGb, $maxSizeGb, $pricePerGb, 1);

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



