<?php
// Public Store Page - Customers can browse and buy from a specific store
session_start();
require_once 'config.php';
require_once 'app/classes/StoreManager.php';
require_once 'app/classes/StorePricingManager.php';

// Get store slug from URL
$storeSlug = $_GET['slug'] ?? '';

if (empty($storeSlug)) {
    header("Location: index.php");
    exit();
}

// Load store information
$storeManager = new StoreManager($conn);
$store = $storeManager->getStoreBySlug($storeSlug);

if (!$store) {
    header("Location: 404.php");
    exit();
}

// Store the store slug in session so we can always link back to this store
// This ensures customers are never redirected to index.php
$_SESSION['last_store_slug'] = $storeSlug;

// If user is logged in as an agent, store the store slug for logout redirect
// Store slug whenever agent visits any store page, but prioritize their own store
if (isset($_SESSION['user_id']) && isset($_SESSION['role']) && $_SESSION['role'] === 'agent') {
    // Check if agent belongs to a store
    $agentStmt = $conn->prepare("SELECT store_id FROM agents WHERE id = ? AND role = 'agent' AND is_store_owner = 0 LIMIT 1");
    $agentStmt->bind_param("i", $_SESSION['user_id']);
    $agentStmt->execute();
    $agentResult = $agentStmt->get_result();
    if ($agentResult->num_rows > 0) {
        $agentData = $agentResult->fetch_assoc();
        // If agent belongs to this store, always store the slug (their own store takes priority)
        if ($agentData['store_id'] == $store['id']) {
            $_SESSION['agent_store_slug'] = $storeSlug;
        } elseif (empty($agentData['store_id'])) {
            // Agent doesn't belong to any store yet, store the current store slug as fallback
            $_SESSION['agent_store_slug'] = $storeSlug;
        }
        // If agent belongs to a different store, don't overwrite their own store slug
    } else {
        // Agent not found in database, but store the slug anyway as fallback
        $_SESSION['agent_store_slug'] = $storeSlug;
    }
    $agentStmt->close();
}

// Check if store is active
$isStoreActive = ($store['status'] === 'active');
if (!$isStoreActive) {
    $error_message = "This store is currently inactive and not accepting orders.";
}

// Load store pricing
$pricingManager = new StorePricingManager($conn);

// Get store owner contact information (use store's WhatsApp, not admin's)
$storeOwnerWhatsApp = $store['whatsapp'] ?? '';
$storeOwnerPhone = $store['phone'] ?? '';
$storeOwnerEmail = $store['email'] ?? '';

// Get available networks (MTN only)
$networks = [
    'mtn' => 'MTN'
];

// Get WhatsApp group link - use only store's own link (no fallback)
$whatsappGroupLink = $store['whatsapp_group_link'] ?? '';

// Handle payment status messages
$paymentStatus = $_GET['payment'] ?? '';
$orderReference = $_GET['ref'] ?? '';
$paymentMessage = '';
$paymentMessageType = '';

if ($paymentStatus === 'payment_success') {
    $paymentMessage = 'Payment successful! Your order has been processed and is being delivered.';
    $paymentMessageType = 'success';
} elseif ($paymentStatus === 'payment_processing') {
    $paymentMessage = 'Payment successful! Your order is being processed.';
    $paymentMessageType = 'success';
} elseif ($paymentStatus === 'payment_error') {
    $paymentMessage = 'Payment processing encountered an error. Please contact support with your order reference: ' . htmlspecialchars($orderReference);
    $paymentMessageType = 'error';
} elseif ($paymentStatus === 'api_failed') {
    $paymentMessage = 'Payment received but order processing failed. Your payment will be refunded. Please contact support.';
    $paymentMessageType = 'error';
}

