<?php
/**
 * Live Tracking - Admin Page
 * Integrates SinoTrack Pro website directly with fallback options
 */

$page_title = 'Live Tracking';
require_once 'includes/header.php';

$pdo = getDBConnection();

// Fetch SinoTrack settings
$stmt = $pdo->query("SELECT key_name, key_value FROM settings WHERE key_name IN ('sinotrack_user', 'sinotrack_pass', 'sinotrack_server', 'gps_tracker_enabled')");
$settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

$user = $settings['sinotrack_user'] ?? '';
$pass = $settings['sinotrack_pass'] ?? '';
$server = !empty($settings['sinotrack_server']) ? rtrim($settings['sinotrack_server'], '/') : "https://www.sinotrackpro.com";

// Ensure server has a protocol
if (!preg_match('/^https?:\/\//', $server)) {
    $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https://' : 'http://';
    $server = $protocol . $server;
}
$gps_enabled = ($settings['gps_tracker_enabled'] ?? '0') === '1';

// Construct auto-login URL if credentials exist
$base_url = $server;
$iframe_url = $base_url;
$has_creds = !empty($user) && !empty($pass);

if ($has_creds) {
    // Try different login formats
    $iframe_url = $server . "/?u=" . urlencode($user) . "&p=" . urlencode($pass);
}

