<?php
/**
 * D-Bundles Stores - Multi-Store Platform Homepage
 * Your own data bundle store in minutes!
 */
// Start output buffering to prevent any content from being sent before redirects
ob_start();
session_start();
require_once 'config.php';

// SECURITY: Block ALL logged-in users from accessing the home page
// Agents and store owners should always be redirected to login page
// CRITICAL: Check session FIRST - if user_id OR role exists, redirect immediately
$hasSession = false;

// Check for user_id in session
if (isset($_SESSION['user_id']) && !empty($_SESSION['user_id'])) {
    $hasSession = true;
}

// Also check for role in session (additional safeguard)
if (isset($_SESSION['role']) && !empty($_SESSION['role'])) {
    $hasSession = true;
}

// If any session data indicates logged-in user, redirect immediately
if ($hasSession) {
    // Clear any output buffer
    while (ob_get_level()) {
        ob_end_clean();
    }
    
    // Ensure no output has been sent
    if (!headers_sent()) {
        header('Location: login.php');
        exit();
    } else {
        // If headers already sent, use JavaScript redirect as fallback
        echo '<script>window.location.href = "login.php";</script>';
        exit();
    }
}

// If we reach here, user is not logged in and is allowed to see the home page
// Clean up output buffer properly
while (ob_get_level() > 0) {
    ob_end_flush();
}

// Get the secret key for store registration
$registration_key = $config['store_registration_key'] ?? 'd-bundles-2024-secret-key';
$register_url = 'register.php?key=' . urlencode($registration_key);
?>
<!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>D-Bundles Stores</title>
    
    <!-- PWA Meta Tags -->
    <meta name="theme-color" content="#2563eb">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    <meta name="apple-mobile-web-app-title" content="D-Bundles">
    
    <!-- PWA Manifest -->
    <link rel="manifest" href="manifest.json">
    
    <!-- Apple Touch Icons -->
    <link rel="apple-touch-icon" href="assets/images/icon-192.png">
    
    <!-- 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;
        }
        
    </style>
</head>