?>
<!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><?php echo htmlspecialchars($store['store_name']); ?> | Data Bundle Store</title>
    <meta name="description" content="Buy affordable data bundles from <?php echo htmlspecialchars($store['store_name']); ?>">
    
    <!-- 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;
        }
        
        .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;
        }
        
        /* Store Custom Colors - Replace all blue colors */
        <?php 
        $buttonColor = $store['button_color'] ?? '#3b82f6';
        $buttonHoverColor = $store['button_hover_color'] ?? '#2563eb';
        // Convert hex to RGB
        $buttonRgb = sscanf($buttonColor, '#%02x%02x%02x');
        $buttonRgbStr = $buttonRgb[0] . ', ' . $buttonRgb[1] . ', ' . $buttonRgb[2];
        ?>
        
        /* Text Colors */
        .text-blue-400,
        .text-blue-300,
        .text-blue-100,
        .text-blue-200 {
            color: <?php echo $buttonColor; ?> !important;
        }
        
        .hover\:text-blue-200:hover,
        .hover\:text-blue-300:hover {
            color: <?php echo $buttonHoverColor; ?> !important;
        }
        
        /* Focus States */
        .focus\:ring-blue-500:focus {
            --tw-ring-color: <?php echo $buttonColor; ?> !important;
        }
        
        .focus\:border-blue-500:focus {
            border-color: <?php echo $buttonColor; ?> !important;
        }
        
        /* Background Colors */
        .bg-blue-900\/50,
        .from-blue-900\/50,
        .to-blue-800\/50 {
            background-color: rgba(<?php echo $buttonRgbStr; ?>, 0.1) !important;
        }
        
        /* Border Colors */
        .border-blue-600\/50,
        .border-blue-600 {
            border-color: <?php echo $buttonColor; ?> !important;
        }
        
        /* Package Card Hover Shadow */
        .package-card:hover {
            box-shadow: 0 10px 20px rgba(<?php echo $buttonRgbStr; ?>, 0.3) !important;
        }
        
        /* Price Display */
        .price-display {
            background: linear-gradient(to right, rgba(<?php echo $buttonRgbStr; ?>, 0.1), rgba(<?php echo $buttonRgbStr; ?>, 0.15)) !important;
            border-color: <?php echo $buttonColor; ?>80 !important;
        }
        
        /* Reference Display */
        .reference-display {
            background: rgba(<?php echo $buttonRgbStr; ?>, 0.1) !important;
            border-color: <?php echo $buttonColor; ?> !important;
        }
        
        .reference-display .text-blue-300 {
            color: <?php echo $buttonColor; ?> !important;
        }
        
        /* Store Link Hover */
        .store-link-hover:hover {
            color: <?php echo $buttonHoverColor; ?> !important;
        }
        
        /* Store Link Color */
        .store-link-color {
            color: <?php echo $buttonColor; ?> !important;
        }
        
        .store-link-color:hover {
            color: <?php echo $buttonHoverColor; ?> !important;
        }
        
        <?php 
        $formTheme = $store['form_theme'] ?? 'dark';
        if ($formTheme === 'light'): 
        ?>
        /* Light Form Theme - Glass-like Professional Design */
        .form-container {
            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,
        .form-header h2 {
            color: #1f2937 !important;
        }
        
        .form-container p,
        .form-container label,
        .form-header p {
            color: #4b5563 !important;
        }
        
        .form-container .text-gray-400,
        .form-header .text-gray-400 {
            color: #6b7280 !important;
        }
        
        .form-container .text-gray-500 {
            color: #6b7280 !important;
        }
        
        .form-header .text-blue-400 {
            color: <?php echo htmlspecialchars($store['button_color'] ?? '#3b82f6'); ?> !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;
        }
        
        /* Status Banner - Light Theme */
        .status-banner {
            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;
        }
        
        .status-banner h3 {
            color: #1f2937 !important;
        }
        
        .status-banner p {
            color: #6b7280 !important;
        }
        
        .status-banner .text-gray-400 {
            color: #6b7280 !important;
        }
        <?php else: ?>
        /* Dark Form Theme (default) */
        .form-container {
            background: linear-gradient(135deg, #1f2937 0%, #111827 100%) !important;
            border-color: #374151 !important;
        }
        
        /* Status Banner - Dark Theme */
        .status-banner {
            background: linear-gradient(135deg, #1f2937 0%, #111827 100%) !important;
            border-color: #374151 !important;
        }
        <?php endif; ?>
        
        .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%);
        }
        
        .package-card {
            transition: all 0.3s ease;
        }
        
        .package-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(59, 130, 246, 0.3);
        }
        
        /* Modal Animation */
        @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;
        }
        
        /* Mobile optimizations */
        @media (max-width: 640px) {
            .animate-fadeIn {
                animation: fadeIn 0.2s ease-out;
            }
        }
    </style>
</head>