// Check if we should use proxy mode
$use_proxy = isset($_GET['proxy']) && $_GET['proxy'] === '1';
$proxy_url = 'proxy.php?url=' . urlencode($iframe_url);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Live Fleet Tracking</title>
    <style>
        /* Add these styles to handle iframe blocking gracefully */
        .iframe-blocked-message {
            display: none;
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255, 255, 255, 0.98);
            backdrop-filter: blur(10px);
            z-index: 100;
            align-items: center;
            justify-content: center;
            text-align: center;
            padding: 2rem;
        }
        
        .dark .iframe-blocked-message {
            background: rgba(15, 23, 42, 0.98);
        }
        
        .iframe-blocked-message.show {
            display: flex;
        }
        
        .pulse-animation {
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }
        
        .fade-in {
            animation: fadeIn 0.5s ease-in;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
    </style>
</head>
<body class="bg-slate-100 dark:bg-background-dark">
    <div class="flex h-screen overflow-hidden bg-slate-100 dark:bg-background-dark">
        <?php include 'includes/sidebar.php'; ?>

        <div class="flex-1 flex flex-col h-full overflow-hidden">
            <header class="flex-none sticky top-0 z-30 flex items-center bg-white/80 dark:bg-background-dark/80 backdrop-blur-md p-4 justify-between border-b border-slate-200 dark:border-slate-800 lg:px-8">
                <div class="flex items-center gap-4">
                    <button class="text-slate-900 dark:text-white flex size-10 items-center justify-center hover:bg-slate-100 dark:hover:bg-slate-800 rounded-full lg:hidden" onclick="toggleSidebar()">
                        <span class="material-symbols-outlined">menu</span>
                    </button>
                    <h2 class="text-slate-900 dark:text-white text-clamp-lg font-bold">Live Fleet Tracking</h2>
                </div>
                <div class="flex items-center gap-4">
                    <?php if (!empty($user)): ?>
                    <div class="hidden md:flex items-center gap-3 px-4 py-2 bg-slate-100 dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700">
                        <div class="flex flex-col">
                            <span class="text-[10px] font-bold text-slate-500 uppercase leading-none mb-1">Account</span>
                            <span class="text-xs font-mono font-bold text-primary leading-none"><?= htmlspecialchars($user) ?></span>
                        </div>
                        <button data-pass="<?= htmlspecialchars($pass) ?>" onclick="copyToClipboard(this.getAttribute('data-pass'))" class="p-1.5 hover:bg-white dark:hover:bg-slate-700 rounded-lg transition-colors group relative" title="Copy Password">
                            <span class="material-symbols-outlined text-sm text-slate-400 group-hover:text-primary">content_copy</span>
                            <span id="copy-toast" class="absolute -top-8 left-1/2 -translate-x-1/2 bg-slate-900 text-white text-[10px] px-2 py-1 rounded opacity-0 transition-opacity pointer-events-none">Copied!</span>
                        </button>
                    </div>
                    <?php endif; ?>
                    
                    <!-- View Mode Toggle -->
                    <div class="flex items-center bg-slate-100 dark:bg-slate-800 rounded-lg p-1">
                        <button onclick="setViewMode('iframe')" id="mode-iframe" class="px-3 py-1.5 rounded-md text-xs font-bold transition-colors flex items-center gap-1">
                            <span class="material-symbols-outlined text-sm">iframe</span>
                            <span class="hidden sm:inline">Iframe</span>
                        </button>
                        <button onclick="setViewMode('newtab')" id="mode-newtab" class="px-3 py-1.5 rounded-md text-xs font-bold transition-colors flex items-center gap-1">
                            <span class="material-symbols-outlined text-sm">open_in_new</span>
                            <span class="hidden sm:inline">New Tab</span>
                        </button>
                        <button onclick="setViewMode('proxy')" id="mode-proxy" class="px-3 py-1.5 rounded-md text-xs font-bold transition-colors flex items-center gap-1">
                            <span class="material-symbols-outlined text-sm">shield</span>
                            <span class="hidden sm:inline">Proxy</span>
                        </button>
                    </div>
                    
                    <button onclick="reloadCurrentView()" class="p-2 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-lg transition-colors" title="Reload">
                        <span class="material-symbols-outlined text-sm">refresh</span>
                    </button>
                </div>
            </header>

            <main class="flex-1 relative bg-slate-200 dark:bg-slate-900 flex flex-col min-h-0 overflow-hidden">
                <?php if (!$gps_enabled): ?>
                    <div class="absolute inset-0 z-30 flex items-center justify-center bg-white/95 dark:bg-background-dark/95 backdrop-blur-sm p-8 text-center">
                        <div class="max-w-md fade-in">
                            <div class="size-20 bg-rose-100 dark:bg-rose-900/30 text-rose-500 rounded-full flex items-center justify-center mx-auto mb-6">
                                <span class="material-symbols-outlined text-4xl">location_off</span>
                            </div>
                            <h3 class="text-2xl font-bold mb-2">GPS Tracking Disabled</h3>
                            <p class="text-slate-500 dark:text-slate-400 mb-8">Please enable the GPS Tracker in system settings to use the live fleet tracking integration.</p>
                            <a href="settings.php" class="inline-flex items-center gap-2 px-6 py-3 bg-primary text-white rounded-xl font-bold shadow-lg shadow-primary/20 hover:scale-105 transition-transform">
                                <span class="material-symbols-outlined text-lg">settings</span>
                                Go to Settings
                            </a>
                        </div>
                    </div>
                <?php endif; ?>

                <!-- Iframe View -->
                <div id="iframe-view" class="absolute inset-0 w-full h-full <?= $use_proxy ? 'hidden' : '' ?>">
                    <!-- Loading Spinner -->
                    <div id="iframe_loading" class="absolute inset-0 z-20 flex items-center justify-center bg-slate-50 dark:bg-slate-900 transition-opacity duration-300">
                        <div class="text-center p-6">
                            <div class="inline-block size-12 border-4 border-primary/20 border-t-primary rounded-full animate-spin mb-4"></div>
                            <p class="text-sm font-bold text-slate-500">Connecting to SinoTrack Portal...</p>
                            <p class="text-[10px] text-slate-400 mt-2"><?= htmlspecialchars(parse_url($server, PHP_URL_HOST)) ?></p>
                        </div>
                    </div>

                    <!-- Iframe Blocked Message -->
                    <div id="iframe-blocked-message" class="iframe-blocked-message">
                        <div class="max-w-2xl mx-auto fade-in">
                            <div class="size-20 bg-amber-100 dark:bg-amber-900/30 text-amber-500 rounded-full flex items-center justify-center mx-auto mb-6">
                                <span class="material-symbols-outlined text-4xl">warning</span>
                            </div>
                            <h3 class="text-2xl font-bold mb-4">Cannot Load in Iframe</h3>
                            <p class="text-slate-600 dark:text-slate-300 mb-6">
                                SinoTrackPro prevents embedding in iframes for security reasons. 
                                Please use one of these options:
                            </p>
                            
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-8">
                                <a href="<?= htmlspecialchars($iframe_url) ?>" target="_blank" 
                                   class="p-6 bg-primary/10 rounded-xl hover:bg-primary/20 transition-colors group">
                                    <span class="material-symbols-outlined text-3xl text-primary mb-3">open_in_new</span>
                                    <h4 class="font-bold mb-2">Open in New Tab</h4>
                                    <p class="text-sm text-slate-500">Open the tracking portal in a new browser tab</p>
                                    <div class="mt-4 text-primary text-sm font-bold group-hover:underline">
                                        Open Portal →
                                    </div>
                                </a>
                                
                                <button onclick="enableProxyMode()" 
                                        class="p-6 bg-slate-100 dark:bg-slate-800 rounded-xl hover:bg-slate-200 dark:hover:bg-slate-700 transition-colors group text-left">
                                    <span class="material-symbols-outlined text-3xl text-slate-500 mb-3">shield</span>
                                    <h4 class="font-bold mb-2">Use Proxy Mode</h4>
                                    <p class="text-sm text-slate-500">Route through our server to bypass restrictions</p>
                                    <div class="mt-4 text-primary text-sm font-bold group-hover:underline">
                                        Enable Proxy →
                                    </div>
                                </button>
                            </div>
                            
                            <div class="bg-slate-100 dark:bg-slate-800 rounded-xl p-4 text-left">
                                <h5 class="font-bold text-sm mb-2 flex items-center gap-2">
                                    <span class="material-symbols-outlined text-sm">info</span>
                                    Quick Login Info
                                </h5>
                                <div class="grid grid-cols-2 gap-4">
                                    <div>
                                        <p class="text-[10px] text-slate-500 uppercase mb-1">Username</p>
                                        <p class="font-mono text-sm bg-white dark:bg-slate-900 p-2 rounded select-all"><?= htmlspecialchars($user ?: 'Not set') ?></p>
                                    </div>
                                    <div>
                                        <p class="text-[10px] text-slate-500 uppercase mb-1">Password</p>
                                        <button onclick="copyToClipboard('<?= htmlspecialchars($pass) ?>')" 
                                                class="w-full bg-white dark:bg-slate-900 p-2 rounded text-left hover:bg-primary hover:text-white transition-colors">
                                            Click to copy
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- The Iframe -->
                    <iframe 
                        src="<?= $use_proxy ? $proxy_url : htmlspecialchars($iframe_url) ?>" 
                        class="w-full h-full border-0 bg-white"
                        allow="geolocation"
                        id="sinotrack_frame"
                        onload="handleIframeLoad()"
                        style="min-height: 500px;"
                        sandbox="allow-same-origin allow-scripts allow-popups allow-forms allow-downloads"
                    ></iframe>
                </div>

                <!-- New Tab View (Auto-open) -->
                <div id="newtab-view" class="absolute inset-0 w-full h-full hidden items-center justify-center bg-slate-50 dark:bg-slate-900">
                    <div class="text-center max-w-md p-8 fade-in">
                        <div class="size-20 bg-green-100 dark:bg-green-900/30 text-green-500 rounded-full flex items-center justify-center mx-auto mb-6 pulse-animation">
                            <span class="material-symbols-outlined text-4xl">open_in_new</span>
                        </div>
                        <h3 class="text-2xl font-bold mb-3">Opening in New Tab</h3>
                        <p class="text-slate-500 dark:text-slate-400 mb-6">
                            SinoTrackPro is opening in a new browser tab for the best experience.
                        </p>
                        <div class="space-y-3">
                            <a href="<?= htmlspecialchars($iframe_url) ?>" target="_blank" 
                               class="inline-flex items-center gap-2 px-6 py-3 bg-primary text-white rounded-xl font-bold shadow-lg shadow-primary/20 hover:scale-105 transition-transform w-full justify-center">
                                <span class="material-symbols-outlined">open_in_new</span>
                                Open Tracking Portal
                            </a>
                            <button onclick="setViewMode('iframe')" 
                                    class="inline-flex items-center gap-2 px-6 py-3 bg-slate-200 dark:bg-slate-800 rounded-xl font-bold hover:bg-slate-300 dark:hover:bg-slate-700 transition-colors w-full justify-center">
                                <span class="material-symbols-outlined">arrow_back</span>
                                Back to Iframe View
                            </button>
                        </div>
                        
                        <?php if ($has_creds): ?>
                        <div class="mt-6 pt-6 border-t border-slate-200 dark:border-slate-700">
                            <p class="text-xs text-slate-400 mb-2">Manual login if needed:</p>
                            <div class="bg-slate-100 dark:bg-slate-800 rounded-lg p-3 text-left">
                                <div class="text-xs mb-2"><span class="font-bold">User:</span> <?= htmlspecialchars($user) ?></div>
                                <div class="text-xs"><span class="font-bold">Pass:</span> •••••••• <button onclick="copyToClipboard('<?= htmlspecialchars($pass) ?>')" class="text-primary hover:underline ml-2">Copy</button></div>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Proxy View (if enabled) -->
                <?php if ($use_proxy): ?>
                <div id="proxy-view" class="absolute inset-0 w-full h-full">
                    <iframe 
                        src="<?= $proxy_url ?>" 
                        class="w-full h-full border-0 bg-white"
                        allow="geolocation"
                        id="proxy_frame"
                        style="min-height: 500px;"
                    ></iframe>
                </div>
                <?php endif; ?>

                <!-- Credential Overlay for Mobile -->
                <div id="credOverlay" class="absolute bottom-6 right-6 z-10 md:hidden">
                    <button onclick="toggleCreds()" class="size-12 bg-primary text-white rounded-full shadow-2xl flex items-center justify-center hover:scale-110 transition-transform">
                        <span class="material-symbols-outlined">key</span>
                    </button>
                    <div id="credPanel" class="hidden absolute bottom-16 right-0 w-64 bg-white dark:bg-surface-dark rounded-2xl shadow-2xl border border-slate-200 dark:border-slate-800 p-4">
                        <h4 class="font-bold text-sm mb-3">Manual Login Info</h4>
                        <div class="space-y-3">
                            <div>
                                <p class="text-[10px] text-slate-500 uppercase font-bold mb-1">Username</p>
                                <p class="text-xs font-mono font-bold bg-slate-50 dark:bg-slate-900 p-2 rounded border dark:border-slate-700 select-all"><?= htmlspecialchars($user ?: 'Not set') ?></p>
                            </div>
                            <div>
                                <p class="text-[10px] text-slate-500 uppercase font-bold mb-1">Password</p>
                                <button data-pass="<?= htmlspecialchars($pass) ?>" onclick="copyToClipboard(this.getAttribute('data-pass'))" class="w-full py-2 bg-slate-100 dark:bg-slate-800 rounded-lg text-xs font-bold hover:bg-primary hover:text-white transition-colors flex items-center justify-center gap-2">
                                    <span class="material-symbols-outlined text-xs">content_copy</span>
                                    Copy Password
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script>
        // Configuration
        const AUTO_LOGIN_URL = '<?= addslashes($iframe_url) ?>';
        const PLAIN_URL = '<?= addslashes($base_url) ?>';
        const PROXY_URL = 'proxy.php?url=' + encodeURIComponent(AUTO_LOGIN_URL);
        
        // Current view mode
        let currentView = '<?= $use_proxy ? "proxy" : "iframe" ?>';
        
        // Initialize
        document.addEventListener('DOMContentLoaded', function() {
            updateViewModeButtons();
            
            // Check if iframe is blocked after 5 seconds
            setTimeout(checkIframeBlocked, 5000);
            
            // Auto-open in new tab if on mobile
            if (window.innerWidth < 768) {
                // For mobile, show new tab option prominently
                console.log('Mobile device detected');
            }
        });
        
        function checkIframeBlocked() {
            const iframe = document.getElementById('sinotrack_frame');
            if (!iframe) return;
            
            try {
                // Try to access iframe content - this will throw error if cross-origin
                const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
                
                // If we can access it, check if it's actually loaded
                if (iframeDoc && iframeDoc.body) {
                    const bodyText = iframeDoc.body.innerText || '';
                    const bodyHtml = iframeDoc.body.innerHTML || '';
                    
                    // Check for common error messages
                    if (bodyText.includes('refuse to connect') || 
                        bodyText.includes('cannot be reached') ||
                        bodyText.includes('404') ||
                        bodyHtml.includes('X-Frame-Options') ||
                        bodyHtml.includes('clickjacking')) {
                        showIframeBlockedMessage();
                    } else {
                        // Successfully loaded
                        hideLoading();
                    }
                }
            } catch (e) {
                // Cross-origin error - this is expected, but if the iframe failed to load,
                // we might still need to show the message
                console.log('Iframe is cross-origin, cannot check content');
                
                // Check if iframe actually loaded by verifying it's not showing error page
                setTimeout(() => {
                    // If loading spinner is still visible after 8 seconds, assume iframe failed
                    const loader = document.getElementById('iframe_loading');
                    if (loader && loader.style.display !== 'none') {
                        showIframeBlockedMessage();
                    }
                }, 3000);
            }
        }
        
        function showIframeBlockedMessage() {
            document.getElementById('iframe-blocked-message').classList.add('show');
            hideLoading();
        }
        
        function hideIframeBlockedMessage() {
            document.getElementById('iframe-blocked-message').classList.remove('show');
        }
        
        function copyToClipboard(text) {
            if (!text) {
                alert('No password to copy');
                return;
            }
            
            navigator.clipboard.writeText(text).then(() => {
                // Show toast
                const toast = document.getElementById('copy-toast');
                if (toast) {
                    toast.classList.remove('opacity-0');
                    setTimeout(() => toast.classList.add('opacity-0'), 2000);
                } else {
                    // Fallback alert
                    alert('Password copied to clipboard!');
                }
            }).catch(err => {
                console.error('Copy failed:', err);
                alert('Failed to copy password');
            });
        }
        
        function toggleCreds() {
            const panel = document.getElementById('credPanel');
            panel.classList.toggle('hidden');
        }
        
        function hideLoading() {
            const loader = document.getElementById('iframe_loading');
            if (loader) {
                loader.classList.add('opacity-0');
                setTimeout(() => {
                    loader.style.display = 'none';
                }, 300);
            }
        }
        
        function showLoading() {
            const loader = document.getElementById('iframe_loading');
            if (loader) {
                loader.style.display = 'flex';
                setTimeout(() => {
                    loader.classList.remove('opacity-0');
                }, 10);
            }
        }
        
        function handleIframeLoad() {
            hideLoading();
            // Check if iframe loaded successfully
            setTimeout(checkIframeBlocked, 1000);
        }
        
        function reloadIframe() {
            showLoading();
            hideIframeBlockedMessage();
            const frame = document.getElementById('sinotrack_frame');
            if (frame) {
                frame.src = AUTO_LOGIN_URL;
            }
        }
        
        function reloadPlain() {
            showLoading();
            hideIframeBlockedMessage();
            const frame = document.getElementById('sinotrack_frame');
            if (frame) {
                frame.src = PLAIN_URL;
            }
        }
        
        function reloadCurrentView() {
            if (currentView === 'iframe') {
                reloadIframe();
            } else if (currentView === 'newtab') {
                window.open(AUTO_LOGIN_URL, '_blank');
            } else if (currentView === 'proxy') {
                window.location.href = '?proxy=1';
            }
        }
        
        function setViewMode(mode) {
            currentView = mode;
            
            // Hide all views
            document.getElementById('iframe-view').classList.add('hidden');
            document.getElementById('newtab-view').classList.add('hidden');
            
            // Show selected view
            if (mode === 'iframe') {
                document.getElementById('iframe-view').classList.remove('hidden');
                reloadIframe();
            } else if (mode === 'newtab') {
                document.getElementById('newtab-view').classList.remove('hidden');
                // Auto-open in new tab
                window.open(AUTO_LOGIN_URL, '_blank');
            } else if (mode === 'proxy') {
                window.location.href = '?proxy=1';
            }
            
            updateViewModeButtons();
        }
        
        function updateViewModeButtons() {
            // Reset all buttons
            document.getElementById('mode-iframe').classList.remove('bg-white', 'dark:bg-slate-700', 'shadow-sm');
            document.getElementById('mode-newtab').classList.remove('bg-white', 'dark:bg-slate-700', 'shadow-sm');
            document.getElementById('mode-proxy').classList.remove('bg-white', 'dark:bg-slate-700', 'shadow-sm');
            
            // Highlight current mode
            if (currentView === 'iframe') {
                document.getElementById('mode-iframe').classList.add('bg-white', 'dark:bg-slate-700', 'shadow-sm');
            } else if (currentView === 'newtab') {
                document.getElementById('mode-newtab').classList.add('bg-white', 'dark:bg-slate-700', 'shadow-sm');
            } else if (currentView === 'proxy') {
                document.getElementById('mode-proxy').classList.add('bg-white', 'dark:bg-slate-700', 'shadow-sm');
            }
        }
        
        function enableProxyMode() {
            window.location.href = '?proxy=1';
        }
        
        // Safety timeout: Hide loader after 10 seconds max
        setTimeout(() => {
            hideLoading();
            // Show blocked message if still loading
            const loader = document.getElementById('iframe_loading');
            if (loader && loader.style.display !== 'none') {
                showIframeBlockedMessage();
            }
        }, 10000);
    </script>

    <?php include 'includes/footer.php'; ?>
</body>
</html>