<body class="bg-gray-50 min-h-screen flex flex-col">
    <!-- Minimal Navigation -->
    <nav class="bg-white shadow-sm">
        <div class="container mx-auto px-4 py-4">
            <div class="flex items-center justify-between">
                <div class="flex items-center space-x-2">
                    <div class="w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center">
                        <span class="text-white font-bold">D</span>
                    </div>
                    <h1 class="text-xl font-bold text-gray-800">D-Bundles Stores</h1>
                </div>
                <a href="login.php" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition">
                        Sign In
                    </a>
            </div>
        </div>
    </nav>

    <!-- Minimal Hero Section -->
    <main class="flex-1 flex items-center justify-center py-20">
        <div class="container mx-auto px-4 text-center max-w-2xl">
            <h1 class="text-4xl md:text-5xl font-bold text-gray-800 mb-4">
                Create Your Own Data Bundle Store
                    </h1>
            <p class="text-xl text-gray-600 mb-8">
                Start selling data bundles with your own brand and custom pricing.
            </p>
            <div class="flex flex-col sm:flex-row gap-4 justify-center items-center">
                <a href="login.php" class="inline-block px-8 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-semibold text-lg transition">
                    Get Started
                </a>
                <!-- PWA Install Button (Always Visible) -->
                <button id="pwaInstallBtn" onclick="installPWA()" 
                        class="hidden inline-flex items-center px-6 py-3 bg-gradient-to-r from-green-600 to-green-700 text-white rounded-lg hover:from-green-700 hover:to-green-800 font-semibold text-lg transition-all shadow-lg transform hover:scale-105 active:scale-95">
                    <i class="fas fa-mobile-alt mr-2"></i>
                    <span>Install App</span>
                </button>
            </div>
        </div>
    </main>

    <!-- Minimal Footer -->
    <footer class="bg-gray-100 py-6">
        <div class="container mx-auto px-4 text-center text-sm text-gray-600">
            <p>&copy; 2024 D-Bundles Stores. All rights reserved.</p>
        </div>
    </footer>


    <script>
        let deferredPrompt = null;
        const installBtn = document.getElementById('pwaInstallBtn');
        const isStandalone = window.matchMedia('(display-mode: standalone)').matches || 
                            window.navigator.standalone === true;

        // Check if already installed
        if (isStandalone) {
            // App is already installed, hide install button
            if (installBtn) installBtn.style.display = 'none';
        }

        // Register Service Worker
        if ('serviceWorker' in navigator) {
            window.addEventListener('load', () => {
                navigator.serviceWorker.register('/sw.js')
                    .then((registration) => {
                        console.log('Service Worker registered:', registration);
                    })
                    .catch((error) => {
                        console.error('Service Worker registration failed:', error);
                        // Try with relative path if absolute fails
                        navigator.serviceWorker.register('sw.js')
                            .then((registration) => {
                                console.log('Service Worker registered (relative path):', registration);
                            })
                            .catch((err) => {
                                console.error('Service Worker registration failed (relative path):', err);
                            });
                    });
            });
        }

        // Listen for beforeinstallprompt event (Chrome, Edge, Android browsers)
        window.addEventListener('beforeinstallprompt', (e) => {
            // Prevent the mini-infobar from appearing
            e.preventDefault();
            // Stash the event so it can be triggered later
            deferredPrompt = e;
            
            // Show install button
            if (installBtn && !isStandalone) {
                installBtn.classList.remove('hidden');
            }
        });

        // Check if app is already installed
        window.addEventListener('appinstalled', () => {
            console.log('PWA was installed');
            if (installBtn) installBtn.style.display = 'none';
            deferredPrompt = null;
            
            // Show success message
            alert('App installed successfully! You can now access it from your home screen.');
        });

        // Install PWA function
        function installPWA() {
            if (deferredPrompt) {
                // Show the install prompt
                deferredPrompt.prompt();
                
                // Wait for the user to respond to the prompt
                deferredPrompt.userChoice.then((choiceResult) => {
                    if (choiceResult.outcome === 'accepted') {
                        console.log('User accepted the install prompt');
                    } else {
                        console.log('User dismissed the install prompt');
                    }
                    deferredPrompt = null;
                    if (installBtn) installBtn.style.display = 'none';
                });
            } else {
                // Fallback for browsers that don't support beforeinstallprompt (iOS Safari, etc.)
                showInstallInstructions();
            }
        }

        // Show installation instructions for iOS and other browsers
        function showInstallInstructions() {
            const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent);
            const isSafari = /Safari/.test(navigator.userAgent) && !/Chrome|CriOS|FxiOS/.test(navigator.userAgent);
            const isAndroid = /Android/.test(navigator.userAgent);
            
            let instructions = '';
            
            if (isIOS && isSafari) {
                instructions = 'To install this app on iOS:\n\n' +
                    '1. Tap the Share button (square with arrow pointing up) at the bottom\n' +
                    '2. Scroll down and tap "Add to Home Screen"\n' +
                    '3. Tap "Add" in the top right corner\n\n' +
                    'The app will appear on your home screen!';
            } else if (isAndroid) {
                instructions = 'To install this app on Android:\n\n' +
                    '1. Look for the "Add to Home Screen" or "Install" option in your browser menu\n' +
                    '2. Or check the browser address bar for an install icon\n' +
                    '3. Tap it and follow the prompts\n\n' +
                    'The app will be added to your home screen!';
            } else {
                instructions = 'To install this app:\n\n' +
                    '1. Look for the install icon in your browser address bar\n' +
                    '2. Or check your browser menu for "Install" or "Add to Home Screen" option\n' +
                    '3. Click it and follow the prompts\n\n' +
                    'The app will be added to your device!';
            }
            
            alert(instructions);
        }

        // Check on page load if install button should be shown
        window.addEventListener('load', () => {
            // If deferredPrompt is not set but we're on mobile, show button anyway
            if (!deferredPrompt && !isStandalone && installBtn) {
                const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
                if (isMobile) {
                    installBtn.classList.remove('hidden');
                }
            }
        });
    </script>
</body>
</html>