<body>
    <!-- Show Dashboard Link if logged in -->
    <?php if (isset($_SESSION['user_id'])): ?>
    <div class="fixed top-4 right-4 z-50">
        <?php
        // Check if user is a store owner
        $userStore = $storeManager->getStoreByOwnerId($_SESSION['user_id']);
        $dashboardUrl = $userStore ? 'pages/store_dashboard.php' : 'user_index.php';
        ?>
        <a href="<?php echo $dashboardUrl; ?>" 
           class="bg-white/90 hover:bg-white text-gray-800 px-4 py-2 rounded-lg shadow-lg flex items-center gap-2 transition-all transform hover:scale-105 backdrop-blur-sm border border-white/20 font-medium">
            <i class="fas fa-tachometer-alt"></i>
            <span class="hidden sm:inline">Dashboard</span>
            <span class="sm:hidden">Dashboard</span>
        </a>
    </div>
    <?php endif; ?>
    
    <!-- Store 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 htmlspecialchars($store['store_name']); ?>" 
                         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 border-4 border-white">
                        <i class="fas fa-store text-4xl text-white"></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-store text-4xl"></i>
                </div>
                <?php endif; ?>
                
                <h1 class="text-4xl font-bold mb-2"><?php echo htmlspecialchars($store['store_name']); ?></h1>
                <?php if (!empty($store['description'])): ?>
                <p class="text-lg mb-4" style="color: rgba(255, 255, 255, 0.9);"><?php echo htmlspecialchars($store['description']); ?></p>
                <?php endif; ?>
                
                <!-- Buy Now Button -->
                <div class="mb-6">
                    <button onclick="scrollToForm()" 
                            class="store-button text-white px-8 py-3 rounded-xl text-lg font-semibold shadow-lg hover:shadow-xl transition-all transform hover:scale-105 flex items-center justify-center gap-2 mx-auto">
                        <i class="fas fa-shopping-cart"></i>
                        <span>Buy Now</span>
                        <i class="fas fa-arrow-down"></i>
                    </button>
                </div>
                
                <!-- Contact Info -->
                <div class="flex justify-center gap-6 mt-6 flex-wrap">
                    <?php if (!empty($store['phone'])): ?>
                    <a href="tel:<?php echo htmlspecialchars($store['phone']); ?>" 
                       class="flex items-center gap-2 text-white transition store-link-hover">
                        <i class="fas fa-phone"></i>
                        <span><?php echo htmlspecialchars($store['phone']); ?></span>
                    </a>
                    <?php endif; ?>
                    
                    <?php if (!empty($store['whatsapp'])): ?>
                    <a href="https://wa.me/<?php echo preg_replace('/\D/', '', $store['whatsapp']); ?>" 
                       target="_blank"
                       class="flex items-center gap-2 text-white transition store-link-hover">
                        <i class="fab fa-whatsapp"></i>
                        <span>WhatsApp</span>
                    </a>
                    <?php endif; ?>
                    
                    <?php if (!empty($whatsappGroupLink)): ?>
                    <a href="<?php echo htmlspecialchars($whatsappGroupLink); ?>" 
                       target="_blank"
                       class="flex items-center gap-2 bg-green-600 hover:bg-green-700 px-4 py-2 rounded-lg text-white transition">
                        <i class="fab fa-whatsapp"></i>
                        <span>Join WhatsApp Group</span>
                    </a>
                    <?php endif; ?>
                </div>
                
                <!-- Working Hours -->
                <?php
                $workingHours = [];
                if (!empty($store['working_hours'])) {
                    $workingHours = json_decode($store['working_hours'], true) ?: [];
                }
                
                if (!empty($workingHours)):
                    $days = [
                        'monday' => 'Mon',
                        'tuesday' => 'Tue',
                        'wednesday' => 'Wed',
                        'thursday' => 'Thu',
                        'friday' => 'Fri',
                        'saturday' => 'Sat',
                        'sunday' => 'Sun'
                    ];
                    
                    // Get current day
                    $currentDay = strtolower(date('l'));
                    $currentDayKey = $currentDay;
                    $isOpen = false;
                    $currentHours = null;
                    
                    if (isset($workingHours[$currentDayKey]) && $workingHours[$currentDayKey]['enabled']) {
                        $currentHours = $workingHours[$currentDayKey];
                        $currentTime = date('H:i');
                        $isOpen = ($currentTime >= $currentHours['open'] && $currentTime <= $currentHours['close']);
                    }
                ?>
                <div class="mt-4 sm:mt-6 pt-4 sm:pt-6 border-t border-white/20">
                    <div class="flex flex-col sm:flex-row items-center justify-center gap-2 sm:gap-2 mb-3">
                        <div class="flex items-center gap-2">
                            <i class="fas fa-clock text-sm sm:text-base"></i>
                            <span class="font-semibold text-sm sm:text-base">Working Hours</span>
            </div>
                        <?php if ($isOpen): ?>
                        <span class="px-2 py-1 bg-green-500/30 border border-green-400/50 rounded text-xs font-medium whitespace-nowrap">
                            <i class="fas fa-circle text-green-400 text-[8px] mr-1"></i>Open Now
                        </span>
                        <?php elseif ($currentHours): ?>
                        <span class="px-2 py-1 bg-red-500/30 border border-red-400/50 rounded text-xs font-medium whitespace-nowrap">
                            <i class="fas fa-circle text-red-400 text-[8px] mr-1"></i>Closed
                        </span>
                        <?php endif; ?>
                    </div>
                    <div class="flex flex-col sm:flex-row sm:flex-wrap justify-center gap-2 sm:gap-x-4 sm:gap-y-2 text-xs sm:text-sm px-2" style="color: rgba(255, 255, 255, 0.9);">
                        <?php foreach ($days as $dayKey => $dayName): ?>
                        <?php if (isset($workingHours[$dayKey]) && $workingHours[$dayKey]['enabled']): ?>
                        <div class="flex items-center justify-center sm:justify-start gap-2 <?php echo $dayKey === $currentDayKey ? 'font-semibold' : ''; ?>">
                            <span class="min-w-[40px] sm:min-w-[45px]"><?php echo $dayName; ?>:</span>
                            <span class="whitespace-nowrap"><?php echo date('g:i A', strtotime($workingHours[$dayKey]['open'])); ?> - <?php echo date('g:i A', strtotime($workingHours[$dayKey]['close'])); ?></span>
                        </div>
                        <?php endif; ?>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Main Content -->
    <div class="container mx-auto px-4 py-8">
        <?php if (isset($error_message)): ?>
        <div class="bg-red-900 border border-red-700 text-red-300 px-4 py-3 rounded mb-6">
            <i class="fas fa-exclamation-triangle mr-2"></i>
            <?php echo htmlspecialchars($error_message); ?>
        </div>
        <?php endif; ?>
        
        <?php if ($paymentMessage): ?>
        <div class="max-w-lg mx-auto mb-6">
            <?php if ($paymentMessageType === 'success'): ?>
            <div class="bg-green-900/50 border border-green-700 text-green-300 px-4 py-3 rounded-lg flex items-start animate-fadeIn">
                <i class="fas fa-check-circle mr-2 mt-0.5 flex-shrink-0"></i>
                <div class="flex-1">
                    <p class="font-semibold mb-1">Payment Successful! 🎉</p>
                    <p class="text-sm"><?php echo htmlspecialchars($paymentMessage); ?></p>
                    <?php if ($orderReference): ?>
                    <p class="text-xs mt-2 text-gray-400">Order Reference: <span class="font-mono text-gray-300"><?php echo htmlspecialchars($orderReference); ?></span></p>
                    <?php endif; ?>
                </div>
                <button onclick="this.parentElement.remove()" class="ml-2 text-green-400 hover:text-green-200 transition-colors">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <?php else: ?>
            <div class="bg-red-900/50 border border-red-700 text-red-300 px-4 py-3 rounded-lg flex items-start animate-fadeIn">
                <i class="fas fa-exclamation-triangle mr-2 mt-0.5 flex-shrink-0"></i>
                <div class="flex-1">
                    <p class="font-semibold mb-1">Payment Error</p>
                    <p class="text-sm"><?php echo htmlspecialchars($paymentMessage); ?></p>
                    <?php if ($orderReference): ?>
                    <p class="text-xs mt-2 text-gray-400">Order Reference: <span class="font-mono text-gray-300"><?php echo htmlspecialchars($orderReference); ?></span></p>
                    <?php endif; ?>
                </div>
                <button onclick="this.parentElement.remove()" class="ml-2 text-red-400 hover:text-red-200 transition-colors">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <!-- Check Order Status Section -->
        <div class="max-w-lg mx-auto mb-6">
            <div class="status-banner bg-gray-800 rounded-xl border border-gray-700 p-4">
                <div class="flex items-center justify-between">
                    <div class="flex items-center gap-3">
                        <div class="w-12 h-12 store-button rounded-lg flex items-center justify-center">
                            <i class="fas fa-search text-white"></i>
                        </div>
                        <div>
                            <h3 class="text-white font-semibold">Check Your Order Status</h3>
                            <p class="text-xs text-gray-400">Enter your order reference to track your order</p>
                        </div>
                    </div>
                    <a href="order-status.php" 
                       class="px-4 py-2 store-button text-white rounded-lg text-sm font-medium transition-colors whitespace-nowrap">
                        <i class="fas fa-search mr-2"></i>Check Status
                    </a>
                </div>
            </div>
        </div>

        <!-- Order Form - Compact & Professional -->
        <div class="max-w-lg mx-auto" id="orderFormSection">
            <?php if (!$isStoreActive): ?>
            <!-- Store Inactive Message -->
            <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-red-600">
                <div class="text-center">
                    <div class="w-16 h-16 bg-red-600 rounded-full flex items-center justify-center mx-auto mb-4">
                        <i class="fas fa-pause text-white text-2xl"></i>
                    </div>
                    <h2 class="text-xl sm:text-2xl font-bold text-white mb-2">
                        Store Currently Inactive
                    </h2>
                    <p class="text-gray-400 mb-4">
                        This store is currently not accepting orders. Please check back later or contact the store owner.
                    </p>
                    <div class="bg-red-900/30 border border-red-700 rounded-lg p-3 text-sm text-red-300">
                        <i class="fas fa-info-circle mr-2"></i>
                        Orders cannot be placed while the store is inactive.
                    </div>
                </div>
            </div>
            <?php else: ?>
            <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-5">
                    <h2 class="text-xl sm:text-2xl font-bold text-white mb-1">
                        <i class="fas fa-shopping-cart mr-2" style="color: <?php echo htmlspecialchars($store['button_color'] ?? '#3b82f6'); ?>;"></i>
                        Place Your Order
                    </h2>
                    <p class="text-xs text-gray-400">Quick & Easy Data Bundle Purchase</p>
                </div>

                <form id="orderForm" class="space-y-4">
                    <input type="hidden" name="store_id" value="<?php echo $store['id']; ?>">
                    
                    <!-- Network Selection -->
                    <div>
                        <label class="block text-xs font-medium text-gray-400 mb-1.5">
                            Network <span class="text-red-400">*</span>
                        </label>
                        <select id="network" name="network" required
                                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 transition-all">
                            <option value="">Choose network...</option>
                            <?php foreach ($networks as $key => $label): ?>
                            <option value="<?php echo $key; ?>"><?php echo $label; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <!-- Package Selection -->
                    <div>
                        <label class="block text-xs font-medium text-gray-400 mb-1.5">
                            Data Package <span class="text-red-400">*</span>
                        </label>
                        <input type="text" id="package" name="package" required
                               placeholder="e.g., 1GB, 2GB, 500MB"
                               inputmode="text"
                               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 transition-all"
                               autocomplete="off"
                               autocorrect="off"
                               autocapitalize="off"
                               spellcheck="false">
                        <p class="text-xs text-gray-500 mt-1.5">Type package size (e.g., 1GB, 2GB)</p>
                        <div id="packageError" class="hidden mt-1.5 text-xs text-red-400 flex items-center gap-1">
                            <i class="fas fa-exclamation-circle text-xs"></i>
                            <span id="packageErrorText"></span>
                        </div>
                    </div>

                    <!-- Phone Number -->
                    <div>
                        <label class="block text-xs font-medium text-gray-400 mb-1.5">
                            Phone Number <span class="text-red-400">*</span>
                        </label>
                        <input type="tel" id="phone" name="phone" required
                               placeholder="0247965501"
                               pattern="[0-9]{10}"
                               maxlength="10"
                               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 transition-all">
                        <p class="text-xs text-gray-500 mt-1.5">10-digit number starting with 0</p>
                        <div id="phoneError" class="hidden mt-1.5 text-xs text-red-400 flex items-center gap-1">
                            <i class="fas fa-exclamation-circle text-xs"></i>
                            <span id="phoneErrorText"></span>
                        </div>
                    </div>

                    <!-- Email (Optional but recommended for Paystack) -->
                    <div>
                        <label class="block text-xs font-medium text-gray-400 mb-1.5">
                            Email Address <span class="text-gray-500 text-xs">(Optional)</span>
                        </label>
                        <input type="email" id="email" name="email"
                               placeholder="your.email@example.com"
                               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 transition-all">
                        <p class="text-xs text-gray-500 mt-1.5">Required for Paystack payment receipts</p>
                        <div id="emailError" class="hidden mt-1.5 text-xs text-red-400 flex items-center gap-1">
                            <i class="fas fa-exclamation-circle text-xs"></i>
                            <span id="emailErrorText"></span>
                        </div>
                    </div>

                    <!-- Price Display - Compact -->
                    <div id="priceDisplay" class="hidden bg-gradient-to-r from-blue-900/50 to-blue-800/50 border border-blue-600/50 rounded-xl p-3">
                        <div class="flex justify-between items-center">
                            <span class="text-sm text-gray-300">Total Price:</span>
                            <span class="text-xl font-bold text-white">GH₵ <span id="totalPrice">0.00</span></span>
                        </div>
                    </div>

                    <!-- Submit Button - Compact -->
                    <button type="submit" 
                            class="w-full store-button text-white py-3 rounded-xl font-semibold text-sm sm:text-base transition-all shadow-lg active:scale-[0.98] flex items-center justify-center gap-2">
                        <i class="fas fa-shopping-cart"></i>
                        <span>Place Order</span>
                    </button>
                </form>
            <?php endif; ?>

                <!-- WhatsApp Group Link -->
                <?php if (!empty($whatsappGroupLink)): ?>
                <div class="mt-4 pt-4 border-t border-gray-700">
                    <a href="<?php echo htmlspecialchars($whatsappGroupLink); ?>" 
                       target="_blank"
                       class="flex items-center justify-center gap-2 w-full bg-green-600 hover:bg-green-700 text-white py-2.5 rounded-lg text-sm font-medium transition-colors">
                        <i class="fab fa-whatsapp"></i>
                        <span>Join WhatsApp Community</span>
                    </a>
                </div>
                <?php endif; ?>
                
                <!-- Agent Sign-In Section - At Bottom of Form -->
                <?php if (!isset($_SESSION['user_id'])): ?>
                <div class="mt-4 pt-4 border-t border-gray-700">
                    <div class="bg-gray-700/50 rounded-xl p-4 border border-gray-600">
                        <div class="flex flex-col sm:flex-row items-center justify-between gap-4">
                            <div class="flex-1 text-center sm:text-left">
                                <h3 class="text-sm sm:text-base font-bold text-white mb-1.5">
                                    <i class="fas fa-user-tie mr-2"></i>
                                    Want to be an Agent?
                                </h3>
                                <p class="text-gray-300 text-xs sm:text-sm mb-2">
                                    If you wish to be an agent of this store, please contact the store owner.
                                </p>
                                <?php if (!empty($storeOwnerWhatsApp) || !empty($storeOwnerPhone) || !empty($storeOwnerEmail)): ?>
                                <div class="flex flex-col sm:flex-row items-center sm:items-start gap-2 sm:gap-3 text-xs text-gray-400">
                                    <?php if (!empty($storeOwnerWhatsApp)): ?>
                                    <a href="https://wa.me/<?php echo preg_replace('/\D/', '', $storeOwnerWhatsApp); ?>" 
                                       target="_blank"
                                       class="flex items-center gap-1.5 hover:text-white transition-colors">
                                        <i class="fab fa-whatsapp text-xs"></i>
                                        <span>WhatsApp: <?php echo htmlspecialchars($storeOwnerWhatsApp); ?></span>
                                    </a>
                                    <?php elseif (!empty($storeOwnerPhone)): ?>
                                    <a href="tel:<?php echo htmlspecialchars($storeOwnerPhone); ?>" 
                                       class="flex items-center gap-1.5 hover:text-white transition-colors">
                                        <i class="fas fa-phone text-xs"></i>
                                        <span><?php echo htmlspecialchars($storeOwnerPhone); ?></span>
                                    </a>
                                    <?php endif; ?>
                                    <?php if (!empty($storeOwnerEmail)): ?>
                                    <a href="mailto:<?php echo htmlspecialchars($storeOwnerEmail); ?>" 
                                       class="flex items-center gap-1.5 hover:text-white transition-colors">
                                        <i class="fas fa-envelope text-xs"></i>
                                        <span><?php echo htmlspecialchars($storeOwnerEmail); ?></span>
                                    </a>
                                    <?php endif; ?>
                                </div>
                                <?php endif; ?>
                            </div>
                            <div class="flex-shrink-0">
                                <a href="login.php<?php echo !empty($storeSlug) ? '?store=' . urlencode($storeSlug) : ''; ?>" 
                                   class="bg-white/90 hover:bg-white text-gray-800 px-4 py-2 rounded-lg shadow-md flex items-center gap-2 transition-all transform hover:scale-105 backdrop-blur-sm border border-white/20 font-medium text-sm whitespace-nowrap">
                                    <i class="fas fa-sign-in-alt"></i>
                                    <span>Agent Sign In</span>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script>
        // Smooth scroll to form function
        function scrollToForm() {
            const formSection = document.getElementById('orderFormSection');
            if (formSection) {
                formSection.scrollIntoView({ 
                    behavior: 'smooth', 
                    block: 'start' 
                });
                // Focus on the first input after scrolling
                setTimeout(() => {
                    const networkSelect = document.getElementById('network');
                    if (networkSelect) {
                        networkSelect.focus();
                    }
                }, 500);
            }
        }
        
        const storeId = <?php echo $store['id']; ?>;
        const networkSelect = document.getElementById('network');
        const packageInput = document.getElementById('package');
        const packageError = document.getElementById('packageError');
        const packageErrorText = document.getElementById('packageErrorText');
        const phoneInput = document.getElementById('phone');
        const phoneError = document.getElementById('phoneError');
        const phoneErrorText = document.getElementById('phoneErrorText');
        const priceDisplay = document.getElementById('priceDisplay');
        const totalPriceEl = document.getElementById('totalPrice');
        const orderForm = document.getElementById('orderForm');
        const storeActive = <?php echo $isStoreActive ? 'true' : 'false'; ?>;
        
        // Only initialize form if store is active and form exists
        if (orderForm && storeActive) {
        
        let currentPrice = 0;
        let isValidPackage = false;
        let isValidPhone = false;
        let validationTimeout = null;
        
        // Phone number validation - only allow digits, max 10
        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.slice(0, 10);
            }
            
            // Validate phone number
            const phone = this.value.trim();
            phoneError.classList.add('hidden');
            phoneInput.classList.remove('border-red-500', 'border-green-500');
            
            if (phone.length === 0) {
                isValidPhone = false;
                return;
            }
            
            if (phone.length < 10) {
                phoneErrorText.textContent = 'Phone number must be exactly 10 digits';
                phoneError.classList.remove('hidden');
                phoneInput.classList.add('border-red-500');
                isValidPhone = false;
            } else if (phone.length === 10) {
                // Check if it starts with 0
                if (phone.charAt(0) !== '0') {
                    phoneErrorText.textContent = 'Phone number must start with 0 (e.g., 0247965501)';
                    phoneError.classList.remove('hidden');
                    phoneInput.classList.add('border-red-500');
                    isValidPhone = false;
                } else {
                    phoneError.classList.add('hidden');
                    phoneInput.classList.remove('border-red-500');
                    phoneInput.classList.add('border-green-500');
                    isValidPhone = true;
                }
            }
        });
        
        // Validate on blur
        phoneInput.addEventListener('blur', function() {
            const phone = this.value.trim();
            if (phone.length > 0 && phone.length < 10) {
                phoneErrorText.textContent = 'Phone number must be exactly 10 digits';
                phoneError.classList.remove('hidden');
                phoneInput.classList.add('border-red-500');
                isValidPhone = false;
            } else if (phone.length === 10 && phone.charAt(0) !== '0') {
                phoneErrorText.textContent = 'Phone number must start with 0 (e.g., 0247965501)';
                phoneError.classList.remove('hidden');
                phoneInput.classList.add('border-red-500');
                isValidPhone = false;
            }
        });
        
        // Email validation (optional field)
        const emailInput = document.getElementById('email');
        const emailError = document.getElementById('emailError');
        const emailErrorText = document.getElementById('emailErrorText');
        
        if (emailInput) {
            emailInput.addEventListener('blur', function() {
                const email = this.value.trim();
                emailError.classList.add('hidden');
                emailInput.classList.remove('border-red-500', 'border-green-500');
                
                // Only validate if email is provided (field is optional)
                if (email.length > 0) {
                    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                    if (!emailRegex.test(email)) {
                        emailErrorText.textContent = 'Please enter a valid email address';
                        emailError.classList.remove('hidden');
                        emailInput.classList.add('border-red-500');
                    } else {
                        emailInput.classList.add('border-green-500');
                    }
                }
            });
        }
        
        // Reset package validation when network changes
        networkSelect.addEventListener('change', function() {
            const network = this.value;
            
            if (!network) {
                packageInput.value = '';
                packageInput.disabled = true;
                priceDisplay.classList.add('hidden');
                packageError.classList.add('hidden');
                isValidPackage = false;
                return;
            }
            
            packageInput.disabled = false;
            packageInput.value = '';
            priceDisplay.classList.add('hidden');
            packageError.classList.add('hidden');
            isValidPackage = false;
        });
        
        // Validate package when user types
        packageInput.addEventListener('input', function() {
            clearTimeout(validationTimeout);
            
            // Sanitize input for iPhone compatibility - remove non-breaking spaces, special Unicode chars
            let packageSize = this.value.trim();
            
            // Replace non-breaking spaces and other Unicode whitespace with regular spaces
            packageSize = packageSize.replace(/[\u00A0\u2000-\u200B\u202F\u205F\u3000]/g, ' ');
            
            // Remove any invisible/special characters that iPhone might add
            packageSize = packageSize.replace(/[\u200C-\u200F\uFEFF]/g, '');
            
            // Normalize multiple spaces to single space
            packageSize = packageSize.replace(/\s+/g, ' ');
            
            // Update the input value with sanitized version
            if (this.value !== packageSize) {
                this.value = packageSize;
            }
            
            const network = networkSelect.value;
            
            // Hide error and price while typing
            packageError.classList.add('hidden');
            priceDisplay.classList.add('hidden');
            isValidPackage = false;
            
            if (!packageSize) {
                return;
            }
            
            if (!network) {
                packageErrorText.textContent = 'Please select a network first';
                packageError.classList.remove('hidden');
                return;
            }
            
            // Debounce validation - wait 500ms after user stops typing
            validationTimeout = setTimeout(() => {
                validatePackage(packageSize, network);
            }, 500);
        });
        
        // Also validate on blur
        packageInput.addEventListener('blur', function() {
            clearTimeout(validationTimeout);
            
            // Sanitize input for iPhone compatibility
            let packageSize = this.value.trim();
            packageSize = packageSize.replace(/[\u00A0\u2000-\u200B\u202F\u205F\u3000]/g, ' ');
            packageSize = packageSize.replace(/[\u200C-\u200F\uFEFF]/g, '');
            packageSize = packageSize.replace(/\s+/g, ' ');
            
            if (this.value !== packageSize) {
                this.value = packageSize;
            }
            
            const network = networkSelect.value;
            
            if (packageSize && network) {
                validatePackage(packageSize, network);
            }
        });
        
        // Function to validate package availability
        function validatePackage(packageSize, network) {
            if (!packageSize || !network) {
                return;
            }
            
            // Show loading state
            packageInput.classList.remove('border-red-500', 'border-green-500', 'border-blue-500');
            packageInput.classList.add('border-yellow-500');
            
            fetch('check_package_availability.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `store_id=${storeId}&network=${network}&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 => {
                        throw new Error('Server returned invalid response: ' + text.substring(0, 200));
                    });
                }
            })
            .then(data => {
                packageInput.classList.remove('border-yellow-500');
                
                if (data.success && data.available) {
                    // Package is available
                    packageInput.classList.remove('border-red-500', 'border-blue-500');
                    packageInput.classList.add('border-green-500');
                    packageError.classList.add('hidden');
                    
                    currentPrice = parseFloat(data.price.replace(/,/g, ''));
                    totalPriceEl.textContent = data.price;
                    priceDisplay.classList.remove('hidden');
                    isValidPackage = true;
                } else {
                    // Package is not available
                    packageInput.classList.remove('border-green-500', 'border-blue-500');
                    packageInput.classList.add('border-red-500');
                    packageErrorText.textContent = data.message || 'This package size is not available';
                    packageError.classList.remove('hidden');
                    priceDisplay.classList.add('hidden');
                    isValidPackage = false;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                packageInput.classList.remove('border-yellow-500', 'border-green-500', 'border-blue-500');
                packageInput.classList.add('border-red-500');
                packageErrorText.textContent = 'Error checking package availability. Please try again.';
                packageError.classList.remove('hidden');
                priceDisplay.classList.add('hidden');
                isValidPackage = false;
            });
        }
        
        // Handle form submission
        orderForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // Check if store is active (client-side validation)
            const storeActive = <?php echo $isStoreActive ? 'true' : 'false'; ?>;
            if (!storeActive) {
                alert('This store is currently inactive and not accepting orders. Please check back later.');
                return;
            }
            
            // Sanitize package size input for iPhone compatibility
            let packageSize = packageInput.value.trim();
            packageSize = packageSize.replace(/[\u00A0\u2000-\u200B\u202F\u205F\u3000]/g, ' ');
            packageSize = packageSize.replace(/[\u200C-\u200F\uFEFF]/g, '');
            packageSize = packageSize.replace(/\s+/g, ' ');
            
            if (packageInput.value !== packageSize) {
                packageInput.value = packageSize;
            }
            
            const network = networkSelect.value;
            const phone = phoneInput.value.trim();
            
            // Validate phone number before submission
            if (!phone) {
                phoneErrorText.textContent = 'Please enter a phone number';
                phoneError.classList.remove('hidden');
                phoneInput.classList.add('border-red-500');
                phoneInput.focus();
                return;
            }
            
            if (phone.length !== 10) {
                phoneErrorText.textContent = 'Phone number must be exactly 10 digits';
                phoneError.classList.remove('hidden');
                phoneInput.classList.add('border-red-500');
                phoneInput.focus();
                return;
            }
            
            if (phone.charAt(0) !== '0') {
                phoneErrorText.textContent = 'Phone number must start with 0 (e.g., 0247965501)';
                phoneError.classList.remove('hidden');
                phoneInput.classList.add('border-red-500');
                phoneInput.focus();
                return;
            }
            
            // Validate package before submission
            if (!packageSize) {
                packageErrorText.textContent = 'Please enter a package size';
                packageError.classList.remove('hidden');
                packageInput.focus();
                return;
            }
            
            if (!network) {
                alert('Please select a network');
                networkSelect.focus();
                return;
            }
            
            if (!isValidPackage) {
                // Re-validate package before submission
                validatePackage(packageSize, network);
                
                // Wait a bit for validation to complete, then check again
                setTimeout(() => {
                    if (!isValidPackage) {
                        packageErrorText.textContent = 'Please enter a valid package size';
                        packageError.classList.remove('hidden');
                        packageInput.focus();
                        return;
                    }
                    
                    // If valid, proceed with submission
                    submitOrder();
                }, 600);
            } else {
                submitOrder();
            }
        });
        
        function submitOrder() {
            const formData = new FormData(orderForm);
            const submitBtn = orderForm.querySelector('button[type="submit"]');
            const originalBtnText = submitBtn.innerHTML;
            
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Processing...';
            
            fetch('process_store_order.php', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                const contentType = response.headers.get('content-type');
                if (contentType && contentType.includes('application/json')) {
                    return response.json();
                } else {
                    return response.text().then(text => {
                        throw new Error('Server returned invalid response: ' + text.substring(0, 200));
                    });
                }
            })
            .then(data => {
                // Debug: Log the response data
                console.log('Order response data:', data);
                console.log('MoMo name:', data.momo_name);
                console.log('Owner phone:', data.owner_phone);
                
                if (data.success) {
                    // Check if Paystack payment is available
                    if (data.payment_method === 'paystack' && data.paystack_auth_url) {
                        // Redirect to Paystack payment page
                        window.location.href = data.paystack_auth_url;
                    } else {
                        // Show payment modal with order reference (Mobile Money)
                        showPaymentModal(data);
                        orderForm.reset();
                        priceDisplay.classList.add('hidden');
                        packageError.classList.add('hidden');
                        phoneError.classList.add('hidden');
                        packageInput.classList.remove('border-green-500', 'border-red-500', 'border-blue-500');
                        phoneInput.classList.remove('border-green-500', 'border-red-500', 'border-blue-500');
                        isValidPackage = false;
                        isValidPhone = false;
                    }
                } else {
                    alert('Order failed: ' + (data.message || 'Unknown error'));
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred. Please try again.');
            })
            .finally(() => {
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalBtnText;
            });
        }
        
        // Show payment instructions modal - Compact & Mobile-Friendly
        function showPaymentModal(data) {
            // Debug: Log modal data
            console.log('Modal data - momo_name:', data.momo_name, 'owner_phone:', data.owner_phone);
            
            const modal = document.createElement('div');
            modal.className = 'fixed inset-0 bg-black bg-opacity-60 flex items-center justify-center z-50 p-3 sm:p-4';
            modal.innerHTML = `
                <div class="bg-gradient-to-br from-gray-800 to-gray-900 rounded-2xl shadow-2xl w-full max-w-sm border border-gray-700 overflow-hidden animate-fadeIn">
                    <!-- Success Header -->
                    <div class="bg-gradient-to-r from-green-500 to-emerald-500 p-4 text-center relative overflow-hidden">
                        <div class="absolute inset-0 bg-white opacity-10"></div>
                        <div class="relative">
                            <div class="w-14 h-14 bg-white rounded-full flex items-center justify-center mx-auto mb-2 shadow-lg">
                                <i class="fas fa-check text-green-600 text-xl"></i>
                            </div>
                            <h2 class="text-lg font-bold text-white">Order Created! 🎉</h2>
                            ${data.momo_name && data.owner_phone ? `
                            <div class="mt-2 text-sm text-white/90">
                                <i class="fas fa-mobile-alt mr-1"></i>
                                Pay to: <strong>${data.momo_name}</strong> (${data.owner_phone})
                            </div>
                            ` : ''}
                        </div>
                    </div>
                    
                    <!-- Compact Content -->
                    <div class="p-4 space-y-3">
                        <!-- Order Reference - Prominent -->
                        <div class="reference-display rounded-xl p-3 text-center">
                            <div class="text-xs mb-1" style="color: <?php echo htmlspecialchars($store['button_color'] ?? '#3b82f6'); ?>;">Reference Code</div>
                            <div class="text-2xl font-bold text-white tracking-widest font-mono">${data.order_reference || 'N/A'}</div>
                        </div>
                        
                        <!-- Order Details - Compact Grid -->
                        <div class="bg-gray-700/50 rounded-xl p-3 space-y-2 text-sm">
                            <div class="flex justify-between items-center">
                                <span class="text-gray-400">Package:</span>
                                <span class="text-white font-semibold">${data.package || 'N/A'}</span>
                            </div>
                            <div class="flex justify-between items-center">
                                <span class="text-gray-400">Phone:</span>
                                <span class="text-white font-semibold">${data.phone || 'N/A'}</span>
                            </div>
                            <div class="flex justify-between items-center pt-2 border-t border-gray-600">
                                <span class="text-gray-400">Amount:</span>
                                <span class="text-green-400 font-bold text-base">GH₵ ${data.amount || '0.00'}</span>
                            </div>
                        </div>
                        
                        <!-- Payment Info - Compact -->
                        <div class="bg-yellow-900/30 border border-yellow-700/50 rounded-xl p-3">
                            <div class="flex items-start gap-2">
                                <i class="fas fa-info-circle text-yellow-400 text-xs mt-0.5 flex-shrink-0"></i>
                                <div class="text-yellow-200 text-xs leading-relaxed">
                                    ${data.momo_name ? `
                                    Send <strong>GH₵ ${data.amount}</strong> to <strong class="text-yellow-300">${data.momo_name}</strong>${data.owner_phone ? ` (${data.owner_phone})` : ''} with reference <strong>${data.order_reference || 'N/A'}</strong>
                                    ` : `
                                    Send <strong>GH₵ ${data.amount}</strong>${data.owner_phone ? ` to ${data.owner_phone}` : ' to store owner'} with reference <strong>${data.order_reference || 'N/A'}</strong>
                                    `}
                                </div>
                            </div>
                        </div>
                        
                        <!-- Check Order Status Button -->
                        <a href="order-status.php?ref=${data.order_reference || ''}" 
                           class="block store-button text-white rounded-xl p-3 text-center transition-colors font-medium">
                            <i class="fas fa-search mr-2"></i>Check Order Status
                        </a>
                        
                        <!-- Payment Number - Compact -->
                        ${data.owner_phone ? `
                        <a href="tel:${data.owner_phone}" 
                           class="block bg-gray-700/50 hover:bg-gray-700 rounded-xl p-3 text-center transition-colors">
                            <div class="text-xs text-gray-400 mb-1">Send Payment To</div>
                            ${data.momo_name ? `
                            <div class="text-sm font-semibold mb-1" style="color: <?php echo htmlspecialchars($store['button_color'] ?? '#3b82f6'); ?>;">
                                ${data.momo_name}
                            </div>
                            ` : ''}
                            <div class="text-base font-bold text-white">
                                <i class="fas fa-mobile-alt mr-2" style="color: <?php echo htmlspecialchars($store['button_color'] ?? '#3b82f6'); ?>;"></i>${data.owner_phone}
                            </div>
                        </a>
                        ` : ''}
                    </div>
                    
                    <!-- Close Button -->
                    <div class="p-3 pt-0">
                        <button onclick="this.closest('.fixed').remove()" 
                                class="w-full bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white py-2.5 rounded-xl font-semibold text-sm transition-all shadow-lg active:scale-95">
                            <i class="fas fa-check mr-2"></i>Got It
                        </button>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
            
            // Close on outside click
            modal.addEventListener('click', function(e) {
                if (e.target === modal) {
                    modal.remove();
                }
            });
            
            // Prevent body scroll when modal is open
            document.body.style.overflow = 'hidden';
            
            // Restore scroll when modal is removed
            const closeBtn = modal.querySelector('button');
            const originalClose = closeBtn.onclick;
            closeBtn.onclick = function() {
                document.body.style.overflow = '';
                if (originalClose) originalClose.call(this);
                modal.remove();
            };
        }
        } // End of orderForm check - only runs if store is active
    </script>
</body>
</html>



