<?php
require_once 'config.php';
require_once 'app/classes/StoreManager.php';
session_start(); // Start session early to access stored store slug

// Get filter parameters
$search_order_id = isset($_GET['order_id']) ? trim($_GET['order_id']) : '';
$search_phone = isset($_GET['phone']) ? trim($_GET['phone']) : '';
$filter_date = isset($_GET['date']) ? $_GET['date'] : '';
$filter_status = isset($_GET['status']) ? $_GET['status'] : '';
$filter_network = isset($_GET['network']) ? $_GET['network'] : '';

// Get store slug from URL (if provided)
$storeSlug = isset($_GET['store']) ? trim($_GET['store']) : '';

// Get order reference from URL (for direct order lookup)
$orderRef = isset($_GET['ref']) ? trim($_GET['ref']) : '';
$singleOrder = null;
$orderNotFound = false;

// If ref parameter is provided, look up single order
if ($orderRef) {
    $refStmt = $conn->prepare("
        SELECT o.*, s.store_name, s.store_slug
        FROM orders o
        LEFT JOIN stores s ON o.store_id = s.id
        WHERE o.order_reference = ?
        LIMIT 1
    ");
    $refStmt->bind_param("s", $orderRef);
    $refStmt->execute();
    $refResult = $refStmt->get_result();
    $singleOrder = $refResult->fetch_assoc();
    $refStmt->close();
    
    if (!$singleOrder) {
        $orderNotFound = true;
    } else {
        // Use store slug from single order if not in URL
        if (!$storeSlug && !empty($singleOrder['store_slug'])) {
            $storeSlug = $singleOrder['store_slug'];
        }
    }
}

// Load store information if we have a store slug (for custom colors and logo)
$store = null;
$storeManager = null;
if (!empty($storeSlug)) {
    $storeManager = new StoreManager($conn);
    $store = $storeManager->getStoreBySlug($storeSlug);
}

// Build query with filters using prepared statements
$whereConditions = [];
$params = [];
$paramTypes = '';

if ($search_order_id) {
    // Use exact match for order reference (case-insensitive)
    $whereConditions[] = "UPPER(order_reference) = UPPER(?)";
    $params[] = $search_order_id;
    $paramTypes .= 's';
}

if ($search_phone) {
    $whereConditions[] = "beneficiary_number LIKE ?";
    $params[] = "%$search_phone%";
    $paramTypes .= 's';
}

if ($filter_date) {
    $whereConditions[] = "DATE(created_at) = ?";
    $params[] = $filter_date;
    $paramTypes .= 's';
}

if ($filter_status) {
    $whereConditions[] = "status = ?";
    $params[] = $filter_status;
    $paramTypes .= 's';
}

if ($filter_network) {
    $whereConditions[] = "network_type = ?";
    $params[] = $filter_network;
    $paramTypes .= 's';
}

$whereClause = !empty($whereConditions) ? "WHERE " . implode(" AND ", $whereConditions) : "";

// Get orders using prepared statement (include store slug)
$orders_query = "SELECT o.*, s.store_slug FROM orders o LEFT JOIN stores s ON o.store_id = s.id $whereClause ORDER BY o.created_at DESC LIMIT 100";
if (!empty($params)) {
    $stmt = mysqli_prepare($conn, $orders_query);
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, $paramTypes, ...$params);
        mysqli_stmt_execute($stmt);
        $orders_result = mysqli_stmt_get_result($stmt);
    } else {
        $orders_result = false;
    }
} else {
    $orders_result = mysqli_query($conn, $orders_query);
}

// Determine home link - Priority order:
// 1. Store slug from URL parameter (explicit)
// 2. Store slug from the order being viewed (if ref parameter)
// 3. Store slug from session (where customer last visited/ordered)
// This ensures customers are NEVER redirected to index.php
if ($storeSlug) {
    // Explicit store parameter in URL - highest priority
    $homeLink = "store.php?slug=" . urlencode($storeSlug);
} elseif ($orderRef && $singleOrder && !empty($singleOrder['store_slug'])) {
    // When viewing a specific order, use that order's store
    $storeSlug = $singleOrder['store_slug'];
    $homeLink = "store.php?slug=" . urlencode($storeSlug);
    // Also update session for future use
    $_SESSION['last_store_slug'] = $storeSlug;
} elseif (isset($_SESSION['last_store_slug']) && !empty($_SESSION['last_store_slug'])) {
    // Use store slug from session (where customer last visited)
    $storeSlug = $_SESSION['last_store_slug'];
    $homeLink = "store.php?slug=" . urlencode($storeSlug);
} else {
    // Last resort: try to get from first search result (but only if we have results)
    if ($orders_result && mysqli_num_rows($orders_result) > 0) {
        $firstOrder = mysqli_fetch_assoc($orders_result);
        if (!empty($firstOrder['store_slug'])) {
            $storeSlug = $firstOrder['store_slug'];
            $homeLink = "store.php?slug=" . urlencode($storeSlug);
            $_SESSION['last_store_slug'] = $storeSlug;
        } else {
            $homeLink = "index.php";
        }
        // Reset result pointer
        mysqli_data_seek($orders_result, 0);
    } else {
        // Only use index.php as absolute last resort
        $homeLink = "index.php";
    }
}

