<?php
/**
 * Check if a specific package size is available for an agent
 * Returns availability status and price if available
 */

session_start();
require_once 'config.php';
require_once 'app/classes/CustomPricingManager.php';
require_once 'app/classes/StorePricingManager.php';

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

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

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

$userId = $_SESSION['user_id'];
$networkType = $_POST['network_type'] ?? '';
$packageSize = trim($_POST['package_size'] ?? '');

if (empty($networkType)) {
    echo json_encode(['success' => false, 'message' => 'Network type is required']);
    exit;
}

if (empty($packageSize)) {
    echo json_encode(['success' => false, 'message' => 'Package size is required']);
    exit;
}

// Normalize package size - accept numeric input and format with GB
$packageSize = trim($packageSize);
$originalSize = $packageSize;

// If it's just a number, assume GB (this is the new format)
if (is_numeric($packageSize)) {
    $packageSize = $packageSize . 'GB';
} elseif (preg_match('/(\d+(?:\.\d+)?)\s*(MB|GB|mb|gb)/i', $packageSize, $matches)) {
    // Handle legacy format with unit (handles "1GB", "1 GB", "1gb", etc.)
    $packageSize = $matches[1] . strtoupper($matches[2]);
} else {
    // Invalid format
    echo json_encode(['success' => false, 'message' => 'Invalid package size. Enter a number (e.g., 1, 2, 3) or format like "1GB"']);
    exit;
}

// Check if user belongs to a store
$userStmt = $conn->prepare("SELECT store_id FROM agents WHERE id = ?");
$userStmt->bind_param("i", $userId);
$userStmt->execute();
$userResult = $userStmt->get_result();
$userData = $userResult->fetch_assoc();
$storeId = $userData['store_id'] ?? null;
$userStmt->close();

$price = null;

// USE STORE PRICING if agent belongs to a store
if ($storeId) {
    $storePricingManager = new StorePricingManager($conn);
    $priceInfo = $storePricingManager->calculatePrice($storeId, $packageSize, $networkType);
    $price = $priceInfo['price'];
} else {
    // Fallback to role-based pricing
    $pricingManager = new CustomPricingManager($conn);
    $role = $_SESSION['role'] ?? 'agent';
    $priceInfo = $pricingManager->calculatePrice($packageSize, $networkType, $role);
    $price = $priceInfo['price'];
}

if ($price === null || $price === false || !is_numeric($price) || $price <= 0) {
    echo json_encode([
        'success' => false,
        'available' => false,
        'message' => 'This package size is not available. Please contact your store owner to set up pricing for this package.'
    ]);
    exit;
}

// Format price to 2 decimal places (return as number, not string, for easier parsing)
$formattedPrice = round((float)$price, 2);

echo json_encode([
    'success' => true,
    'available' => true,
    'package_size' => $packageSize,
    'price' => $formattedPrice,
    'price_formatted' => number_format($formattedPrice, 2, '.', ''),
    'message' => 'Package is available'
]);
?>

