 <?php
// Include required classes
require_once 'config_api.php';
require_once 'app/classes/ExternalAPIService.php';
require_once 'app/classes/BalanceHistory.php';
require_once 'app/classes/AdminNotificationManager.php';
require_once 'app/classes/ExternalAPIPricingManager.php';
use App\classes\BalanceHistory;
use App\classes\ExternalAPIPricingManager;

// Session security measures
if (!isset($_SESSION['user_id'])) {
    header('Location: logout.php');
    exit();
}

// Clean up any stale submission flags (older than 5 minutes)
$currentTime = time();
if (isset($_SESSION['submission_timestamps'])) {
    foreach ($_SESSION['submission_timestamps'] as $key => $timestamp) {
        if ($currentTime - $timestamp > 300) { // 5 minutes
            unset($_SESSION['submission_timestamps'][$key]);
            unset($_SESSION[$key]);
        }
    }
}

// Validate session integrity
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'agent') {
    header('Location: logout.php');
    exit();
}

// CSRF protection for sensitive operations
function generateCSRFToken() {
    if (!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

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

// Direct database query for site data
$sql = "SELECT * FROM `site`";
$result = mysqli_query($conn, $sql);
if ($result) {
    $ob = $result;
} else {
    $ob = false;
}
$siteData = mysqli_fetch_assoc($ob);
date_default_timezone_set('GMT');

// Get user's current balance and information with validation (including store info)
$stmt = $conn->prepare("
    SELECT a.username, a.email, a.balance, a.role, a.store_id, a.is_store_owner,
           s.store_name, s.store_slug, sa.status as agent_status
    FROM agents a
    LEFT JOIN stores s ON a.store_id = s.id
    LEFT JOIN store_agents sa ON a.id = sa.agent_id AND sa.store_id = a.store_id
    WHERE a.id = ?
");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
$stmt->close();

if (!$user) {
    header('Location: logout.php');
    exit();
}

$balance = isset($user['balance']) ? floatval($user['balance']) : 0;
$username = isset($user['username']) ? htmlspecialchars($user['username'], ENT_QUOTES, 'UTF-8') : 'Unknown';
$user_email = isset($user['email']) ? htmlspecialchars($user['email'], ENT_QUOTES, 'UTF-8') : '';
$role = isset($user['role']) ? $user['role'] : 'agent';
$userStoreId = $user['store_id'] ?? null;
$storeName = $user['store_name'] ?? null;
$storeSlug = $user['store_slug'] ?? null;
$isStoreOwner = isset($user['is_store_owner']) && $user['is_store_owner'] == 1;
$agentStatus = $user['agent_status'] ?? 'active';

// Check if agent is suspended (only for non-store-owners)
if (!$isStoreOwner && $agentStatus === 'suspended') {
    // Clear cart if suspended
    $_SESSION['cart'] = [];
    // Show error message
    $error_message = "Your account has been suspended. Please contact your store owner for assistance.";
}

// Validate balance
if (!validateBalance($balance)) {
    error_log("Invalid balance detected for user $user_id: $balance");
    $balance = 0;
}

// Initialize notification manager and get notifications
$notificationManager = new AdminNotificationManager($conn);
$notifications = $notificationManager->getUserNotifications($user_id, $role, 5, 0, true); // Get 5 unread notifications
$unreadCount = $notificationManager->getUnreadCount($user_id, $role);

// Minimum top-up manager is initialized in user_index.php for all pages

// Handle notification actions
if (isset($_POST['mark_notification_read'])) {
    $notificationId = intval($_POST['notification_id']);
    $result = $notificationManager->markAsRead($notificationId, $user_id, $role);
    if ($result['success']) {
        // Redirect to refresh the page with updated notification count
        header('Location: user_index.php?page=dashboard&notification=marked_read');
        exit();
    } else {
        $error_message = "Failed to mark notification as read: " . $result['message'];
    }
}

if (isset($_POST['mark_all_read'])) {
    $result = $notificationManager->markAllAsRead($user_id, $role);
    if ($result['success']) {
        // Redirect to refresh the page with updated notification count
        header('Location: user_index.php?page=dashboard&notification=all_marked_read');
        exit();
    } else {
        $error_message = "Failed to mark all notifications as read: " . $result['message'];
    }
}

// Initialize cart if not set
if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = [];
}

// Cart validation and security functions
function validateCartItem($item) {
    // Validate required fields
    if (!isset($item['bundle']) || !isset($item['cost']) || !isset($item['beneficiary_number']) || !isset($item['network_type'])) {
        return ['valid' => false, 'error' => 'Missing required cart item fields'];
    }
    
    // Validate bundle format (accept both MB and GB formats)
    if (!preg_match('/^\d+(\.\d+)?(MB|GB)$/i', $item['bundle'])) {
        return ['valid' => false, 'error' => 'Invalid bundle format'];
    }
    
    // Validate cost (must be positive number)
    if (!is_numeric($item['cost']) || $item['cost'] <= 0 || $item['cost'] > 10000) {
        return ['valid' => false, 'error' => 'Invalid cost value'];
    }
    
    // Validate beneficiary number (10 digits)
    if (!preg_match('/^\d{10}$/', $item['beneficiary_number'])) {
        return ['valid' => false, 'error' => 'Invalid phone number format'];
    }
    
    // Validate network type
    if (!in_array($item['network_type'], ['mtn', 'telecel', 'airtel_tigo'])) {
        return ['valid' => false, 'error' => 'Invalid network type'];
    }
    
    return ['valid' => true];
}

function validateCart($cart) {
    if (!is_array($cart)) {
        return ['valid' => false, 'error' => 'Cart must be an array'];
    }
    
    if (count($cart) > 50) { // Limit cart size
        return ['valid' => false, 'error' => 'Cart size limit exceeded (max 50 items)'];
    }
    
    $totalCost = 0;
    $networkTypes = [];
    
    foreach ($cart as $index => $item) {
        $validation = validateCartItem($item);
        if (!$validation['valid']) {
            return ['valid' => false, 'error' => "Item $index: " . $validation['error']];
        }
        
        $totalCost += $item['cost'];
        
        // Check for network mixing
        if (!in_array($item['network_type'], $networkTypes)) {
            $networkTypes[] = $item['network_type'];
        }
    }
    
    // Validate total cost bounds
    if ($totalCost <= 0 || $totalCost > 50000) { // Max 50,000 GHS per cart
        return ['valid' => false, 'error' => 'Invalid total cost'];
    }
    
    // Check for network mixing (only allow one network type per cart)
    if (count($networkTypes) > 1) {
        return ['valid' => false, 'error' => 'Cannot mix different network types in one cart'];
    }
    
    return ['valid' => true, 'total_cost' => $totalCost];
}

function sanitizeCartItem($item) {
    return [
        'bundle' => htmlspecialchars(trim($item['bundle']), ENT_QUOTES, 'UTF-8'),
        'cost' => floatval($item['cost']),
        'beneficiary_number' => preg_replace('/[^0-9]/', '', $item['beneficiary_number']),
        'network_type' => in_array($item['network_type'], ['mtn', 'telecel', 'airtel_tigo']) ? $item['network_type'] : 'mtn'
    ];
}

function validateBalance($balance) {
    if (!is_numeric($balance) || $balance < 0 || $balance > 1000000) { // Max 1M GHS balance
        return false;
    }
    return true;
}

// Network validation function
function validatePhoneForNetwork($phoneNumber, $networkType) {
    $phone = preg_replace('/[^0-9]/', '', $phoneNumber);
    
    // Check if phone number is 10 digits
    if (strlen($phone) !== 10) {
        return false;
    }
    
    $prefix = substr($phone, 0, 3);
    
    $networkPrefixes = [
        'mtn' => ['024', '025', '053', '054', '055', '059'],
        'telecel' => ['020', '050'],
        'airtel_tigo' => ['027', '057', '026', '056', '023']
    ];
    
    return isset($networkPrefixes[$networkType]) && in_array($prefix, $networkPrefixes[$networkType]);
}

// shouldUseExternalAPI() function is already declared in config_api.php

// Handle bulk text input
if (isset($_POST['add_bulk_orders'])) {
    $bulkText = trim($_POST['bulk_orders_text']);
    $networkType = trim($_POST['network_type']);
    
    // Check if cart already has items from a different network
    if (!empty($_SESSION['cart'])) {
        $existingNetwork = $_SESSION['cart'][0]['network_type'];
        if ($existingNetwork !== $networkType) {
            $networkNames = [
                'mtn' => 'MTN',
                'telecel' => 'Telecel (Vodafone)',
                'airtel_tigo' => 'AirtelTigo'
            ];
            $error_message = "Cannot mix networks! Your cart contains {$networkNames[$existingNetwork]} orders. Please checkout or clear cart before adding {$networkNames[$networkType]} orders.";
        } else {
            // Same network, proceed with bulk processing
            processBulkOrders($bulkText, $networkType, $role);
        }
        } else {
            // Empty cart, proceed with bulk processing
            processBulkOrders($bulkText, $networkType, $role);
        }
    }

// Helper function to process bulk orders
function processBulkOrders($bulkText, $networkType, $role) {
    global $conn, $success_message, $error_message;
    
    // Validate input parameters
    if (!in_array($networkType, ['mtn', 'telecel', 'airtel_tigo'])) {
        $error_message = "Invalid network type";
        return;
    }
    
    if ($role !== 'agent') {
        $error_message = "Invalid user role";
        return;
    }
    
    // Validate and sanitize bulk text
    $bulkText = trim($bulkText);
    if (strlen($bulkText) > 10000) { // Limit bulk text size
        $error_message = "Bulk text too large (max 10,000 characters)";
        return;
    }
    
    $lines = explode("\n", $bulkText);
    $addedCount = 0;
    $rejectedOrders = [];
    $lineNumber = 0;
    
    // Limit number of lines
    if (count($lines) > 100) {
        $error_message = "Too many lines in bulk text (max 100 lines)";
        return;
    }
    
    foreach ($lines as $line) {
        $lineNumber++;
        $line = trim($line);
        if (empty($line)) continue;
        
        // Split by space or tab to get phone number and bundle size
        $parts = preg_split('/[\s\t]+/', $line, 2);
        if (count($parts) >= 2) {
            $beneficiaryNumber = trim($parts[0]);
            $packageSize = trim($parts[1]);
            // Format package size - if it's just a number, add GB
            if (is_numeric($packageSize)) {
                $packageSize = $packageSize . 'GB';
            }
            
            // Validate phone number format first
            $cleanPhone = preg_replace('/[^0-9]/', '', $beneficiaryNumber);
            if (strlen($cleanPhone) !== 10) {
                $rejectedOrders[] = "Line $lineNumber: $beneficiaryNumber - Phone number must be 10 digits";
                continue;
            }
            
            // Validate phone number against selected network
            if (!validatePhoneForNetwork($beneficiaryNumber, $networkType)) {
                $networkNames = [
                    'mtn' => 'MTN',
                    'telecel' => 'Telecel (Vodafone)',
                    'airtel_tigo' => 'AirtelTigo'
                ];
                $networkPrefixes = [
                    'mtn' => ['024', '025', '053', '054', '055', '059'],
                    'telecel' => ['020', '050'],
                    'airtel_tigo' => ['027', '057', '026', '056', '023']
                ];
                $validPrefixes = implode(', ', $networkPrefixes[$networkType]);
                $rejectedOrders[] = "Line $lineNumber: $beneficiaryNumber - Invalid prefix for {$networkNames[$networkType]}. Valid prefixes: $validPrefixes";
                continue;
            }
            
            // Extract numeric value for validation
            $packageSizeNum = floatval(preg_replace('/[^0-9.]/', '', $packageSize));
            
            // Validate package size bounds
            if ($packageSizeNum <= 0 || $packageSizeNum > 1000) {
                $rejectedOrders[] = "Line $lineNumber: $beneficiaryNumber - Invalid package size (must be between 0.1 and 1000 GB)";
                continue;
            }
            
            // Get pricing - use STORE pricing if agent belongs to a store
            $cost = null;
            
            // Check if user belongs to a store
            $userStoreStmt = $conn->prepare("SELECT store_id FROM agents WHERE id = ?");
            $userStoreStmt->bind_param("i", $user_id);
            $userStoreStmt->execute();
            $userStoreResult = $userStoreStmt->get_result();
            $userStoreData = $userStoreResult->fetch_assoc();
            $userStoreId = $userStoreData['store_id'] ?? null;
            $userStoreStmt->close();
            
            if ($userStoreId) {
                // USE STORE PRICING
                require_once 'app/classes/StorePricingManager.php';
                $storePricingManager = new StorePricingManager($conn);
                // Use formatted package size (already has GB if numeric was provided)
                $bundleLabel = $packageSize;
                $pricingResult = $storePricingManager->calculatePrice($userStoreId, $bundleLabel, $networkType);
                $cost = $pricingResult['price'];
            } else {
                // Fallback to role-based pricing
                require_once 'app/classes/CustomPricingManager.php';
                $pricingManager = new CustomPricingManager($conn);
                // Use formatted package size (already has GB if numeric was provided)
                $bundleLabel = $packageSize;
                $pricingResult = $pricingManager->calculatePrice($bundleLabel, $networkType, $role);
                $cost = $pricingResult['price'];
            }
            
            // Validate pricing result
            if ($cost === null || $cost === false || !is_numeric($cost) || $cost <= 0 || $cost > 10000) {
                $rejectedOrders[] = "Line $lineNumber: $beneficiaryNumber $packageSize GB - No valid pricing set for this package size";
                continue;
            }
            
            // Create cart item with validation
            $cartItem = [
                'bundle' => $packageSize . 'GB',
                'cost' => floatval($cost),
                'beneficiary_number' => $cleanPhone,
                'network_type' => $networkType
            ];
            
            // Validate cart item before adding
            $itemValidation = validateCartItem($cartItem);
            if (!$itemValidation['valid']) {
                $rejectedOrders[] = "Line $lineNumber: $beneficiaryNumber - " . $itemValidation['error'];
                continue;
            }
            
            // Sanitize and add to cart
            $sanitizedItem = sanitizeCartItem($cartItem);
            $_SESSION['cart'][] = $sanitizedItem;
            $addedCount++;
        } else {
            $rejectedOrders[] = "Line $lineNumber: Invalid format (expected: phone_number package_size)";
        }
    }
    
    // Validate entire cart after adding items
    $cartValidation = validateCart($_SESSION['cart']);
    if (!$cartValidation['valid']) {
        // Clear cart if validation fails
        $_SESSION['cart'] = [];
        $error_message = "Cart validation failed: " . $cartValidation['error'];
        return;
    }
    
    // Provide detailed feedback
    if ($addedCount > 0) {
        $success_message = "✅ Successfully added $addedCount item(s) to your cart!";
        if (!empty($rejectedOrders)) {
            $success_message .= " " . count($rejectedOrders) . " order(s) were rejected due to invalid format.";
            $_SESSION['bulk_rejected_orders'] = $rejectedOrders;
        }
    } else {
        $error_message = "No valid orders found in the text.";
        if (!empty($rejectedOrders)) {
            $_SESSION['bulk_rejected_orders'] = $rejectedOrders;
        }
    }
    
}

// Add bundle to cart manually
if (isset($_POST['add_to_cart'])) {
    // Format package size - if it's just a number, add GB
    $selectedPackage = trim($_POST['bundle_size']);
    if (is_numeric($selectedPackage)) {
        $selectedPackage = $selectedPackage . 'GB';
    }
    $networkType = $_POST['network_type'];
    $beneficiaryNumber = $_POST['beneficiary_number'];
    
    // Check if cart already has items from a different network
    if (!empty($_SESSION['cart'])) {
        $existingNetwork = $_SESSION['cart'][0]['network_type'];
        if ($existingNetwork !== $networkType) {
            $networkNames = [
                'mtn' => 'MTN',
                'telecel' => 'Telecel (Vodafone)',
                'airtel_tigo' => 'AirtelTigo'
            ];
            $error_message = "Cannot mix networks! Your cart contains {$networkNames[$existingNetwork]} orders. Please checkout or clear cart before adding {$networkNames[$networkType]} orders.";
        } else {
            // Same network, proceed with adding
            addToCart($selectedPackage, $networkType, $beneficiaryNumber, $role, $balance, $user_id);
        }
        } else {
            // Empty cart, proceed with adding
            addToCart($selectedPackage, $networkType, $beneficiaryNumber, $role, $balance, $user_id);
        }
    }

// Helper function to add item to cart
function addToCart($selectedPackage, $networkType, $beneficiaryNumber, $role, $balance, $user_id) {
    global $conn, $success_message, $error_message;
    
    // Validate input parameters (MTN only now)
    if ($networkType !== 'mtn') {
        $error_message = "Invalid network type. Only MTN is supported.";
        return;
    }
    
    if ($role !== 'agent') {
        $error_message = "Invalid user role";
        return;
    }
    
    // Validate and sanitize package selection (accept both MB and GB formats)
    $selectedPackage = trim($selectedPackage);
    if (empty($selectedPackage) || !preg_match('/^\d+(\.\d+)?(MB|GB)$/i', $selectedPackage)) {
        $error_message = "Invalid package format";
        return;
    }
    
    // Validate phone number format first
    $cleanPhone = preg_replace('/[^0-9]/', '', $beneficiaryNumber);
    if (strlen($cleanPhone) !== 10) {
        $error_message = "Phone number must be 10 digits";
        return;
    }
    
    // Validate phone number against selected network (MTN prefixes)
    if (!validatePhoneForNetwork($beneficiaryNumber, $networkType)) {
        $networkPrefixes = ['024', '025', '053', '054', '055', '059'];
        $validPrefixes = implode(', ', $networkPrefixes);
        $error_message = "Invalid phone number for MTN. Valid prefixes: $validPrefixes";
        return;
    }
    
    // Get pricing - USE STORE PRICING if agent belongs to a store
    $cost = null;
    
    // Check if user belongs to a store
    $userStoreStmt = $conn->prepare("SELECT store_id FROM agents WHERE id = ?");
    $userStoreStmt->bind_param("i", $user_id);
    $userStoreStmt->execute();
    $userStoreResult = $userStoreStmt->get_result();
    $userStoreData = $userStoreResult->fetch_assoc();
    $userStoreId = $userStoreData['store_id'] ?? null;
    $userStoreStmt->close();
    
    if ($userStoreId) {
        // USE STORE PRICING
        require_once 'app/classes/StorePricingManager.php';
        $storePricingManager = new StorePricingManager($conn);
        $pricingResult = $storePricingManager->calculatePrice($userStoreId, $selectedPackage, $networkType);
        $cost = $pricingResult['price'];
    } else {
        // Fallback to role-based pricing
        require_once 'app/classes/CustomPricingManager.php';
        $pricingManager = new CustomPricingManager($conn);
        $pricingResult = $pricingManager->calculatePrice($selectedPackage, $networkType, $role);
        $cost = $pricingResult['price'];
    }
    
    // Validate pricing result
    if ($cost === null || $cost === false || !is_numeric($cost) || $cost <= 0 || $cost > 10000) {
        $error_message = "No valid pricing set for " . $selectedPackage . ". Please contact your store owner to set up pricing for this package.";
        return;
    }
    
    // Create cart item with validation
    $cartItem = [
        'bundle' => $selectedPackage,
        'cost' => floatval($cost),
        'beneficiary_number' => $cleanPhone,
        'network_type' => $networkType
    ];
    
    // Validate cart item
    $itemValidation = validateCartItem($cartItem);
    if (!$itemValidation['valid']) {
        $error_message = $itemValidation['error'];
        return;
    }
    
    // Check balance
    if ($balance < $cost) {
        $shortfall = $cost - $balance;
        $error_message = "Insufficient balance! You need GHS " . number_format($shortfall, 2) . " more to add this " . $selectedPackage . " bundle.";
        return;
    }
    
    // Validate entire cart before adding
    $tempCart = $_SESSION['cart'];
    $tempCart[] = $cartItem;
    $cartValidation = validateCart($tempCart);
    
    if (!$cartValidation['valid']) {
        $error_message = "Cannot add item to cart: " . $cartValidation['error'];
        return;
    }
    
    // Sanitize and add to cart
    $sanitizedItem = sanitizeCartItem($cartItem);
    $_SESSION['cart'][] = $sanitizedItem;
    $success_message = "✅ Item added to cart! You can review your cart and proceed to checkout when ready.";
}

// Remove item from cart
if (isset($_POST['remove_item'])) {
    $index = $_POST['item_index'];
    unset($_SESSION['cart'][$index]);
    $_SESSION['cart'] = array_values($_SESSION['cart']);
    $success_message = "Item removed from cart!";
}

// Clear rejected orders
if (isset($_POST['clear_rejected_orders'])) {
    unset($_SESSION['bulk_rejected_orders']);
    $success_message = "Rejected orders cleared!";
}

// Checkout
if (isset($_POST['checkout'])) {
    // Get user's store_id and store owner_id for order tracking
    $userStoreStmt = $conn->prepare("SELECT a.store_id, a.is_store_owner, s.owner_id FROM agents a LEFT JOIN stores s ON a.store_id = s.id WHERE a.id = ?");
    $userStoreStmt->bind_param("i", $user_id);
    $userStoreStmt->execute();
    $userStoreResult = $userStoreStmt->get_result();
    $userStoreData = $userStoreResult->fetch_assoc();
    $userStoreId = $userStoreData['store_id'] ?? null;
    $storeOwnerId = $userStoreData['owner_id'] ?? null;
    $isStoreOwner = isset($userStoreData['is_store_owner']) && $userStoreData['is_store_owner'] == 1;
    $userStoreStmt->close();
    
    // Determine if this is a sub-agent order (requires two-level debit)
    $isSubAgent = (!$isStoreOwner && $userStoreId && $storeOwnerId);
    
    // Helper function to get admin price from agent_pricing_rules
    function getAdminPriceForPackage($conn, $packageSizeGb, $networkType = 'mtn') {
        $stmt = $conn->prepare("
            SELECT price_per_gb FROM agent_pricing_rules 
            WHERE network_type = ? AND role = 'agent' AND is_active = 1 
            AND min_size_gb <= ? AND max_size_gb >= ?
            ORDER BY min_size_gb DESC
            LIMIT 1
        ");
        $stmt->bind_param("sdd", $networkType, $packageSizeGb, $packageSizeGb);
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_assoc();
        $stmt->close();
        
        if ($row) {
            return round($row['price_per_gb'] * $packageSizeGb, 2);
        }
        return null;
    }
    
    // Helper function to parse package size to GB
    function parsePackageSizeToGb($packageSize) {
        if (empty($packageSize)) return 0;
        $packageSize = trim($packageSize);
        
        if (stripos($packageSize, 'MB') !== false) {
            $num = floatval(preg_replace('/[^0-9.]/', '', $packageSize));
            return round($num / 1024, 4);
        }
        
        if (stripos($packageSize, 'GB') !== false) {
            $num = floatval(preg_replace('/[^0-9.]/', '', $packageSize));
            return round($num, 4);
        }
        
        $num = floatval(preg_replace('/[^0-9.]/', '', $packageSize));
        return round($num, 4);
    }
    
    // CSRF protection
    if (!isset($_POST['csrf_token']) || !validateCSRFToken($_POST['csrf_token'])) {
        $error_message = "Invalid request. Please try again.";
    } elseif (!$isStoreOwner && $agentStatus === 'suspended') {
        $error_message = "Your account has been suspended. Please contact your store owner for assistance.";
        $_SESSION['cart'] = []; // Clear cart
    } elseif (isset($_SESSION['checkout_in_progress']) && $_SESSION['checkout_in_progress'] === true) {
        $error_message = "Checkout already in progress. Please wait for the current transaction to complete.";
    } else {
        // Set checkout in progress flag with timestamp
        $_SESSION['checkout_in_progress'] = true;
        $_SESSION['submission_timestamps']['checkout_in_progress'] = time();
        // Validate cart before processing
        $cartValidation = validateCart($_SESSION['cart']);
        if (!$cartValidation['valid']) {
            $error_message = "Cart validation failed: " . $cartValidation['error'];
            $_SESSION['cart'] = []; // Clear invalid cart
        } else {
            $totalStoreCost = $cartValidation['total_cost']; // Store owner's price (what sub-agent pays)
            
            // Calculate admin prices for each cart item if sub-agent
            $totalAdminCost = 0.0;
            if ($isSubAgent) {
                require_once 'app/classes/ExternalAPIPricingManager.php';
                $externalPricingManager = new ExternalAPIPricingManager($conn);
                
                foreach ($_SESSION['cart'] as &$item) {
                    $packageSizeGb = parsePackageSizeToGb($item['bundle']);
                    $adminPrice = $externalPricingManager->getAdminPrice($item['bundle'], $item['network_type']);
                    if ($adminPrice === null) {
                        $adminPrice = getAdminPriceForPackage($conn, $packageSizeGb, $item['network_type']);
                    }
                    $item['admin_cost'] = $adminPrice ?? $item['cost']; // Fallback to store cost if admin price not found
                    $totalAdminCost += $item['admin_cost'];
                }
                unset($item);
                $totalAdminCost = round($totalAdminCost, 2);
            } else {
                // Store owner placing order - calculate admin cost
                require_once 'app/classes/ExternalAPIPricingManager.php';
                $externalPricingManager = new ExternalAPIPricingManager($conn);
                
                foreach ($_SESSION['cart'] as &$item) {
                    $packageSizeGb = parsePackageSizeToGb($item['bundle']);
                    $adminPrice = $externalPricingManager->getAdminPrice($item['bundle'], $item['network_type']);
                    if ($adminPrice === null) {
                        $adminPrice = getAdminPriceForPackage($conn, $packageSizeGb, $item['network_type']);
                    }
                    $item['admin_cost'] = $adminPrice ?? $item['cost'];
                    $totalAdminCost += $item['admin_cost'];
                }
                unset($item);
                $totalAdminCost = round($totalAdminCost, 2);
                $totalStoreCost = $totalAdminCost; // Store owner pays admin price
            }
            
            // Lock and check sub-agent's balance (if sub-agent)
            if ($isSubAgent) {
                $stmt = $conn->prepare("SELECT balance FROM agents WHERE id = ? FOR UPDATE");
                $stmt->bind_param("i", $user_id);
                $stmt->execute();
                $result = $stmt->get_result();
                $subAgentBalance = $result->fetch_assoc()['balance'];
                $stmt->close();
                
                if (!validateBalance($subAgentBalance)) {
                    $error_message = "Invalid balance detected. Please refresh and try again.";
                } elseif ($subAgentBalance < $totalStoreCost) {
                    $shortfall = $totalStoreCost - $subAgentBalance;
                    $error_message = "Insufficient balance for checkout! You need GHS " . number_format($shortfall, 2) . " more to complete this order.";
                }
            }
            
            // Lock and check store owner's balance (always needed)
            $ownerBalanceId = $isSubAgent ? $storeOwnerId : $user_id;
            $stmt = $conn->prepare("SELECT balance FROM agents WHERE id = ? FOR UPDATE");
            $stmt->bind_param("i", $ownerBalanceId);
            $stmt->execute();
            $result = $stmt->get_result();
            $ownerBalance = $result->fetch_assoc()['balance'];
            $stmt->close();
            
            if (!validateBalance($ownerBalance)) {
                $error_message = "Invalid balance detected. Please refresh and try again.";
            } elseif ($ownerBalance < $totalAdminCost) {
                $shortfall = $totalAdminCost - $ownerBalance;
                $error_message = "Insufficient balance for checkout! You need GHS " . number_format($shortfall, 2) . " more to complete this order.";
            }
            
            if (!isset($error_message)) {
                // Start database transaction
                $conn->autocommit(false);
                
                try {
                    // Debit sub-agent's balance (if sub-agent)
                    if ($isSubAgent) {
                        $newSubAgentBalance = round($subAgentBalance - $totalStoreCost, 2);
                        $stmt = $conn->prepare("UPDATE agents SET balance = ? WHERE id = ?");
                        $stmt->bind_param("di", $newSubAgentBalance, $user_id);
                        if (!$stmt->execute()) {
                            throw new Exception("Failed to update sub-agent balance");
                        }
                        $stmt->close();
                    }
                    
                    // Debit store owner's balance (admin cost)
                    $newOwnerBalance = round($ownerBalance - $totalAdminCost, 2);
                    $stmt = $conn->prepare("UPDATE agents SET balance = ? WHERE id = ?");
                    $stmt->bind_param("di", $newOwnerBalance, $ownerBalanceId);
                    if (!$stmt->execute()) {
                        throw new Exception("Failed to update store owner balance");
                    }
                    $stmt->close();
                    
                    // Record payment transaction (record sub-agent's payment if applicable, otherwise store owner's)
                    $paymentAmount = $isSubAgent ? $totalStoreCost : $totalAdminCost;
                    $paymentUserId = $isSubAgent ? $user_id : $ownerBalanceId;
                    $stmt = $conn->prepare("INSERT INTO orders_payments (user_id, total_amount) VALUES (?, ?)");
                    $stmt->bind_param("id", $paymentUserId, $paymentAmount);
                    if (!$stmt->execute()) {
                        throw new Exception("Failed to record payment");
                    }
                    $stmt->close();

                    $apiResults = [];
                    $successCount = 0;
                    $failedCount = 0;

                    foreach ($_SESSION['cart'] as $item) {
                        // Validate each cart item before processing
                        $itemValidation = validateCartItem($item);
                        if (!$itemValidation['valid']) {
                            $failedCount++;
                            $apiResults[] = "❌ " . $item['beneficiary_number'] . " - " . $itemValidation['error'];
                            continue;
                        }
                        
                        $bundle = $item['bundle'];
                        $cost = $item['cost'];
                        $beneficiaryNumber = $item['beneficiary_number'];
                        $networkType = $item['network_type'];

                        // Insert into agent_orders table (with store_id if applicable)
                        if ($userStoreId) {
                            $stmt = $conn->prepare("INSERT INTO agent_orders (agent_id, store_id, package_size, amount, beneficiary_number, network_type, status, created_at) VALUES (?, ?, ?, ?, ?, ?, 'pending', NOW())");
                            $stmt->bind_param("iissss", $user_id, $userStoreId, $bundle, $cost, $beneficiaryNumber, $networkType);
                        } else {
                            $stmt = $conn->prepare("INSERT INTO agent_orders (agent_id, package_size, amount, beneficiary_number, network_type, status, created_at) VALUES (?, ?, ?, ?, ?, 'pending', NOW())");
                            $stmt->bind_param("issss", $user_id, $bundle, $cost, $beneficiaryNumber, $networkType);
                        }
                        if (!$stmt->execute()) {
                            throw new Exception("Failed to create order for $beneficiaryNumber");
                        }
                        $agentOrderId = $stmt->insert_id;
                        $stmt->close();

                        // Log balance history for sub-agent (if applicable)
                        if ($isSubAgent) {
                            $orderStoreCost = $item['cost']; // Store owner's price
                            BalanceHistory::log($conn, $user_id, -1 * $orderStoreCost, 'order', $agentOrderId, $beneficiaryNumber, $subAgentBalance, $newSubAgentBalance);
                        }
                        
                        // Log balance history for store owner (admin cost)
                        $orderAdminCost = $item['admin_cost'] ?? $item['cost'];
                        BalanceHistory::log($conn, $ownerBalanceId, -1 * $orderAdminCost, 'order', $agentOrderId, $beneficiaryNumber, $ownerBalance, $newOwnerBalance);

                        // Create external API order entry for MTN orders (for profit tracking)
                        if (strtolower($networkType) === 'mtn') {
                            try {
                                $externalPricingManager = new ExternalAPIPricingManager($conn);
                                $adminPrice = $externalPricingManager->getAdminPrice($bundle, 'mtn');
                                $externalPrice = $externalPricingManager->getExternalPrice($bundle, 'mtn');
                                
                                // Only create external API order if pricing is available
                                if ($adminPrice !== null && $externalPrice !== null) {
                                    $profit = $adminPrice - $externalPrice;
                                    
                                    // Parse package size to GB
                                    $packageSizeGb = 0;
                                    if (preg_match('/(\d+(?:\.\d+)?)\s*GB/i', $bundle, $matches)) {
                                        $packageSizeGb = (float)$matches[1];
                                    } elseif (preg_match('/(\d+(?:\.\d+)?)\s*MB/i', $bundle, $matches)) {
                                        $packageSizeGb = round(((float)$matches[1]) / 1024, 4);
                                    } else {
                                        $num = floatval(preg_replace('/[^0-9.]/', '', $bundle));
                                        $packageSizeGb = $num > 0 ? $num : 0;
                                    }
                                    
                                    // Format package label
                                    $packageLabel = $bundle; // Use bundle as-is (already formatted)
                                    
                                    $externalOrderStmt = $conn->prepare("
                                        INSERT INTO external_api_orders 
                                        (agent_id, network_type, package_size, package_size_gb, beneficiary_number, 
                                         admin_price, external_api_price, profit, status, created_at)
                                        VALUES (?, 'mtn', ?, ?, ?, ?, ?, ?, 'pending', NOW())
                                    ");
                                    
                                    if ($externalOrderStmt) {
                                        $externalOrderStmt->bind_param("isddsdd", $user_id, $packageLabel, $packageSizeGb, $beneficiaryNumber, $adminPrice, $externalPrice, $profit);
                                        if ($externalOrderStmt->execute()) {
                                            $externalOrderId = $conn->insert_id;
                                            error_log("External API Order created: ID $externalOrderId for agent_order $agentOrderId");
                                        } else {
                                            error_log("Failed to create external API order: " . $externalOrderStmt->error);
                                        }
                                        $externalOrderStmt->close();
                                    }
                                } else {
                                    error_log("External API pricing not available for package: $bundle (MTN). Admin: " . ($adminPrice ?? 'null') . ", External: " . ($externalPrice ?? 'null'));
                                }
                            } catch (Exception $e) {
                                error_log("Error creating external API order: " . $e->getMessage());
                                // Don't fail the main order if external API order creation fails
                            }
                        }

                        // Check if we should use external API for this network
                        if (shouldUseExternalAPI($networkType)) {
                            $apiService = new ExternalAPIService($networkType);
                            $capacity = $apiService->convertPackageSize($bundle);
                            $cleanPhone = $apiService->validatePhoneNumber($beneficiaryNumber);
                            
                            if ($cleanPhone) {
                                // Call external API with agent order ID for tracking
                                $apiResponse = $apiService->purchaseData($cleanPhone, $networkType, $capacity, 'wallet', $agentOrderId);
                                
                                if ($apiResponse['success']) {
                                    // Get the external API's transaction reference
                                    $externalApiReference = $apiResponse['data']['data']['transactionReference'] ?? null;
                                    $purchaseId = $apiResponse['data']['data']['purchaseId'] ?? null;
                                    
                                    $dataWebsiteTransactionId = $purchaseId ? (string)$purchaseId : null;
                                    
                                    // Update agent_orders with external transaction details
                                    $updateStmt = $conn->prepare("UPDATE agent_orders SET status = 'pending', external_transaction_id = ?, external_reference = ? WHERE id = ?");
                                    $updateStmt->bind_param("ssi", $dataWebsiteTransactionId, $externalApiReference, $agentOrderId);
                                    $updateStmt->execute();
                                    $updateStmt->close();
                                    
                                    $successCount++;
                                    $apiResults[] = "✅ $beneficiaryNumber ($bundle) - API Success (Pending Delivery)";
                                } else {
                                    // API call failed
                                    $updateStmt = $conn->prepare("UPDATE agent_orders SET status = 'failed' WHERE id = ?");
                                    $updateStmt->bind_param("i", $agentOrderId);
                                    $updateStmt->execute();
                                    $updateStmt->close();
                                    
                                    $errorMsg = $apiResponse['error'] ?? 'Unknown API error';
                                    $failedCount++;
                                    $apiResults[] = "❌ $beneficiaryNumber ($bundle) - API Failed: $errorMsg";
                                    
                                    // Send SMS alert to admins
                                    try {
                                        $adminNotifier = new AdminNotificationManager($conn);
                                        $orderDetails = [
                                            'beneficiary_number' => $beneficiaryNumber,
                                            'package_size' => $bundle,
                                            'error' => $errorMsg,
                                            'network_type' => $networkType
                                        ];
                                        $adminNotifier->sendOrderFailedSMS($agentOrderId, $orderDetails);
                                    } catch (Exception $e) {
                                        error_log("Failed to send order failure SMS alert from user dashboard: " . $e->getMessage());
                                    }
                                }
                            } else {
                                $failedCount++;
                                $apiResults[] = "❌ $beneficiaryNumber ($bundle) - Invalid phone number";
                            }
                        } else {
                            // External API not enabled for this network
                            $successCount++;
                            $apiResults[] = "✅ $beneficiaryNumber ($bundle) - Order saved (No external API)";
                        }
                    }

                    // Commit transaction
                    $conn->commit();
                    $conn->autocommit(true);
                    
                    $_SESSION['cart'] = [];
                    
                    // Create detailed success message for payment/checkout
                    $message = "🎉 Payment successful! Your order has been processed. ";
                    if ($successCount > 0) {
                        $message .= "$successCount order(s) are being processed. ";
                    }
                    if ($failedCount > 0) {
                        $message .= "$failedCount order(s) encountered issues. ";
                    }
                    $message .= "Check your order history for detailed status.";
                    
                    // Store success message in session for display after redirect
                    $_SESSION['checkout_success_message'] = $message;
                    
                    // Store API results in session for detailed view (optional)
                    $_SESSION['last_checkout_results'] = $apiResults;
                    
                    // Clear checkout in progress flag
                    unset($_SESSION['checkout_in_progress']);
                    unset($_SESSION['submission_timestamps']['checkout_in_progress']);
                    
                    header('Location: user_index.php?page=dashboard&checkout=success');
                    exit();
                    
                } catch (Exception $e) {
                    // Rollback transaction on error
                    $conn->rollback();
                    $conn->autocommit(true);
                    
                    // Clear checkout in progress flag on error
                    unset($_SESSION['checkout_in_progress']);
                    unset($_SESSION['submission_timestamps']['checkout_in_progress']);
                    
                    error_log("Checkout failed: " . $e->getMessage());
                    $error_message = "Checkout failed. Please try again.";
                }
            }
        }
    }
}

// Calculate total cost with validation
$totalCost = 0;
if (!empty($_SESSION['cart'])) {
    $cartValidation = validateCart($_SESSION['cart']);
    if ($cartValidation['valid']) {
        $totalCost = $cartValidation['total_cost'];
    } else {
        // Clear invalid cart
        $_SESSION['cart'] = [];
        $error_message = "Cart contains invalid items and has been cleared: " . $cartValidation['error'];
    }
}

// Handle top-up success message
if (isset($_GET['topup'])) {
    if ($_GET['topup'] === 'success' && isset($_GET['amount'])) {
        $topupAmount = floatval($_GET['amount']);
        $success_message = "Top-up successful! Your account has been credited with GHS " . number_format($topupAmount, 2);
    } elseif ($_GET['topup'] === 'already_processed') {
        $ref = isset($_GET['ref']) ? htmlspecialchars($_GET['ref']) : 'N/A';
        $error_message = "⚠️ Payment Already Processed: This payment has already been credited to your account. Reference: $ref. If you believe this is an error, please contact support.";
    }
}

// Handle checkout success message
if (isset($_GET['checkout']) && $_GET['checkout'] === 'success') {
    if (isset($_SESSION['checkout_success_message'])) {
        $success_message = $_SESSION['checkout_success_message'];
        unset($_SESSION['checkout_success_message']); // Clear after displaying
    } else {
        $success_message = "🎉 Payment successful! Your orders have been processed. Check your order history for detailed status.";
    }
}

// Handle notification success messages
if (isset($_GET['notification'])) {
    switch ($_GET['notification']) {
        case 'marked_read':
            $success_message = "Notification marked as read!";
            break;
        case 'all_marked_read':
            $success_message = "All notifications marked as read!";
            break;
    }
}
?>


<!-- Professional Balance Overview Card -->
<div class="relative overflow-hidden glass-card rounded-xl sm:rounded-2xl p-3 sm:p-4 lg:p-5 mb-3 sm:mb-4 shadow-xl border-2 border-emerald-500/30 backdrop-blur-xl bg-gradient-to-br from-slate-800/90 via-slate-900/90 to-slate-800/90 card-hover">
    <!-- Animated background pattern -->
    <div class="absolute inset-0 opacity-5">
        <div class="absolute top-0 left-0 w-full h-full" style="background-image: radial-gradient(circle at 2px 2px, rgba(16, 185, 129, 0.4) 1px, transparent 0); background-size: 32px 32px;"></div>
    </div>
    
    <!-- Decorative gradient orbs -->
    <div class="absolute top-0 right-0 w-24 h-24 sm:w-32 sm:h-32 bg-gradient-to-br from-emerald-500/20 to-green-500/10 rounded-full blur-3xl"></div>
    <div class="absolute bottom-0 left-0 w-20 h-20 sm:w-24 sm:h-24 bg-gradient-to-tr from-teal-500/20 to-emerald-500/10 rounded-full blur-2xl"></div>
    
    <div class="relative z-10 flex flex-col lg:flex-row lg:items-center lg:justify-between gap-3 lg:gap-0">
        <div class="flex items-center space-x-3 sm:space-x-4">
            <!-- Enhanced Wallet Icon -->
            <div class="relative w-14 h-14 sm:w-16 sm:h-16 bg-gradient-to-br from-emerald-500 via-green-500 to-teal-600 rounded-lg sm:rounded-xl flex items-center justify-center shadow-xl group flex-shrink-0">
                <div class="absolute inset-0 bg-gradient-to-br from-white/20 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 rounded-lg sm:rounded-xl"></div>
                <i class="fas fa-wallet text-white text-xl sm:text-2xl relative z-10 icon-glow"></i>
                <div class="absolute inset-0 bg-emerald-400/30 blur-2xl group-hover:blur-3xl transition-all duration-300"></div>
            </div>
            
            <!-- Balance Info -->
            <div class="min-w-0 flex-1">
                <p class="text-[10px] xs:text-xs text-gray-400 mb-0.5 font-semibold uppercase tracking-wider">Available Balance</p>
                <p class="text-2xl sm:text-3xl lg:text-4xl font-bold text-white tracking-tight leading-tight">
                    <?php echo number_format($balance, 2); ?> 
                    <span class="text-sm sm:text-base lg:text-lg text-gray-400 font-normal">GHS</span>
                </p>
                <div class="flex items-center gap-1.5 text-[10px] xs:text-xs text-emerald-300/80">
                    <i class="fas fa-circle text-[4px]"></i>
                    <span>Account Active</span>
                </div>
            </div>
        </div>
        
        <!-- Enhanced Cart Total Display -->
        <?php if (!empty($_SESSION['cart'])): ?>
        <div class="relative text-left lg:text-right px-3 sm:px-4 py-2.5 sm:py-3 bg-gradient-to-br from-blue-500/25 via-indigo-500/20 to-purple-500/25 rounded-lg sm:rounded-xl border-2 border-blue-500/40 backdrop-blur-md shadow-lg w-full lg:w-auto">
            <div class="absolute inset-0 bg-gradient-to-br from-white/5 to-transparent rounded-lg sm:rounded-xl"></div>
            <div class="relative z-10">
                <p class="text-[10px] xs:text-xs text-gray-300 mb-0.5 font-semibold flex items-center lg:justify-end uppercase tracking-wider">
                    <i class="fas fa-shopping-cart mr-1.5 text-blue-400"></i>Cart Total
                </p>
                <p class="text-lg sm:text-xl lg:text-2xl font-bold text-blue-300 leading-tight">
                    <?php echo number_format($totalCost, 2); ?> 
                    <span class="text-xs sm:text-sm text-gray-400 font-normal">GHS</span>
                </p>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>


<!-- Quick Stats -->
<div class="grid grid-cols-2 gap-2.5 sm:gap-3 mb-3 sm:mb-4">
    <div class="glass-card-light rounded-lg p-2.5 sm:p-3 shadow-lg border-2 border-slate-600/50 bg-slate-800/40 card-hover hover:border-blue-500/40 transition-all duration-300">
        <div class="flex items-center space-x-2 sm:space-x-2.5">
            <div class="w-9 h-9 sm:w-10 sm:h-10 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-lg flex items-center justify-center shadow-md flex-shrink-0">
                <i class="fas fa-shopping-cart text-white text-sm sm:text-base"></i>
            </div>
            <div class="min-w-0 flex-1">
                <p class="text-[10px] xs:text-xs text-gray-400 font-medium mb-0.5 truncate">Cart Items</p>
                <p class="text-base sm:text-lg lg:text-xl font-bold text-white"><?php echo count($_SESSION['cart']); ?></p>
            </div>
        </div>
    </div>
    <div class="glass-card-light rounded-lg p-2.5 sm:p-3 shadow-lg border-2 border-slate-600/50 bg-slate-800/40 card-hover hover:border-purple-500/40 transition-all duration-300">
        <a href="?page=today_orders" class="flex items-center space-x-2 sm:space-x-2.5 group w-full">
            <div class="w-9 h-9 sm:w-10 sm:h-10 bg-gradient-to-br from-purple-500 to-pink-600 rounded-lg flex items-center justify-center shadow-md group-hover:scale-110 transition-transform flex-shrink-0">
                <i class="fas fa-chart-line text-white text-sm sm:text-base"></i>
            </div>
            <div class="min-w-0 flex-1">
                <p class="text-[10px] xs:text-xs text-gray-400 font-medium mb-0.5 truncate">Today's Orders</p>
                <p class="text-base sm:text-lg lg:text-xl font-bold text-white group-hover:text-purple-300 transition-colors">View →</p>
            </div>
        </a>
    </div>
</div>

<!-- Order Creation Section -->
<div class="glass-card rounded-xl sm:rounded-2xl p-3 sm:p-4 lg:p-5 mb-3 sm:mb-4 shadow-lg border border-slate-600/50">
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-3 sm:mb-4 gap-2.5 sm:gap-0">
        <h2 class="text-sm sm:text-base lg:text-lg font-bold text-white">Create Orders</h2>
        <div class="flex space-x-1 bg-slate-700/50 p-0.5 sm:p-1 rounded-lg w-full sm:w-auto">
            <button onclick="showTab('single')" class="tab-btn active flex-1 sm:flex-none px-2.5 sm:px-3 lg:px-4 py-2 rounded-md text-xs sm:text-sm font-medium transition-all min-h-[40px] sm:min-h-[36px]" id="single-tab">
                <i class="fas fa-plus mr-1 sm:mr-1.5"></i>Single
            </button>
            <button onclick="showTab('bulk')" class="tab-btn flex-1 sm:flex-none px-2.5 sm:px-3 lg:px-4 py-2 rounded-md text-xs sm:text-sm font-medium transition-all min-h-[40px] sm:min-h-[36px]" id="bulk-tab">
                <i class="fas fa-paste mr-1 sm:mr-1.5"></i>Bulk
            </button>
        </div>
    </div>
            <button onclick="showTab('bulk')" class="tab-btn flex-1 sm:flex-none px-3 sm:px-4 py-2 rounded-md text-xs sm:text-sm font-medium transition-all" id="bulk-tab">
                <i class="fas fa-paste mr-1 sm:mr-2"></i>Bulk
            </button>
        </div>
    </div>

    <!-- Single Order Form -->
    <div id="single-content" class="tab-content">
        <form action="" method="post" class="space-y-3 sm:space-y-4">
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 sm:gap-4">
                <div class="sm:col-span-2 lg:col-span-1">
                    <label class="block text-xs font-medium text-gray-300 mb-1.5">
                        <i class="fas fa-network-wired mr-1.5"></i>Network
                    </label>
                    <select name="network_type" id="network_type" class="w-full border border-slate-600 bg-[#0f172a]/80 rounded-lg px-3 py-2.5 sm:py-3 text-sm text-white focus:ring-2 focus:ring-amber-500 focus:border-amber-500 transition-all min-h-[44px]" required onchange="updatePhonePlaceholder()">
                        <option value="">Select Network</option>
                        <option value="mtn">MTN</option>
                    </select>
                </div>
                <div class="sm:col-span-2 lg:col-span-1">
                    <label class="block text-xs font-medium text-gray-300 mb-1.5">
                        <i class="fas fa-mobile-alt mr-1.5"></i>Phone Number
                    </label>
                    <input type="text" name="beneficiary_number" id="beneficiary_number" 
                           pattern="[0-9]{10}" maxlength="10"
                           class="w-full border border-slate-600 bg-[#0f172a]/80 rounded-lg px-3 py-2.5 sm:py-3 text-sm text-white focus:ring-2 focus:ring-amber-500 focus:border-amber-500 transition-all min-h-[44px]" 
                           placeholder="0247965501" required>
                    <p class="text-[10px] text-gray-400 mt-1">Enter 10-digit phone number</p>
                    <div id="phone_validation" class="mt-1 text-[10px]"></div>
                </div>
                <div class="sm:col-span-2 lg:col-span-1">
                    <label class="block text-xs font-medium text-gray-300 mb-1.5">
                        <i class="fas fa-database mr-1.5"></i>Package Size (GB)
                    </label>
                    <input type="number" name="bundle_size" id="bundle_size" required
                           placeholder="e.g., 1, 2, 3, 5"
                           min="0.1" step="0.1"
                           class="w-full border border-slate-600 bg-[#0f172a]/80 rounded-lg px-3 py-2.5 sm:py-3 text-sm text-white focus:ring-2 focus:ring-amber-500 focus:border-amber-500 transition-all min-h-[44px]"
                           autocomplete="off">
                    <p class="text-[10px] text-gray-400 mt-1">Price: <span id="calculated_price" class="font-semibold text-green-400">GHS 0.00</span></p>
                    <div id="packageError" class="hidden mt-1.5 text-xs text-red-400">
                        <i class="fas fa-exclamation-circle mr-1"></i>
                        <span id="packageErrorText"></span>
                    </div>
                </div>
            </div>
            <button type="submit" name="add_to_cart" class="w-full bg-gradient-to-r from-green-500 to-green-600 text-white py-2.5 sm:py-3 rounded-lg font-medium hover:from-green-600 hover:to-green-700 transition-all hover-glow text-sm shadow-lg min-h-[44px] flex items-center justify-center">
                <i class="fas fa-cart-plus mr-2"></i>Add to Cart
            </button>
        </form>
    </div>

    <!-- Bulk Order Form -->
    <div id="bulk-content" class="tab-content hidden">
        <form action="" method="post" class="space-y-3 sm:space-y-4">
            <div>
                <label class="block text-xs font-medium text-gray-300 mb-1.5">
                    <i class="fas fa-network-wired mr-1.5"></i>Network Type
                </label>
                <select name="network_type" class="w-full border border-slate-600 bg-[#0f172a]/80 rounded-lg px-3 py-2.5 sm:py-3 text-sm text-white focus:ring-2 focus:ring-amber-500 focus:border-amber-500 transition-all min-h-[44px]" required>
                    <option value="">Select Network</option>
                    <option value="mtn">MTN</option>
                </select>
            </div>
            <div>
                <label class="block text-xs font-medium text-gray-300 mb-1.5">
                    <i class="fas fa-paste mr-1.5"></i>Bulk Orders
                </label>
                <textarea name="bulk_orders_text" rows="5" class="w-full border border-slate-600 bg-[#0f172a]/80 rounded-lg px-3 py-2.5 text-sm text-white focus:ring-2 focus:ring-amber-500 focus:border-amber-500 resize-none transition-all" placeholder="0247965501 8&#10;0246145475 2&#10;0598544791 5" required></textarea>
                <p class="text-[10px] text-gray-400 mt-1">
                    <i class="fas fa-info-circle mr-1"></i>Format: phone_number space bundle_size_in_GB
                </p>
            </div>
            <button type="submit" name="add_bulk_orders" class="w-full bg-blue-500 text-white py-2.5 sm:py-3 rounded-lg font-medium hover:bg-blue-600 transition-colors text-sm shadow-lg min-h-[44px] flex items-center justify-center">
                <i class="fas fa-plus mr-2"></i>Add Bulk Orders
            </button>
        </form>
    </div>
</div>

<!-- Rejected Orders Display -->
<?php if (!empty($_SESSION['bulk_rejected_orders'])): ?>
<div class="bg-red-50 border border-red-200 rounded-2xl p-6 mb-6">
    <div class="flex items-center justify-between mb-4">
        <h3 class="text-lg font-bold text-red-800">
            <i class="fas fa-exclamation-triangle mr-2"></i>Rejected Orders
        </h3>
        <span class="bg-red-100 text-red-700 px-3 py-1 rounded-full text-sm font-medium">
            <?php echo count($_SESSION['bulk_rejected_orders']); ?> rejected
        </span>
    </div>
    
    <div class="space-y-2 max-h-60 overflow-y-auto">
        <?php foreach ($_SESSION['bulk_rejected_orders'] as $rejectedOrder): ?>
        <div class="glass-card-light border border-red-500/30 rounded-lg p-3">
            <div class="flex items-start gap-3">
                <i class="fas fa-times-circle text-red-500 mt-0.5"></i>
                <span class="text-sm text-red-700"><?php echo htmlspecialchars($rejectedOrder); ?></span>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    
    <div class="mt-4 pt-4 border-t border-red-200">
        <p class="text-sm text-red-600">
            <i class="fas fa-info-circle mr-1"></i>
            Only orders with valid package sizes that exist in the system are added to cart.
        </p>
        <form action="" method="post" class="mt-3">
            <button type="submit" name="clear_rejected_orders" class="text-red-600 hover:text-red-800 text-sm font-medium">
                <i class="fas fa-times mr-1"></i>Clear Rejected Orders
            </button>
        </form>
    </div>
</div>
<?php endif; ?>

<!-- Cart Section -->
<?php if (!empty($_SESSION['cart'])): ?>
<div class="glass-card rounded-xl sm:rounded-2xl p-3 sm:p-4 lg:p-5 mb-3 sm:mb-4 shadow-xl border border-slate-600/50 backdrop-blur-xl bg-slate-800/60">
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-3 sm:mb-4 pb-3 border-b border-slate-600/50 gap-2.5 sm:gap-0">
        <div class="flex items-center space-x-2.5 sm:space-x-3">
            <div class="w-9 h-9 sm:w-10 sm:h-10 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-lg flex items-center justify-center shadow-lg flex-shrink-0">
                <i class="fas fa-shopping-cart text-white text-sm sm:text-base"></i>
            </div>
            <div class="min-w-0 flex-1">
                <h3 class="text-sm sm:text-base lg:text-lg font-bold text-white">Shopping Cart</h3>
                <p class="text-[10px] xs:text-xs text-gray-400">Review your order before checkout</p>
            </div>
        </div>
        <div class="flex items-center space-x-2">
            <span class="bg-gradient-to-r from-blue-500/20 to-indigo-500/20 text-blue-300 px-2 sm:px-2.5 py-1 rounded-lg text-[10px] xs:text-xs font-semibold border border-blue-500/30 backdrop-blur-sm whitespace-nowrap">
                <i class="fas fa-box mr-1"></i><?php echo count($_SESSION['cart']); ?> <?php echo count($_SESSION['cart']) === 1 ? 'item' : 'items'; ?>
            </span>
        </div>
    </div>
    
    <div class="space-y-3 sm:space-y-3">
        <?php foreach ($_SESSION['cart'] as $index => $item): ?>
        <div class="glass-card-light rounded-xl p-3 sm:p-5 border-2 border-slate-600/50 bg-slate-700/40 hover:border-slate-500/60 hover:bg-slate-700/60 transition-all duration-200 hover:shadow-lg group cart-item cart-item-hover">
            <!-- Mobile Layout: Stacked -->
            <div class="flex flex-col sm:hidden space-y-3">
                <!-- Top Row: Icon, Phone, Network -->
                <div class="flex items-start space-x-3">
                    <div class="w-12 h-12 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-xl flex items-center justify-center shadow-md flex-shrink-0">
                        <i class="fas fa-mobile-alt text-white text-base"></i>
                    </div>
                    <div class="flex-1 min-w-0">
                        <div class="flex flex-col sm:flex-row sm:items-center sm:space-x-3 mb-2 gap-2">
                            <p class="font-bold text-white text-base break-all"><?php echo htmlspecialchars($item['beneficiary_number']); ?></p>
                            <span class="inline-flex items-center px-2.5 py-1 rounded-lg text-xs font-bold w-fit
                                <?php 
                                switch($item['network_type']) {
                                    case 'mtn': echo 'bg-yellow-500/20 text-yellow-300 border-2 border-yellow-500/40'; break;
                                    case 'telecel': echo 'bg-red-500/20 text-red-300 border-2 border-red-500/40'; break;
                                    case 'airtel_tigo': echo 'bg-orange-500/20 text-orange-300 border-2 border-orange-500/40'; break;
                                    default: echo 'bg-gray-500/20 text-gray-300 border-2 border-gray-500/40';
                                }
                                ?>">
                                <i class="fas fa-network-wired mr-1.5"></i><?php echo strtoupper(str_replace('_', ' ', $item['network_type'])); ?>
                            </span>
                        </div>
                        <div class="flex items-center">
                            <p class="text-sm text-gray-300 flex items-center">
                                <i class="fas fa-database mr-2 text-blue-400"></i>
                                <span class="font-semibold"><?php echo htmlspecialchars($item['bundle']); ?></span>
                            </p>
                        </div>
                    </div>
                </div>
                <!-- Bottom Row: Price and Remove Button -->
                <div class="flex items-center justify-between pt-2 border-t border-slate-600/30">
                    <div>
                        <p class="text-xs text-gray-400 mb-0.5">Price</p>
                        <p class="text-lg font-bold text-green-400"><?php echo htmlspecialchars(number_format($item['cost'], 2)); ?> <span class="text-xs text-gray-400">GHS</span></p>
                    </div>
                    <form action="" method="post" class="flex-shrink-0">
                        <input type="hidden" name="item_index" value="<?php echo $index; ?>">
                        <button type="submit" name="remove_item" class="w-11 h-11 flex items-center justify-center bg-red-500/20 hover:bg-red-500/30 text-red-400 hover:text-red-300 rounded-lg border-2 border-red-500/40 hover:border-red-500/60 transition-all duration-200 active:scale-95">
                            <i class="fas fa-trash-alt text-sm"></i>
                        </button>
                    </form>
                </div>
            </div>
            
            <!-- Desktop Layout: Horizontal -->
            <div class="hidden sm:flex items-center justify-between">
                <div class="flex items-center space-x-4 flex-1 min-w-0">
                    <div class="w-14 h-14 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-xl flex items-center justify-center shadow-md group-hover:scale-110 transition-transform duration-200 flex-shrink-0">
                        <i class="fas fa-mobile-alt text-white text-lg"></i>
                    </div>
                    <div class="flex-1 min-w-0">
                        <div class="flex items-center space-x-3 mb-2 flex-wrap">
                            <p class="font-bold text-white text-lg break-all"><?php echo htmlspecialchars($item['beneficiary_number']); ?></p>
                            <span class="inline-flex items-center px-3 py-1 rounded-lg text-xs font-bold flex-shrink-0
                                <?php 
                                switch($item['network_type']) {
                                    case 'mtn': echo 'bg-yellow-500/20 text-yellow-300 border-2 border-yellow-500/40'; break;
                                    case 'telecel': echo 'bg-red-500/20 text-red-300 border-2 border-red-500/40'; break;
                                    case 'airtel_tigo': echo 'bg-orange-500/20 text-orange-300 border-2 border-orange-500/40'; break;
                                    default: echo 'bg-gray-500/20 text-gray-300 border-2 border-gray-500/40';
                                }
                                ?>">
                                <i class="fas fa-network-wired mr-1.5"></i><?php echo strtoupper(str_replace('_', ' ', $item['network_type'])); ?>
                            </span>
                        </div>
                        <div class="flex items-center space-x-4">
                            <p class="text-sm text-gray-300 flex items-center">
                                <i class="fas fa-database mr-2 text-blue-400"></i>
                                <span class="font-semibold"><?php echo htmlspecialchars($item['bundle']); ?></span>
                            </p>
                        </div>
                    </div>
                </div>
                <div class="flex items-center space-x-4 ml-4 flex-shrink-0">
                    <div class="text-right">
                        <p class="text-xs text-gray-400 mb-1">Price</p>
                        <p class="text-xl font-bold text-green-400"><?php echo htmlspecialchars(number_format($item['cost'], 2)); ?> <span class="text-sm text-gray-400">GHS</span></p>
                    </div>
                    <form action="" method="post" class="flex-shrink-0">
                        <input type="hidden" name="item_index" value="<?php echo $index; ?>">
                        <button type="submit" name="remove_item" class="w-10 h-10 flex items-center justify-center bg-red-500/20 hover:bg-red-500/30 text-red-400 hover:text-red-300 rounded-lg border-2 border-red-500/40 hover:border-red-500/60 transition-all duration-200 hover:scale-110 group/remove">
                            <i class="fas fa-trash-alt text-sm group-hover/remove:scale-110 transition-transform"></i>
                        </button>
                    </form>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    
    <!-- Cart Summary -->
    <div class="mt-4 sm:mt-6 pt-4 sm:pt-6 border-t border-slate-600/50">
        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 sm:gap-0">
            <div>
                <p class="text-xs sm:text-sm text-gray-400">Total Items</p>
                <p class="text-base sm:text-lg font-semibold text-white"><?php echo count($_SESSION['cart']); ?></p>
            </div>
            <div class="text-left sm:text-right">
                <p class="text-xs sm:text-sm text-gray-400">Total Amount</p>
                <p class="text-xl sm:text-2xl font-bold text-green-400"><?php echo number_format($totalCost, 2); ?> <span class="text-sm sm:text-base text-gray-400">GHS</span></p>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Recent Activity -->
<!-- <?php if (!empty($_SESSION['last_checkout_results'])): ?>
<div class="bg-white rounded-2xl p-6 mb-6 shadow-lg border border-gray-200/50">
    <h3 class="text-lg font-bold text-gray-900 mb-4">
        <i class="fas fa-list-ul mr-2"></i>Recent Activity
    </h3>
    <div class="space-y-2">
        <?php foreach (array_slice($_SESSION['last_checkout_results'], 0, 5) as $entry): ?>
        <div class="flex items-start gap-3 text-sm text-gray-700">
            <span class="mt-0.5 text-gray-400">•</span>
            <span><?php echo htmlspecialchars($entry); ?></span>
        </div>
        <?php endforeach; ?>
    </div>
</div>
<?php endif; ?> -->

<!-- Make Payment Button -->
<?php if (!empty($_SESSION['cart'])): ?>
<div class="sticky bottom-0 left-0 right-0 z-50 p-4 bg-gradient-to-t from-slate-900/95 via-slate-900/90 to-transparent backdrop-blur-xl border-t border-slate-700/50 sm:bg-transparent sm:border-t-0 sm:p-0 sm:relative sm:bottom-auto sm:mt-6">
    <form action="" method="post" class="max-w-2xl mx-auto sm:max-w-none">
        <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
        <button type="submit" name="checkout" class="w-full bg-gradient-to-r from-emerald-500 via-green-500 to-emerald-600 text-white px-8 py-4 rounded-xl font-bold text-lg shadow-2xl hover:from-emerald-600 hover:via-green-600 hover:to-emerald-700 transition-all duration-200 transform hover:scale-[1.02] hover:shadow-emerald-500/50 flex items-center justify-center space-x-3 group">
            <i class="fas fa-credit-card text-xl group-hover:scale-110 transition-transform"></i>
            <span>Proceed to Checkout</span>
            <span class="bg-white/20 px-3 py-1 rounded-lg text-base font-bold"><?php echo number_format($totalCost, 2); ?> GHS</span>
        </button>
    </form>
</div>
<?php endif; ?>

<script>
    const networkPrefixes = {
        'mtn': ['024', '025', '053', '054', '055', '059'],
        'telecel': ['020', '050'],
        'airtel_tigo': ['027', '057', '026', '056', '023']
    };

    const networkNames = {
        'mtn': 'MTN',
        'telecel': 'Telecel (Vodafone)',
        'airtel_tigo': 'AirtelTigo'
    };

    function showTab(tabName) {
        // Hide all tab contents
        document.querySelectorAll('.tab-content').forEach(content => {
            content.classList.add('hidden');
        });
        
        // Remove active class from all tabs
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.classList.remove('bg-white', 'text-primary-600', 'shadow-sm');
            btn.classList.add('text-gray-600');
        });
        
        // Show selected tab content
        document.getElementById(tabName + '-content').classList.remove('hidden');
        
        // Add active class to selected tab
        document.getElementById(tabName + '-tab').classList.add('bg-white', 'text-primary-600', 'shadow-sm');
        document.getElementById(tabName + '-tab').classList.remove('text-gray-600');
    }

    // Global function for onchange handler
    function updatePhonePlaceholder() {
        const networkSelectEl = document.getElementById('network_type');
        const phoneInputEl = document.getElementById('beneficiary_number');
        if (!networkSelectEl || !phoneInputEl) return;
        
        const network = networkSelectEl.value;
        
        if (network && networkPrefixes[network]) {
            const prefix = networkPrefixes[network][0];
            phoneInputEl.placeholder = `e.g., ${prefix}1234567`;
            phoneInputEl.title = `Enter ${networkNames[network]} number starting with: ${networkPrefixes[network].join(', ')}`;
        } else {
            phoneInputEl.placeholder = '0247965501';
            phoneInputEl.title = 'Enter phone number';
        }
        
        const validationDiv = document.getElementById('phone_validation');
        if (validationDiv) validationDiv.innerHTML = '';
    }

    function validatePhoneNumber() {
        const phoneInputEl = document.getElementById('beneficiary_number');
        const networkSelect = document.getElementById('network_type');
        const validationDiv = document.getElementById('phone_validation');
        
        if (!phoneInputEl || !networkSelect || !validationDiv) return;
        
        const phone = phoneInputEl.value.trim();
        const network = networkSelect.value;
        
        if (!phone) {
            validationDiv.innerHTML = '';
            phoneInputEl.classList.remove('border-red-500', 'border-green-500');
            return;
        }
        
        const cleanPhone = phone.replace(/\D/g, '');
        
        // Must be exactly 10 digits
        if (cleanPhone.length !== 10) {
            validationDiv.innerHTML = '<span class="text-red-600"><i class="fas fa-times-circle mr-1"></i>Phone number must be exactly 10 digits</span>';
            phoneInputEl.classList.remove('border-green-500');
            phoneInputEl.classList.add('border-red-500');
            return;
        }
        
        // Must start with 0
        if (cleanPhone.charAt(0) !== '0') {
            validationDiv.innerHTML = '<span class="text-red-600"><i class="fas fa-times-circle mr-1"></i>Phone number must start with 0 (e.g., 0247965501)</span>';
            phoneInputEl.classList.remove('border-green-500');
            phoneInputEl.classList.add('border-red-500');
            return;
        }
        
        if (!network) {
            validationDiv.innerHTML = '<span class="text-yellow-600"><i class="fas fa-info-circle mr-1"></i>Select network to validate prefix</span>';
            phoneInputEl.classList.remove('border-red-500', 'border-green-500');
            return;
        }
        
        const prefix = cleanPhone.substring(0, 3);
        
        if (networkPrefixes[network] && networkPrefixes[network].includes(prefix)) {
            validationDiv.innerHTML = '<span class="text-green-600"><i class="fas fa-check-circle mr-1"></i>Valid ' + networkNames[network] + ' number</span>';
            phoneInputEl.classList.remove('border-red-500');
            phoneInputEl.classList.add('border-green-500');
        } else {
            const validPrefixes = networkPrefixes[network] ? networkPrefixes[network].join(', ') : '';
            validationDiv.innerHTML = '<span class="text-red-600"><i class="fas fa-times-circle mr-1"></i>Invalid prefix for ' + networkNames[network] + '. Valid prefixes: ' + validPrefixes + '</span>';
            phoneInputEl.classList.remove('border-green-500');
            phoneInputEl.classList.add('border-red-500');
        }
    }

    // Event listeners
    document.addEventListener('DOMContentLoaded', function() {
        const phoneInput = document.getElementById('beneficiary_number');
        const networkSelect = document.getElementById('network_type');
        
        // Package validation - ensure elements exist (moved inside DOMContentLoaded)
        const bundleSizeInput = document.getElementById('bundle_size');
        const packageError = document.getElementById('packageError');
        const packageErrorText = document.getElementById('packageErrorText');
        const calculatedPriceEl = document.getElementById('calculated_price');
        let isValidPackage = false;
        let packageValidationTimeout = null;
        
        // Helper function to safely update price
        function updatePriceDisplay(price, isError = false) {
            if (!calculatedPriceEl) {
                console.error('calculated_price element not found');
                return;
            }
            
            if (isError || price === 0 || price === null || price === undefined) {
                calculatedPriceEl.textContent = "GHS 0.00";
                calculatedPriceEl.classList.remove('text-yellow-400', 'text-green-400');
            } else {
                const priceNum = typeof price === 'number' ? price : parseFloat(price) || 0;
                if (priceNum > 0) {
                    calculatedPriceEl.textContent = "GHS " + priceNum.toFixed(2);
                    calculatedPriceEl.classList.remove('text-yellow-400');
                    calculatedPriceEl.classList.add('text-green-400');
                } else {
                    calculatedPriceEl.textContent = "GHS 0.00";
                    calculatedPriceEl.classList.remove('text-yellow-400', 'text-green-400');
                }
            }
        }
        
        // Function to validate package availability for agents
        function validateAgentPackage(packageSize, networkType) {
            if (!packageSize || !networkType) {
                return;
            }
            
            if (!bundleSizeInput) {
                console.error('bundle_size input element not found');
                return;
            }
            
            // Show loading state
            bundleSizeInput.classList.remove('border-red-500', 'border-green-500');
            bundleSizeInput.classList.add('border-yellow-500');
            
            // Show loading price
            if (calculatedPriceEl) {
                calculatedPriceEl.textContent = "Checking...";
                calculatedPriceEl.classList.add('text-yellow-400');
                calculatedPriceEl.classList.remove('text-green-400');
            }
            
            fetch('check_agent_package_availability.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `network_type=${encodeURIComponent(networkType)}&package_size=${encodeURIComponent(packageSize)}`
            })
            .then(response => {
                const contentType = response.headers.get('content-type');
                if (contentType && contentType.includes('application/json')) {
                    return response.json();
                } else {
                    return response.text().then(text => {
                        console.error('Invalid response:', text.substring(0, 200));
                        throw new Error('Server returned invalid response: ' + text.substring(0, 200));
                    });
                }
            })
            .then(data => {
                if (!bundleSizeInput) return;
                
                bundleSizeInput.classList.remove('border-yellow-500');
                
                if (data.success && data.available && data.price !== undefined && data.price !== null) {
                    // Package is available
                    bundleSizeInput.classList.remove('border-red-500');
                    bundleSizeInput.classList.add('border-green-500');
                    if (packageError) packageError.classList.add('hidden');
                    
                    // Format price properly - handle both string and number formats
                    let price = 0;
                    if (typeof data.price === 'number') {
                        price = data.price;
                    } else if (typeof data.price === 'string') {
                        // Remove any formatting (commas, currency symbols) and parse
                        const priceStr = data.price.replace(/[^\d.]/g, '');
                        price = parseFloat(priceStr) || 0;
                    }
                    
                    // Update price display
                    updatePriceDisplay(price);
                    isValidPackage = true;
                } else {
                    // Package is not available
                    bundleSizeInput.classList.remove('border-green-500');
                    bundleSizeInput.classList.add('border-red-500');
                    if (packageErrorText) packageErrorText.textContent = data.message || 'This package size is not available';
                    if (packageError) packageError.classList.remove('hidden');
                    updatePriceDisplay(0, true);
                    isValidPackage = false;
                }
            })
            .catch(error => {
                console.error('Error checking package availability:', error);
                if (bundleSizeInput) {
                    bundleSizeInput.classList.remove('border-yellow-500', 'border-green-500');
                    bundleSizeInput.classList.add('border-red-500');
                }
                if (packageErrorText) packageErrorText.textContent = 'Error checking package availability. Please try again.';
                if (packageError) packageError.classList.remove('hidden');
                updatePriceDisplay(0, true);
                isValidPackage = false;
            });
        }
        
        // Reset package validation when network changes
        if (networkSelect && bundleSizeInput) {
            networkSelect.addEventListener('change', function() {
                const network = this.value;
                
                if (!network) {
                    bundleSizeInput.value = '';
                    bundleSizeInput.disabled = true;
                    updatePriceDisplay(0);
                    if (packageError) packageError.classList.add('hidden');
                    isValidPackage = false;
                    return;
                }
                
                bundleSizeInput.disabled = false;
                bundleSizeInput.value = '';
                updatePriceDisplay(0);
                if (packageError) packageError.classList.add('hidden');
                isValidPackage = false;
            });
        }
        
        // Validate package when user types
        if (bundleSizeInput) {
            bundleSizeInput.addEventListener('input', function() {
                clearTimeout(packageValidationTimeout);
                
                const packageSize = this.value.trim();
                const networkType = networkSelect ? networkSelect.value : '';
                
                // Hide error and reset price while typing
                if (packageError) packageError.classList.add('hidden');
                updatePriceDisplay(0);
                isValidPackage = false;
                this.classList.remove('border-red-500', 'border-green-500');
                
                if (!packageSize) {
                    return;
                }
                
                if (!networkType) {
                    // Network not selected - show error
                    if (packageErrorText) packageErrorText.textContent = 'Please select a network first';
                    if (packageError) packageError.classList.remove('hidden');
                    this.classList.add('border-red-500');
                    updatePriceDisplay(0);
                    isValidPackage = false;
                    return;
                }
                
                // Network is selected - debounce validation - wait 500ms after user stops typing
                packageValidationTimeout = setTimeout(() => {
                    validateAgentPackage(packageSize, networkType);
                }, 500);
            });
            
            // Also validate on blur
            bundleSizeInput.addEventListener('blur', function() {
                clearTimeout(packageValidationTimeout);
                const packageSize = this.value.trim();
                const networkType = networkSelect ? networkSelect.value : '';
                
                if (packageSize && networkType) {
                    validateAgentPackage(packageSize, networkType);
                }
            });
        }
        
        // Phone number validation (reusing phoneInput and networkSelect from above)
        if (phoneInput) {
            phoneInput.addEventListener('input', function() {
                // Remove any non-digit characters
                this.value = this.value.replace(/\D/g, '');
                // Limit to 10 digits
                if (this.value.length > 10) {
                    this.value = this.value.substring(0, 10);
                }
                validatePhoneNumber();
            });
            
            phoneInput.addEventListener('blur', function() {
                validatePhoneNumber();
            });
        }
        
        if (networkSelect) {
            networkSelect.addEventListener('change', function() {
                updatePhonePlaceholder();
                // Package input validation will be triggered when user types
            });
        }
        
        // Form submission validation
        const orderForm = document.querySelector('form[action=""]');
        if (orderForm) {
            orderForm.addEventListener('submit', function(e) {
                const packageSize = bundleSizeInput ? bundleSizeInput.value.trim() : '';
                const networkType = networkSelect ? networkSelect.value : '';
                
                // Validate package before submission
                if (!packageSize) {
                    e.preventDefault();
                    if (packageErrorText) packageErrorText.textContent = 'Please enter a package size';
                    if (packageError) packageError.classList.remove('hidden');
                    if (bundleSizeInput) bundleSizeInput.focus();
                    return false;
                }
                
                if (!networkType) {
                    e.preventDefault();
                    alert('Please select a network');
                    if (networkSelect) networkSelect.focus();
                    return false;
                }
                
                if (!isValidPackage) {
                    // Re-validate package before submission
                    validateAgentPackage(packageSize, networkType);
                    
                    // Wait a bit for validation to complete, then check again
                    setTimeout(() => {
                        if (!isValidPackage) {
                            if (packageErrorText) packageErrorText.textContent = 'Please enter a valid package size';
                            if (packageError) packageError.classList.remove('hidden');
                            if (bundleSizeInput) bundleSizeInput.focus();
                        } else {
                            // If valid, proceed with submission
                            orderForm.submit();
                        }
                    }, 600);
                    
                    e.preventDefault();
                    return false;
                }
            });
        }
    });
</script>

<style>
</style>

<!-- Enhanced Notification System -->
<?php if (isset($success_message)): ?>
<div id="notification-success" class="notification-toast notification-success">
    <div class="notification-content">
        <div class="notification-icon">
            <i class="fas fa-check-circle"></i>
        </div>
        <div class="notification-body">
            <h4 class="notification-title">Success!</h4>
            <p class="notification-message"><?php echo htmlspecialchars($success_message); ?></p>
        </div>
        <button class="notification-close" onclick="closeNotification(this)">
            <i class="fas fa-times"></i>
        </button>
    </div>
    <div class="notification-progress"></div>
</div>
<?php endif; ?>

<?php if (isset($error_message)): ?>
<div id="notification-error" class="notification-toast notification-error">
    <div class="notification-content">
        <div class="notification-icon">
            <i class="fas fa-exclamation-triangle"></i>
        </div>
        <div class="notification-body">
            <h4 class="notification-title">Error!</h4>
            <p class="notification-message"><?php echo htmlspecialchars($error_message); ?></p>
        </div>
        <button class="notification-close" onclick="closeNotification(this)">
            <i class="fas fa-times"></i>
        </button>
    </div>
    <div class="notification-progress"></div>
</div>
<?php endif; ?>

<script>
    // Enhanced notification system
    function closeNotification(button) {
        const notification = button.closest('.notification-toast');
        notification.classList.add('notification-hide');
        setTimeout(() => {
            notification.remove();
        }, 300);
    }

    // Auto-hide notifications with progress bar and adjust positioning
    document.addEventListener('DOMContentLoaded', function() {
        const notifications = document.querySelectorAll('.notification-toast');
        
        // Calculate correct top position based on banner and navbar
        function calculateTopPosition() {
            const banner = document.getElementById('movingBanner');
            const navbar = document.querySelector('header');
            
            let topPosition = 80; // Default: just below navbar
            
            if (banner && navbar) {
                const bannerHeight = banner.offsetHeight || 48;
                const navbarHeight = navbar.offsetHeight || 70;
                topPosition = bannerHeight + navbarHeight + 10; // Add 10px spacing
            } else if (navbar) {
                const navbarHeight = navbar.offsetHeight || 70;
                topPosition = navbarHeight + 10;
            }
            
            return topPosition;
        }
        
        notifications.forEach(notification => {
            // Move notification to body level to avoid stacking context issues
            if (notification.parentElement !== document.body) {
                document.body.appendChild(notification);
            }
            
            // Force highest z-index and positioning
            notification.style.cssText += 'position: fixed !important; z-index: 99999 !important;';
            
            // Adjust top position dynamically
            const topPos = calculateTopPosition();
            notification.style.top = topPos + 'px';
            notification.style.right = '20px';
            
            // Show notification with animation
            setTimeout(() => {
                notification.classList.add('notification-show');
            }, 100);
            
            // Start progress bar animation
            const progressBar = notification.querySelector('.notification-progress');
            if (progressBar) {
                progressBar.style.animation = 'notification-progress 5s linear forwards';
            }
            
            // Auto-hide after 5 seconds
            setTimeout(() => {
                if (notification.classList.contains('notification-show')) {
                    notification.classList.add('notification-hide');
                    setTimeout(() => {
                        notification.remove();
                    }, 300);
                }
            }, 5000);
        });
        
        // Recalculate on window resize (in case banner/navbar height changes)
        let resizeTimer;
        window.addEventListener('resize', function() {
            clearTimeout(resizeTimer);
            resizeTimer = setTimeout(function() {
                const notifications = document.querySelectorAll('.notification-toast');
                const topPos = calculateTopPosition();
                notifications.forEach(notification => {
                    notification.style.top = topPos + 'px';
                });
            }, 250);
        });
        
    });
</script>

<style>
    /* Enhanced Notification Styles - Highest priority */
    .notification-toast {
        position: fixed !important;
        /* Account for banner (48px) + navbar (~70px) = ~118px, add 10px spacing */
        top: 128px !important;
        right: 20px !important;
        min-width: 320px;
        max-width: 400px;
        background: white !important;
        border-radius: 12px;
        box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15) !important;
        z-index: 99999 !important; /* Highest z-index to ensure it's above everything */
        transform: translateX(100%);
        opacity: 0;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        border-left: 4px solid;
        overflow: hidden;
        pointer-events: auto !important;
    }
    
    /* If no banner, adjust top position */
    body:not(:has(#movingBanner)) .notification-toast {
        top: 80px !important; /* Just below navbar when no banner */
    }
    
    /* Ensure notification is always on top - override any parent stacking contexts */
    body > .notification-toast {
        z-index: 99999 !important;
        position: fixed !important;
    }

    .notification-toast.notification-show {
        transform: translateX(0);
        opacity: 1;
    }

    .notification-toast.notification-hide {
        transform: translateX(100%);
        opacity: 0;
    }

    .notification-success {
        border-left-color: #10b981;
    }

    .notification-error {
        border-left-color: #ef4444;
    }

    .notification-content {
        display: flex;
        align-items: flex-start;
        padding: 16px;
        gap: 12px;
    }

    .notification-icon {
        flex-shrink: 0;
        width: 24px;
        height: 24px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
    }

    .notification-success .notification-icon {
        background: #d1fae5;
        color: #10b981;
    }

    .notification-error .notification-icon {
        background: #fee2e2;
        color: #ef4444;
    }

    .notification-body {
        flex: 1;
        min-width: 0;
    }

    .notification-title {
        font-size: 14px;
        font-weight: 600;
        margin: 0 0 4px 0;
        color: #1f2937;
    }

    .notification-message {
        font-size: 13px;
        color: #6b7280;
        margin: 0;
        line-height: 1.4;
    }

    .notification-close {
        flex-shrink: 0;
        background: none;
        border: none;
        color: #9ca3af;
        cursor: pointer;
        padding: 4px;
        border-radius: 4px;
        transition: all 0.2s;
        font-size: 12px;
    }

    .notification-close:hover {
        background: #f3f4f6;
        color: #374151;
    }

    .notification-progress {
        position: absolute;
        bottom: 0;
        left: 0;
        height: 3px;
        background: #e5e7eb;
        width: 100%;
    }

    .notification-success .notification-progress {
        background: linear-gradient(90deg, #10b981, #34d399);
    }

    .notification-error .notification-progress {
        background: linear-gradient(90deg, #ef4444, #f87171);
    }

    @keyframes notification-progress {
        from {
            width: 100%;
        }
        to {
            width: 0%;
        }
    }

    /* Mobile responsiveness */
    @media (max-width: 640px) {
        .notification-toast {
            top: 118px !important; /* Banner (48px) + Navbar (~70px) on mobile */
            right: 10px !important;
            left: 10px !important;
            min-width: auto;
            max-width: none;
            border-radius: 8px;
        }
        
        /* If no banner on mobile */
        body:not(:has(#movingBanner)) .notification-toast {
            top: 70px !important; /* Just below navbar when no banner */
        }
        
        .notification-content {
            padding: 12px;
            gap: 8px;
        }
        
        .notification-icon {
            width: 20px;
            height: 20px;
            font-size: 12px;
        }
        
        .notification-title {
            font-size: 13px;
            margin-bottom: 2px;
        }
        
        .notification-message {
            font-size: 12px;
            line-height: 1.3;
        }
        
        .notification-close {
            padding: 2px;
            font-size: 10px;
        }
    }
    
    /* Small mobile devices */
    @media (max-width: 375px) {
        .notification-toast {
            top: 113px !important; /* Banner (48px) + Navbar (~65px) on small mobile */
            right: 5px !important;
            left: 5px !important;
        }
        
        /* If no banner on small mobile */
        body:not(:has(#movingBanner)) .notification-toast {
            top: 65px !important; /* Just below navbar when no banner */
        }
        
        .notification-content {
            padding: 10px;
        }
        
        .notification-title {
            font-size: 12px;
        }
        
        .notification-message {
            font-size: 11px;
        }
    }

    /* Hover effects */
    .notification-toast:hover {
        transform: translateX(0) scale(1.02);
        box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
    }

    .notification-toast:hover .notification-progress {
        animation-play-state: paused;
    }
    
    /* Professional Cart & Navbar Enhancements */
    .glass-card {
        background: rgba(30, 41, 59, 0.75) !important;
        backdrop-filter: blur(20px) !important;
        -webkit-backdrop-filter: blur(20px) !important;
        border: 1px solid rgba(71, 85, 105, 0.4) !important;
    }
    
    .glass-card-light {
        background: rgba(51, 65, 85, 0.65) !important;
        backdrop-filter: blur(16px) !important;
        -webkit-backdrop-filter: blur(16px) !important;
        border: 1px solid rgba(71, 85, 105, 0.3) !important;
    }
    
    /* Enhanced Navbar Styling */
    header.glass-card {
        background: rgba(15, 23, 42, 0.85) !important;
        backdrop-filter: blur(24px) !important;
        -webkit-backdrop-filter: blur(24px) !important;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3) !important;
    }
    
    /* Professional Button Hover Effects */
    .card-hover {
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
    }
    
    .card-hover:hover {
        transform: translateY(-2px) !important;
        box-shadow: 0 12px 30px rgba(0, 0, 0, 0.4) !important;
        border-color: rgba(251, 191, 36, 0.5) !important;
    }
    
    /* Cart Item Hover Effects */
    .cart-item-hover:hover {
        transform: translateX(4px) !important;
        border-color: rgba(59, 130, 246, 0.6) !important;
    }
    
    /* Professional Network Badges */
    .network-badge {
        font-weight: 700 !important;
        letter-spacing: 0.5px !important;
        text-transform: uppercase !important;
    }
    
    /* Smooth Transitions */
    * {
        transition-property: color, background-color, border-color, transform, box-shadow !important;
        transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1) !important;
    }
    
    /* Professional Form Inputs */
    input[type="text"],
    input[type="email"],
    input[type="number"],
    select,
    textarea {
        transition: all 0.2s ease !important;
    }
    
    input[type="text"]:focus,
    input[type="email"]:focus,
    input[type="number"]:focus,
    select:focus,
    textarea:focus {
        transform: scale(1.01) !important;
        box-shadow: 0 0 0 3px rgba(251, 191, 36, 0.2) !important;
    }
    
    /* Compact Professional Spacing */
    .glass-card {
        margin-bottom: 0.75rem !important;
    }
    
    @media (min-width: 640px) {
        .glass-card {
            margin-bottom: 1rem !important;
        }
    }
    
    /* Enhanced Mobile Responsive Improvements */
    @media (max-width: 640px) {
        .cart-item {
            padding: 0.625rem !important;
        }
        
        /* Ensure text doesn't overflow on mobile */
        .cart-item p {
            word-break: break-word;
            overflow-wrap: break-word;
        }
        
        /* Better spacing for mobile cart items */
        .cart-item .space-y-3 > * + * {
            margin-top: 0.625rem;
        }
        
        /* Prevent horizontal scroll on mobile */
        .cart-item {
            overflow-x: hidden;
        }
        
        /* Better touch targets for mobile */
        .cart-item button,
        .cart-item a {
            min-width: 44px;
            min-height: 44px;
        }
        
        /* Improved form inputs on mobile */
        input[type="text"],
        input[type="number"],
        select,
        textarea {
            font-size: 16px !important; /* Prevents zoom on iOS */
        }
        
        /* Better button spacing */
        button[type="submit"],
        .tab-btn {
            min-height: 44px;
        }
    }
    
    /* Extra small devices (phones in portrait) */
    @media (max-width: 375px) {
        .glass-card {
            padding: 0.75rem !important;
        }
        
        .text-2xl {
            font-size: 1.5rem !important;
        }
        
        .text-3xl {
            font-size: 1.75rem !important;
        }
        
        .text-4xl {
            font-size: 2rem !important;
        }
    }
    
    /* Professional Typography Enhancements */
    body {
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        text-rendering: optimizeLegibility;
    }
    
    /* Enhanced Focus States for Accessibility */
    button:focus-visible,
    a:focus-visible,
    input:focus-visible,
    select:focus-visible,
    textarea:focus-visible {
        outline: 2px solid rgba(251, 191, 36, 0.8);
        outline-offset: 2px;
    }
    
    /* Smooth Scrolling */
    html {
        scroll-behavior: smooth;
    }
    
    /* Better Touch Feedback */
    @media (hover: none) and (pointer: coarse) {
        button:active,
        a:active {
            transform: scale(0.98);
        }
    }
    
    /* Professional Loading States */
    button[disabled] {
        opacity: 0.6;
        cursor: not-allowed;
    }
    
    /* Enhanced Tab Button Styles */
    .tab-btn {
        position: relative;
        overflow: hidden;
    }
    
    .tab-btn.active {
        background: linear-gradient(135deg, rgba(59, 130, 246, 0.2), rgba(99, 102, 241, 0.2));
        border: 1px solid rgba(59, 130, 246, 0.4);
        color: #93c5fd;
    }
    
    .tab-btn:not(.active) {
        color: #9ca3af;
    }
    
    .tab-btn:not(.active):hover {
        background: rgba(71, 85, 105, 0.3);
        color: #cbd5e1;
    }
</style>