// Load store information if we have a store slug (for custom colors and logo)
$store = null;
if (!empty($storeSlug)) {
    $storeManager = new StoreManager($conn);
    $store = $storeManager->getStoreBySlug($storeSlug);
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    
    <title>Check Order Status | D-Bundles Stores</title>
    <meta name="description" content="Track your data bundle orders in real-time">
    
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');
        
        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(180deg, <?php echo htmlspecialchars($store['background_color'] ?? '#0f172a'); ?> 0%, <?php echo htmlspecialchars($store['background_color'] ?? '#0f172a'); ?> 100%);
            min-height: 100vh;
        }
        
        .gradient-bg {
            background: linear-gradient(135deg, #1e293b 0%, #334155 50%, #475569 100%);
        }
        
        .store-header {
            background: linear-gradient(135deg, <?php echo htmlspecialchars($store['hero_color_1'] ?? '#3b82f6'); ?> 0%, <?php echo htmlspecialchars($store['hero_color_2'] ?? '#8b5cf6'); ?> 100%);
        }
        
        .store-button {
            background-color: <?php echo htmlspecialchars($store['button_color'] ?? '#3b82f6'); ?> !important;
        }
        
        .store-button:hover {
            background-color: <?php echo htmlspecialchars($store['button_hover_color'] ?? '#2563eb'); ?> !important;
        }
        
        <?php 
        $formTheme = $store['form_theme'] ?? 'dark';
        if ($formTheme === 'light'): 
        ?>
        /* Light Form Theme - Glass-like Professional Design */
        .form-container,
        .order-card,
        .status-card {
            background: rgba(255, 255, 255, 0.95) !important;
            backdrop-filter: blur(20px) saturate(180%) !important;
            -webkit-backdrop-filter: blur(20px) saturate(180%) !important;
            border: 1px solid rgba(255, 255, 255, 0.3) !important;
            box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.1) !important;
        }
        
        .form-container h2,
        .form-container h3,
        .order-card h2,
        .order-card h3,
        .status-card h2,
        .status-card h3 {
            color: #1f2937 !important;
        }
        
        .form-container p,
        .form-container label,
        .order-card p,
        .order-card label,
        .status-card p,
        .status-card label {
            color: #4b5563 !important;
        }
        
        .form-container .text-gray-400,
        .order-card .text-gray-400,
        .status-card .text-gray-400 {
            color: #6b7280 !important;
        }
        
        .form-container .text-gray-500,
        .order-card .text-gray-500,
        .status-card .text-gray-500 {
            color: #6b7280 !important;
        }
        
        .form-container input[type="text"],
        .form-container input[type="tel"],
        .form-container input[type="number"],
        .form-container select,
        .form-container textarea,
        .form-input {
            background-color: rgba(255, 255, 255, 0.8) !important;
            backdrop-filter: blur(10px) !important;
            -webkit-backdrop-filter: blur(10px) !important;
            border: 1px solid rgba(209, 213, 219, 0.5) !important;
            color: #1f2937 !important;
        }
        
        .form-container input[type="text"]:focus,
        .form-container input[type="tel"]:focus,
        .form-container input[type="number"]:focus,
        .form-container select:focus,
        .form-container textarea:focus,
        .form-input:focus {
            background-color: rgba(255, 255, 255, 0.95) !important;
            border-color: <?php echo htmlspecialchars($store['button_color'] ?? '#3b82f6'); ?> !important;
            color: #1f2937 !important;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1) !important;
            outline: none !important;
        }
        
        .form-container input::placeholder,
        .form-container textarea::placeholder {
            color: #9ca3af !important;
        }
        
        .form-container select option {
            background-color: #ffffff !important;
            color: #1f2937 !important;
        }
        
        .form-container .text-white,
        .order-card .text-white,
        .status-card .text-white,
        .form-header .text-white {
            color: #1f2937 !important;
        }
        
        .form-container .bg-gray-700,
        .order-card .bg-gray-700,
        .status-card .bg-gray-700 {
            background-color: rgba(255, 255, 255, 0.5) !important;
        }
        
        .form-container .bg-gray-800,
        .order-card .bg-gray-800,
        .status-card .bg-gray-800 {
            background-color: rgba(255, 255, 255, 0.6) !important;
        }
        
        .order-details {
            background-color: rgba(255, 255, 255, 0.4) !important;
        }
        
        .form-header .text-blue-400 {
            color: <?php echo htmlspecialchars($store['button_color'] ?? '#3b82f6'); ?> !important;
        }
        
        /* Help Section - Light Theme */
        .help-section {
            background: rgba(255, 255, 255, 0.95) !important;
            backdrop-filter: blur(20px) saturate(180%) !important;
            -webkit-backdrop-filter: blur(20px) saturate(180%) !important;
            border: 1px solid rgba(255, 255, 255, 0.3) !important;
            box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.1) !important;
        }
        
        .help-section h3,
        .help-section h4 {
            color: #1f2937 !important;
        }
        
        .help-section p,
        .help-section .text-gray-400 {
            color: #6b7280 !important;
        }
        
        .help-section .bg-gray-700\/50 {
            background-color: rgba(255, 255, 255, 0.4) !important;
        }
        <?php else: ?>
        /* Dark Form Theme (default) */
        .form-container,
        .order-card,
        .status-card {
            background: linear-gradient(135deg, #1f2937 0%, #111827 100%) !important;
            border-color: #374151 !important;
        }
        
        /* Help Section - Dark Theme */
        .help-section {
            background: linear-gradient(135deg, #1f2937 0%, #111827 100%) !important;
            border-color: #374151 !important;
        }
        <?php endif; ?>
        
        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: scale(0.9) translateY(-10px);
            }
            to {
                opacity: 1;
                transform: scale(1) translateY(0);
            }
        }
        
        .animate-fadeIn {
            animation: fadeIn 0.3s ease-out;
        }
    </style>
