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

require_once 'config.php';
require_once 'app/classes/StorePricingManager.php';
require_once 'app/classes/StoreCustomerPricingManager.php';

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

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

$storeId = intval($_POST['store_id'] ?? 0);
$network = $_POST['network'] ?? '';
$packageSize = trim($_POST['package_size'] ?? '');

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

if ($network !== 'mtn') {
    echo json_encode(['success' => false, 'message' => 'Invalid network. Only MTN is supported.']);
    exit;
}

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

// Normalize package size (handle variations like "1GB", "1 GB", "1gb", etc.)
// First, sanitize iPhone-specific characters (non-breaking spaces, Unicode whitespace, etc.)
$packageSize = trim($packageSize);
$packageSize = preg_replace('/[\x{00A0}\x{2000}-\x{200B}\x{202F}\x{205F}\x{3000}]/u', ' ', $packageSize); // Replace non-breaking spaces and Unicode whitespace
$packageSize = preg_replace('/[\x{200C}-\x{200F}\x{FEFF}]/u', '', $packageSize); // Remove invisible/special characters
$packageSize = preg_replace('/\s+/', ' ', $packageSize); // Normalize multiple spaces to single space
$packageSize = trim($packageSize);
$originalSize = $packageSize;

// Try to extract number and unit (handles "1GB", "1 GB", "1gb", "1 gb", etc.)
// More lenient regex to handle iPhone input quirks
if (preg_match('/(\d+(?:\.\d+)?)\s*(MB|GB|mb|gb|Mb|Gb|mB|gB)/i', $packageSize, $matches)) {
    $packageSize = $matches[1] . strtoupper($matches[2]);
} elseif (preg_match('/^(\d+(?:\.\d+)?)\s*$/', $packageSize, $matches)) {
    // If it's just a number (with optional spaces), assume GB
    $packageSize = $matches[1] . 'GB';
} elseif (is_numeric($packageSize)) {
    // If it's just a number, assume GB
    $packageSize = $packageSize . 'GB';
} elseif (preg_match('/^(MB|GB|mb|gb|Mb|Gb|mB|gB)$/i', trim($packageSize))) {
    // Already has unit but no number - invalid
    echo json_encode(['success' => false, 'message' => 'Invalid package size format. Use format like "1GB" or "500MB"']);
    exit;
} else {
    // Try one more time with a more lenient approach - extract any number
    if (preg_match('/(\d+(?:\.\d+)?)/', $packageSize, $matches)) {
        // Found a number, check if there's a unit
        if (preg_match('/(MB|GB|mb|gb|Mb|Gb|mB|gB)/i', $packageSize, $unitMatches)) {
            $packageSize = $matches[1] . strtoupper($unitMatches[1]);
        } else {
            // No unit found, assume GB
            $packageSize = $matches[1] . 'GB';
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid package size format. Use format like "1GB" or "500MB"']);
        exit;
    }
}

// Check if store exists and is active
require_once 'app/classes/StoreManager.php';
$storeManager = new StoreManager($conn);
$store = $storeManager->getStoreById($storeId);

if (!$store || $store['status'] !== 'active') {
    echo json_encode(['success' => false, 'message' => 'Store is not available']);
    exit;
}

// Calculate price for this package using CUSTOMER pricing (not agent pricing)
// Regular customers use package-specific pricing, not range-based pricing
$customerPricingManager = new StoreCustomerPricingManager($conn);
$priceInfo = $customerPricingManager->getPriceForPackage($storeId, $packageSize, $network);

if ($priceInfo['price'] === null || $priceInfo['price'] <= 0) {
    echo json_encode([
        'success' => false,
        'available' => false,
        'message' => 'This package size is not available for this store'
    ]);
    exit;
}

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