</head>

<body>
    <!-- Header -->
    <div class="store-header text-white py-12">
        <div class="container mx-auto px-4">
            <div class="text-center">
                <?php 
                // Normalize logo URL - ensure it starts with uploads/ if it doesn't already have a full path
                $logoUrl = '';
                if (!empty($store['logo_url'])) {
                    $logoUrl = $store['logo_url'];
                    // If it doesn't start with http:// or https:// or /, ensure it's relative to root
                    if (!preg_match('/^(https?:\/\/|\/)/', $logoUrl)) {
                        // Remove any leading ../ or ./ 
                        $logoUrl = ltrim($logoUrl, './');
                        // Ensure it starts with uploads/ if it's a relative path
                        if (substr($logoUrl, 0, 8) !== 'uploads/') {
                            $logoUrl = 'uploads/stores/' . basename($logoUrl);
                        }
                    }
                }
                ?>
                <?php if (!empty($logoUrl)): ?>
                <div class="mb-4">
                    <img src="<?php echo htmlspecialchars($logoUrl); ?>" 
                         alt="<?php echo !empty($store['store_name']) ? htmlspecialchars($store['store_name']) : 'Store Logo'; ?>" 
                         class="w-24 h-24 mx-auto rounded-full border-4 border-white object-cover"
                         onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">
                    <div style="display:none;" class="w-24 h-24 mx-auto bg-white/20 rounded-full flex items-center justify-center mb-4 border-4 border-white">
                        <i class="fas fa-search text-4xl"></i>
                    </div>
                </div>
                <?php else: ?>
                <div class="w-24 h-24 mx-auto bg-white/20 rounded-full flex items-center justify-center mb-4">
                    <i class="fas fa-search text-4xl"></i>
                </div>
                <?php endif; ?>
                
                <h1 class="text-4xl font-bold mb-2">
                    <?php if (!empty($store['store_name'])): ?>
                        <?php echo htmlspecialchars($store['store_name']); ?> - Order Status
                    <?php else: ?>
                        Check Order Status
                    <?php endif; ?>
                </h1>
                <p class="text-lg text-blue-100 mb-4">Track your data bundle orders in real-time</p>
                
                <!-- Quick Links -->
                <div class="flex justify-center gap-4 mt-6 flex-wrap">
                    <a href="<?= htmlspecialchars($homeLink) ?>" 
                       class="flex items-center gap-2 text-white hover:text-blue-200 transition px-4 py-2 rounded-lg hover:bg-white/10">
                        <i class="fas fa-home"></i>
                        <span>Home</span>
                    </a>
                    <a href="order-status.php" 
                       class="flex items-center gap-2 bg-white/20 hover:bg-white/30 px-4 py-2 rounded-lg text-white transition">
                        <i class="fas fa-search"></i>
                        <span>Check Status</span>
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Content -->
    <div class="container mx-auto px-4 py-8">
        
        <!-- Single Order Status Display (when ref parameter is provided) -->
        <?php if ($orderRef): ?>
        <div class="max-w-2xl mx-auto mb-8">
            <?php if ($orderNotFound): ?>
            <!-- Order Not Found -->
            <div class="status-card bg-gray-800 border-2 border-red-700 rounded-2xl p-8 text-center animate-fadeIn">
                <div class="w-20 h-20 bg-red-900/50 rounded-full flex items-center justify-center mx-auto mb-4">
                    <i class="fas fa-exclamation-triangle text-red-400 text-3xl"></i>
                </div>
                <h2 class="text-2xl font-bold text-white mb-2">Order Not Found</h2>
                <p class="text-gray-300 mb-4">We couldn't find an order with reference: <strong class="font-mono text-white"><?= htmlspecialchars($orderRef) ?></strong></p>
                <p class="text-sm text-gray-400 mb-4">Please check your order reference and try again.</p>
                <a href="order-status.php" class="inline-block bg-red-600 text-white px-6 py-2 rounded-lg hover:bg-red-700 transition-colors">
                    <i class="fas fa-search mr-2"></i>Search Again
                </a>
            </div>
            <?php else: ?>
            <!-- Order Found - Display Status -->
            <?php
            $status = $singleOrder['status'];
            $isDelivered = $status === 'delivered';
            $isProcessing = $status === 'processing';
            $isPending = $status === 'pending';
            $isFailed = $status === 'failed';
            ?>
            <div class="status-card bg-gray-800 rounded-2xl shadow-xl border-2 p-6 sm:p-8 animate-fadeIn <?php echo $isDelivered ? 'border-green-600' : ($isProcessing ? 'border-blue-600' : ($isFailed ? 'border-red-600' : 'border-yellow-600')); ?>">
                <!-- Status Header -->
                <div class="text-center mb-6">
                    <div class="w-24 h-24 rounded-full flex items-center justify-center mx-auto mb-4 <?php echo $isDelivered ? 'bg-green-900/50' : ($isProcessing ? 'bg-blue-900/50' : ($isFailed ? 'bg-red-900/50' : 'bg-yellow-900/50')); ?>">
                        <i class="fas <?php echo $isDelivered ? 'fa-check-circle text-green-400' : ($isProcessing ? 'fa-spinner fa-spin text-blue-400' : ($isFailed ? 'fa-times-circle text-red-400' : 'fa-clock text-yellow-400')); ?> text-4xl"></i>
                    </div>
                    <h2 class="text-3xl font-bold mb-2 text-white">
                        Order <?= ucfirst($singleOrder['status']) ?>
                    </h2>
                    <p class="text-gray-400">Order Reference: <span class="font-mono font-bold text-lg text-white"><?= htmlspecialchars($singleOrder['order_reference']) ?></span></p>
                </div>

                <!-- Order Details -->
                <div class="order-details bg-gray-700/50 rounded-xl p-4 sm:p-6 mb-6">
                    <h3 class="text-lg font-semibold text-white mb-4 flex items-center">
                        <i class="fas fa-info-circle text-blue-400 mr-2"></i>Order Details
                    </h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <p class="text-xs text-gray-400 mb-1">Network</p>
                            <p class="font-semibold text-white"><?= strtoupper($singleOrder['network_type']) ?></p>
                        </div>
                        <div>
                            <p class="text-xs text-gray-400 mb-1">Package Size</p>
                            <p class="font-semibold text-white"><?= htmlspecialchars($singleOrder['package_size']) ?></p>
                        </div>
                        <div>
                            <p class="text-xs text-gray-400 mb-1">Phone Number</p>
                            <p class="font-semibold text-white font-mono"><?= htmlspecialchars($singleOrder['beneficiary_number']) ?></p>
                        </div>
                        <div>
                            <p class="text-xs text-gray-400 mb-1">Amount Paid</p>
                            <p class="font-semibold text-green-400 text-lg">GH₵ <?= number_format($singleOrder['amount'], 2) ?></p>
                        </div>
                        <div>
                            <p class="text-xs text-gray-400 mb-1">Payment Method</p>
                            <p class="font-semibold text-white">
                                <?= ucfirst(str_replace('_', ' ', $singleOrder['payment_method'] ?? 'mobile_money')) ?>
                            </p>
                        </div>
                        <div>
                            <p class="text-xs text-gray-400 mb-1">Order Date</p>
                            <p class="font-semibold text-white"><?= date('M d, Y g:i A', strtotime($singleOrder['created_at'])) ?></p>
                        </div>
                        <?php if ($singleOrder['store_name']): ?>
                        <div>
                            <p class="text-xs text-gray-400 mb-1">Store</p>
                            <p class="font-semibold text-white"><?= htmlspecialchars($singleOrder['store_name']) ?></p>
                        </div>
                        <?php endif; ?>
                        <?php if ($singleOrder['status_updated_at']): ?>
                        <div>
                            <p class="text-xs text-gray-400 mb-1">Last Updated</p>
                            <p class="font-semibold text-white"><?= date('M d, Y g:i A', strtotime($singleOrder['status_updated_at'])) ?></p>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Status Message -->
                <div class="rounded-xl p-4 mb-6 <?php echo $isDelivered ? 'bg-green-900/30 border border-green-700' : ($isProcessing ? 'bg-blue-900/30 border border-blue-700' : ($isFailed ? 'bg-red-900/30 border border-red-700' : 'bg-yellow-900/30 border border-yellow-700')); ?>">
                    <?php if ($isDelivered): ?>
                        <p class="text-green-300 font-semibold mb-1">
                            <i class="fas fa-check-circle mr-2"></i>Your data bundle has been successfully delivered!
                        </p>
                        <p class="text-green-200 text-sm">The data has been credited to <?= htmlspecialchars($singleOrder['beneficiary_number']) ?>.</p>
                    <?php elseif ($isProcessing): ?>
                        <p class="text-blue-300 font-semibold mb-1">
                            <i class="fas fa-spinner fa-spin mr-2"></i>Your order is being processed
                        </p>
                        <p class="text-blue-200 text-sm">Your payment has been confirmed and the order is being sent to the network. Please wait a few minutes.</p>
                    <?php elseif ($isPending): ?>
                        <p class="text-yellow-300 font-semibold mb-1">
                            <i class="fas fa-clock mr-2"></i>Your order is pending payment confirmation
                        </p>
                        <p class="text-yellow-200 text-sm">Please complete your payment to process the order.</p>
                    <?php elseif ($isFailed): ?>
                        <p class="text-red-300 font-semibold mb-1">
                            <i class="fas fa-times-circle mr-2"></i>Order processing failed
                        </p>
                        <p class="text-red-200 text-sm">There was an issue processing your order. Please contact support for assistance.</p>
                    <?php else: ?>
                        <p class="text-gray-300 font-semibold">Status: <?= ucfirst($singleOrder['status']) ?></p>
                    <?php endif; ?>
                </div>

                <!-- Actions -->
                <div class="flex flex-col sm:flex-row gap-3 justify-center">
                    <a href="order-status.php" class="flex-1 bg-gray-700 text-white px-6 py-3 rounded-lg hover:bg-gray-600 transition-colors text-center">
                        <i class="fas fa-search mr-2"></i>Check Another Order
                    </a>
                    <?php if ($singleOrder['store_slug']): ?>
                    <a href="store.php?slug=<?= urlencode($singleOrder['store_slug']) ?>" class="flex-1 store-button text-white px-6 py-3 rounded-lg transition-colors text-center">
                        <i class="fas fa-store mr-2"></i>Back to Store
                    </a>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <!-- Search Form -->
        <div class="max-w-2xl mx-auto mb-8">
            <div class="form-container bg-gradient-to-br from-gray-800 to-gray-900 rounded-2xl p-5 sm:p-6 shadow-2xl border border-gray-700">
                <div class="form-header text-center mb-6">
                    <h2 class="text-xl sm:text-2xl font-bold text-white mb-1">
                        <i class="fas fa-search mr-2 text-blue-400"></i>
                        Search Your Order
                    </h2>
                    <p class="text-xs text-gray-400">Enter your order reference or phone number</p>
                </div>

                <form method="GET" class="space-y-4">
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div>
                            <label for="order_id" class="block text-xs font-medium text-gray-400 mb-1.5">
                                Order Reference
                            </label>
                            <input 
                                type="text" 
                                id="order_id" 
                                name="order_id" 
                                value="<?= htmlspecialchars($search_order_id ?: $orderRef) ?>"
                                class="form-input w-full bg-gray-700/50 border border-gray-600 text-white rounded-xl px-4 py-2.5 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 placeholder-gray-500"
                                placeholder="Enter Order Reference (e.g., ABCD)"
                            >
                        </div>
                        
                        <div>
                            <label for="phone" class="block text-xs font-medium text-gray-400 mb-1.5">
                                Phone Number
                            </label>
                            <input 
                                type="text" 
                                id="phone" 
                                name="phone" 
                                value="<?= htmlspecialchars($search_phone) ?>"
                                class="form-input w-full bg-gray-700/50 border border-gray-600 text-white rounded-xl px-4 py-2.5 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 placeholder-gray-500"
                                placeholder="Enter phone number"
                            >
                        </div>
                    </div>
                    
                    <button type="submit" class="w-full store-button text-white py-3 rounded-xl font-medium transition-colors">
                        <i class="fas fa-search mr-2"></i>Search Order
                    </button>
                </form>
            </div>
        </div>

        <!-- Orders List (if search results) -->
        <?php if ($orders_result && mysqli_num_rows($orders_result) > 0 && ($search_order_id || $search_phone)): ?>
        <div class="max-w-4xl mx-auto">
            <div class="order-card bg-gradient-to-br from-gray-800 to-gray-900 rounded-2xl p-5 sm:p-6 shadow-2xl border border-gray-700">
                <div class="text-center mb-6">
                    <h2 class="text-xl sm:text-2xl font-bold text-white mb-1">
                        <i class="fas fa-list mr-2 text-blue-400"></i>
                        Search Results
                    </h2>
                    <p class="text-xs text-gray-400">Found <?= mysqli_num_rows($orders_result) ?> order(s)</p>
                </div>

                <div class="space-y-3">
                    <?php while ($order = mysqli_fetch_assoc($orders_result)): ?>
                    <?php
                    $orderStatus = $order['status'];
                    $orderIsDelivered = $orderStatus === 'delivered';
                    $orderIsProcessing = $orderStatus === 'processing';
                    $orderIsPending = $orderStatus === 'pending';
                    $orderIsFailed = $orderStatus === 'failed';
                    ?>
                    <div class="bg-gray-700/50 rounded-xl p-4 border border-gray-600 hover:border-blue-500 transition-colors">
                        <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
                            <div class="flex-1">
                                <div class="flex items-center gap-3 mb-2">
                                    <div class="w-10 h-10 rounded-lg flex items-center justify-center <?php echo $orderIsDelivered ? 'bg-green-900/50' : ($orderIsProcessing ? 'bg-blue-900/50' : ($orderIsFailed ? 'bg-red-900/50' : 'bg-yellow-900/50')); ?>">
                                        <i class="fas <?php echo $orderIsDelivered ? 'fa-check-circle text-green-400' : ($orderIsProcessing ? 'fa-spinner fa-spin text-blue-400' : ($orderIsFailed ? 'fa-times-circle text-red-400' : 'fa-clock text-yellow-400')); ?>"></i>
                                    </div>
                                    <div>
                                        <p class="font-mono font-bold text-white"><?= htmlspecialchars($order['order_reference']) ?></p>
                                        <p class="text-xs text-gray-400"><?= date('M d, Y g:i A', strtotime($order['created_at'])) ?></p>
                                    </div>
                                </div>
                                <div class="grid grid-cols-2 sm:grid-cols-4 gap-2 text-sm">
                                    <div>
                                        <p class="text-xs text-gray-400">Network</p>
                                        <p class="text-white font-semibold"><?= strtoupper($order['network_type']) ?></p>
                                    </div>
                                    <div>
                                        <p class="text-xs text-gray-400">Package</p>
                                        <p class="text-white font-semibold"><?= htmlspecialchars($order['package_size']) ?></p>
                                    </div>
                                    <div>
                                        <p class="text-xs text-gray-400">Phone</p>
                                        <p class="text-white font-mono text-xs"><?= htmlspecialchars($order['beneficiary_number']) ?></p>
                                    </div>
                                    <div>
                                        <p class="text-xs text-gray-400">Amount</p>
                                        <p class="text-green-400 font-semibold">GH₵ <?= number_format($order['amount'], 2) ?></p>
                                    </div>
                                </div>
                            </div>
                            <div class="flex items-center gap-2">
                                <span class="px-3 py-1 rounded-full text-xs font-medium <?php echo $orderIsDelivered ? 'bg-green-900/50 text-green-300' : ($orderIsProcessing ? 'bg-blue-900/50 text-blue-300' : ($orderIsFailed ? 'bg-red-900/50 text-red-300' : 'bg-yellow-900/50 text-yellow-300')); ?>">
                                    <?= ucfirst($orderStatus) ?>
                                </span>
                                <a href="order-status.php?ref=<?= urlencode($order['order_reference']) ?><?= !empty($order['store_slug']) ? '&store=' . urlencode($order['store_slug']) : '' ?>" 
                                   class="px-3 py-1 store-button text-white rounded-lg text-xs transition-colors">
                                    <i class="fas fa-eye"></i>
                                </a>
                            </div>
                        </div>
                    </div>
                    <?php endwhile; ?>
                </div>
            </div>
        </div>
        <?php elseif ($search_order_id || $search_phone): ?>
        <!-- No Results -->
        <div class="max-w-2xl mx-auto">
            <div class="bg-gray-800 rounded-2xl p-8 text-center border border-gray-700">
                <div class="w-20 h-20 bg-gray-700 rounded-full flex items-center justify-center mx-auto mb-4">
                    <i class="fas fa-inbox text-gray-400 text-2xl"></i>
                </div>
                <h3 class="text-lg font-semibold text-white mb-2">No Orders Found</h3>
                <p class="text-gray-400 mb-4">No orders match your search criteria.</p>
                <a href="order-status.php" class="inline-block store-button text-white px-6 py-2 rounded-lg transition-colors">
                    <i class="fas fa-search mr-2"></i>Search Again
                </a>
            </div>
        </div>
        <?php endif; ?>

        <!-- Help Section -->
        <div class="max-w-2xl mx-auto mt-8">
            <div class="help-section bg-gradient-to-br from-gray-800 to-gray-900 rounded-2xl p-5 sm:p-6 shadow-2xl border border-gray-700">
                <h3 class="text-lg font-bold text-white mb-4 flex items-center">
                    <i class="fas fa-question-circle mr-2" style="color: <?php echo htmlspecialchars($store['button_color'] ?? '#3b82f6'); ?>;"></i>Need Help?
                </h3>
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                   
                    <div class="bg-gray-700/50 rounded-xl p-4 border border-gray-600">
                        <h4 class="font-semibold text-white mb-2 flex items-center">
                            <i class="fas fa-home mr-2" style="color: <?php echo htmlspecialchars($store['button_color'] ?? '#3b82f6'); ?>;"></i>Go Home
                        </h4>
                        <p class="text-gray-400 text-sm mb-3">Return to store</p>
                        <a href="<?= htmlspecialchars($homeLink) ?>" class="inline-flex items-center store-button text-white px-4 py-2 rounded-lg text-sm transition-colors">
                            <i class="fas fa-home mr-2"></i>Home
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Add input validation and formatting
        document.getElementById('order_id')?.addEventListener('input', function() {
            this.value = this.value.toUpperCase();
        });

        document.getElementById('phone')?.addEventListener('input', function() {
            this.value = this.value.replace(/[^0-9]/g, '');
        });

        // Form validation
        document.querySelector('form')?.addEventListener('submit', function(e) {
            const orderId = document.getElementById('order_id')?.value.trim() || '';
            const phone = document.getElementById('phone')?.value.trim() || '';
            
            if (!orderId && !phone) {
                e.preventDefault();
                alert('Please enter either an Order Reference or phone number to search.');
                return false;
            }
            
            if (orderId && orderId.length < 3) {
                e.preventDefault();
                alert('Order Reference should be at least 3 characters long.');
                return false;
            }
            
            if (phone && phone.length < 10) {
                e.preventDefault();
                alert('Phone number should be at least 10 digits long.');
                return false;
            }
        });
    </script>
</body>
</html>
