<?php
session_start();
include('includes/config.php'); // Database connection

// Set lock screen flag
$_SESSION['locked'] = true;

// Get real data from database
$today = date('Y-m-d');

// Get active users count
$active_users_sql = "SELECT COUNT(*) as total FROM users WHERE status = 'verified'";
$active_users_result = mysqli_query($conn, $active_users_sql);
$active_users_row = mysqli_fetch_assoc($active_users_result);
$active_users = $active_users_row['total'];

// Get trades today (transactions count)
$trades_sql = "SELECT COUNT(*) as total FROM transactions WHERE DATE(date) = '$today' AND type IN ('profit', 'loss')";
$trades_result = mysqli_query($conn, $trades_sql);
$trades_row = mysqli_fetch_assoc($trades_result);
$trades_today = $trades_row['total'];

// Get 24h volume
$volume_sql = "SELECT COALESCE(SUM(amount), 0) as total FROM transactions 
               WHERE DATE(date) = '$today' AND status = 'completed' 
               AND type IN ('deposit', 'withdrawal', 'profit')";
$volume_result = mysqli_query($conn, $volume_sql);
$volume_row = mysqli_fetch_assoc($volume_result);
$volume_24h = $volume_row['total'];

// Get open tickets
$tickets_sql = "SELECT COUNT(*) as total FROM support_tickets WHERE status IN ('open', 'in_progress')";
$tickets_result = mysqli_query($conn, $tickets_sql);
$tickets_row = mysqli_fetch_assoc($tickets_result);
$open_tickets = $tickets_row['total'];

// Get profit today
$profit_sql = "SELECT COALESCE(SUM(amount), 0) as total FROM transactions 
               WHERE type = 'profit' AND status = 'completed' AND DATE(date) = '$today'";
$profit_result = mysqli_query($conn, $profit_sql);
$profit_row = mysqli_fetch_assoc($profit_result);
$profit_today = $profit_row['total'];

// Get system load (active subscriptions percentage)
$total_users_sql = "SELECT COUNT(*) as total FROM users";
$total_users_result = mysqli_query($conn, $total_users_sql);
$total_users_row = mysqli_fetch_assoc($total_users_result);
$total_users = $total_users_row['total'] ?: 1; // Avoid division by zero

$active_subs_sql = "SELECT COUNT(*) as total FROM user_bot_subscriptions WHERE status = 'active'";
$active_subs_result = mysqli_query($conn, $active_subs_sql);
$active_subs_row = mysqli_fetch_assoc($active_subs_result);
$active_subs = $active_subs_row['total'];

// Calculate system load percentage (active subscriptions vs total users)
$system_load = $total_users > 0 ? round(($active_subs / $total_users) * 100) : 0;
$system_load = min($system_load, 100); // Cap at 100%

// Get admin password for verification
$admin_sql = "SELECT password FROM admins WHERE id = " . ($_SESSION['admin_id'] ?: 1);
$admin_result = mysqli_query($conn, $admin_sql);
$admin_row = mysqli_fetch_assoc($admin_result);
$admin_password_hash = $admin_row['password'] ?: '0192023a7bbd73250516f069df18b500'; // Default admin123

// Format numbers
$volume_formatted = '$' . number_format($volume_24h, 2);
$profit_formatted = '$' . number_format($profit_today, 2);
?>

<!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.0, maximum-scale=1.0, user-scalable=no">
    <title>AI Trading - Admin Lock Screen</title>
    
    <!-- CSS -->
    <link rel="stylesheet" href="css/vendors_css.css">
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="css/skin_color.css">
    <link rel="stylesheet" href="css/dashboard.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    
    <!-- 3D Effects Library -->
    <script src="https://cdn.jsdelivr.net/npm/three@0.132.2/build/three.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/three@0.132.2/examples/js/controls/OrbitControls.js"></script>
    
    <!-- Chart.js for speedometers -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <style>
    * {
        -webkit-tap-highlight-color: transparent;
    }
    
    body {
        margin: 0;
        padding: 0;
        overflow: hidden;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        background: linear-gradient(-45deg, #0f0c29, #302b63, #24243e, #000428);
        background-size: 400% 400%;
        animation: gradientBG 15s ease infinite;
        height: 100vh;
        width: 100vw;
        position: fixed;
        touch-action: manipulation;
    }
    
    @keyframes gradientBG {
        0% { background-position: 0% 50%; }
        50% { background-position: 100% 50%; }
        100% { background-position: 0% 50%; }
    }
    
    #bg3d {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: -2;
        opacity: 0.3;
    }
    
    .gradient-overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: radial-gradient(circle at 20% 50%, rgba(102, 126, 234, 0.15) 0%, transparent 50%),
                    radial-gradient(circle at 80% 20%, rgba(67, 233, 123, 0.1) 0%, transparent 50%),
                    radial-gradient(circle at 40% 80%, rgba(255, 107, 107, 0.1) 0%, transparent 50%);
        z-index: -1;
        animation: pulseOverlay 10s ease-in-out infinite alternate;
    }
    
    @keyframes pulseOverlay {
        0% { opacity: 0.7; }
        100% { opacity: 1; }
    }
    
    .lock-container {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 1000;
        padding: 20px;
        overflow-y: auto;
        -webkit-overflow-scrolling: touch;
    }
    
    .lock-box {
        background: rgba(255, 255, 255, 0.1);
        backdrop-filter: blur(20px);
        -webkit-backdrop-filter: blur(20px);
        border-radius: 25px;
        padding: 30px;
        width: 100%;
        max-width: 400px;
        text-align: center;
        border: 1px solid rgba(255, 255, 255, 0.2);
        box-shadow: 0 25px 45px rgba(0, 0, 0, 0.5);
        animation: float 6s ease-in-out infinite;
        position: relative;
        z-index: 1002;
        margin: auto;
    }
    
    @keyframes float {
        0%, 100% { transform: translateY(0px); }
        50% { transform: translateY(-10px); }
    }
    
    .avatar {
        width: 100px;
        height: 100px;
        margin: 0 auto 20px;
        border-radius: 50%;
        background: linear-gradient(45deg, #667eea, #764ba2);
        display: flex;
        align-items: center;
        justify-content: center;
        border: 5px solid rgba(255, 255, 255, 0.3);
        animation: pulse 2s infinite;
    }
    
    @keyframes pulse {
        0%, 100% { box-shadow: 0 0 0 0 rgba(102, 126, 234, 0.7); }
        70% { box-shadow: 0 0 0 15px rgba(102, 126, 234, 0); }
    }
    
    .avatar i {
        font-size: 40px;
        color: white;
    }
    
    h1 {
        color: white;
        margin-bottom: 5px;
        font-weight: 600;
        font-size: 22px;
        line-height: 1.3;
    }
    
    .subtitle {
        color: rgba(255, 255, 255, 0.7);
        margin-bottom: 25px;
        font-size: 13px;
        line-height: 1.4;
    }
    
    .password-input {
        position: relative;
        margin-bottom: 20px;
    }
    
    .password-input input {
        width: 100%;
        padding: 15px 20px;
        background: rgba(255, 255, 255, 0.1);
        border: 2px solid rgba(255, 255, 255, 0.2);
        border-radius: 15px;
        color: white;
        font-size: 16px;
        transition: all 0.3s;
        box-sizing: border-box;
        -webkit-appearance: none;
        appearance: none;
    }
    
    .password-input input:focus {
        outline: none;
        border-color: #667eea;
        background: rgba(255, 255, 255, 0.15);
        box-shadow: 0 0 15px rgba(102, 126, 234, 0.3);
    }
    
    .password-input i {
        position: absolute;
        right: 20px;
        top: 50%;
        transform: translateY(-50%);
        color: rgba(255, 255, 255, 0.5);
        pointer-events: none;
    }
    
    .btn-unlock {
        width: 100%;
        padding: 15px;
        background: linear-gradient(45deg, #667eea, #764ba2);
        border: none;
        border-radius: 15px;
        color: white;
        font-size: 16px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s;
        position: relative;
        overflow: hidden;
        box-sizing: border-box;
    }
    
    .btn-unlock:hover {
        transform: translateY(-2px);
        box-shadow: 0 10px 20px rgba(102, 126, 234, 0.4);
    }
    
    .btn-unlock:disabled {
        opacity: 0.5;
        cursor: not-allowed;
        transform: none;
    }
    
    .btn-unlock:active {
        transform: scale(0.98);
    }
    
    .error-message {
        color: #ff6b6b;
        margin-top: 15px;
        font-size: 13px;
        display: none;
        line-height: 1.4;
    }
    
    .time-display {
        position: fixed;
        top: 20px;
        left: 20px;
        color: white;
        font-size: 13px;
        z-index: 1001;
        text-align: left;
        background: rgba(0, 0, 0, 0.3);
        padding: 10px 15px;
        border-radius: 10px;
        backdrop-filter: blur(10px);
        -webkit-backdrop-filter: blur(10px);
        border: 1px solid rgba(255, 255, 255, 0.1);
        max-width: calc(100% - 40px);
    }
    
    .stats-grid {
        position: fixed;
        bottom: 20px;
        left: 20px;
        right: 20px;
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 15px;
        z-index: 1001;
    }
    
    .stat-card {
        background: rgba(255, 255, 255, 0.1);
        backdrop-filter: blur(10px);
        -webkit-backdrop-filter: blur(10px);
        border-radius: 15px;
        padding: 15px;
        color: white;
        border: 1px solid rgba(255, 255, 255, 0.1);
        transition: all 0.3s;
        text-align: center;
        min-height: 80px;
        display: flex;
        flex-direction: column;
        justify-content: center;
    }
    
    .stat-card:hover {
        transform: translateY(-5px);
        background: rgba(255, 255, 255, 0.15);
    }
    
    .stat-value {
        font-size: 22px;
        font-weight: 700;
        margin-bottom: 3px;
        background: linear-gradient(45deg, #fff, #a8edea);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        line-height: 1.2;
    }
    
    .stat-label {
        font-size: 11px;
        color: rgba(255, 255, 255, 0.7);
        text-transform: uppercase;
        letter-spacing: 0.5px;
        line-height: 1.3;
    }
    
    .speedometer-grid {
        position: fixed;
        top: 20px;
        right: 20px;
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 15px;
        z-index: 1001;
        max-width: calc(100% - 40px);
    }
    
    .speedometer-card {
        background: rgba(255, 255, 255, 0.1);
        backdrop-filter: blur(10px);
        -webkit-backdrop-filter: blur(10px);
        border-radius: 15px;
        padding: 15px;
        width: 130px;
        height: 130px;
        position: relative;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }
    
    .gauge-title {
        position: absolute;
        top: 10px;
        left: 0;
        right: 0;
        text-align: center;
        color: white;
        font-size: 10px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        z-index: 2;
        line-height: 1.3;
        padding: 0 5px;
    }
    
    .gauge-value {
        position: absolute;
        bottom: 15px;
        left: 0;
        right: 0;
        text-align: center;
        color: white;
        font-size: 16px;
        font-weight: 700;
        z-index: 2;
        line-height: 1.2;
    }
    
    .gauge-container {
        position: relative;
        width: 100px;
        height: 100px;
        margin-top: 5px;
    }
    
    .particles {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        pointer-events: none;
        z-index: 0;
    }
    
    .neon-text {
        text-shadow: 0 0 10px #667eea, 0 0 20px #667eea, 0 0 30px #667eea;
        animation: neon 1.5s ease-in-out infinite alternate;
    }
    
    @keyframes neon {
        from { text-shadow: 0 0 10px #667eea, 0 0 20px #667eea, 0 0 30px #667eea; }
        to { text-shadow: 0 0 20px #667eea, 0 0 30px #667eea, 0 0 40px #667eea; }
    }
    
    .glitch {
        animation: glitch 1s linear infinite;
    }
    
    @keyframes glitch {
        2%, 64% { transform: translate(1px,0) skew(0deg); }
        4%, 60% { transform: translate(-1px,0) skew(0deg); }
        62% { transform: translate(0,0) skew(2deg); }
    }
    
    /* Mobile-first responsive design */
    @media (max-width: 767px) {
        body {
            background-size: 600% 600%;
            animation: gradientBG 20s ease infinite;
        }
        
        .lock-container {
            padding: 15px;
            align-items: flex-start;
            padding-top: 120px;
        }
        
        .lock-box {
            padding: 25px 20px;
            max-width: 90%;
            margin-top: 0;
            animation: floatMobile 6s ease-in-out infinite;
        }
        
        @keyframes floatMobile {
            0%, 100% { transform: translateY(0px) scale(1); }
            50% { transform: translateY(-5px) scale(1.01); }
        }
        
        .avatar {
            width: 80px;
            height: 80px;
            margin-bottom: 15px;
        }
        
        .avatar i {
            font-size: 30px;
        }
        
        h1 {
            font-size: 18px;
            margin-bottom: 3px;
        }
        
        .subtitle {
            font-size: 12px;
            margin-bottom: 20px;
        }
        
        .password-input input {
            padding: 12px 15px;
            font-size: 15px;
        }
        
        .btn-unlock {
            padding: 12px;
            font-size: 15px;
        }
        
        .time-display {
            top: 15px;
            left: 15px;
            font-size: 11px;
            padding: 8px 12px;
            max-width: 180px;
        }
        
        #currentTime {
            font-size: 14px;
        }
        
        .speedometer-grid {
            top: 15px;
            right: 15px;
            gap: 10px;
            grid-template-columns: 1fr;
            max-width: 130px;
        }
        
        .speedometer-card {
            width: 120px;
            height: 120px;
            padding: 12px;
        }
        
        .gauge-container {
            width: 90px;
            height: 90px;
        }
        
        .gauge-title {
            font-size: 9px;
            top: 8px;
        }
        
        .gauge-value {
            font-size: 14px;
            bottom: 12px;
        }
        
        .stats-grid {
            bottom: 15px;
            left: 15px;
            right: 15px;
            gap: 10px;
            grid-template-columns: repeat(2, 1fr);
        }
        
        .stat-card {
            padding: 12px 10px;
            min-height: 70px;
        }
        
        .stat-value {
            font-size: 18px;
        }
        
        .stat-label {
            font-size: 10px;
        }
    }
    
    @media (max-width: 480px) {
        .lock-box {
            max-width: 95%;
            padding: 20px 15px;
        }
        
        .speedometer-grid {
            max-width: 120px;
        }
        
        .speedometer-card {
            width: 110px;
            height: 110px;
        }
        
        .gauge-container {
            width: 80px;
            height: 80px;
        }
        
        .stats-grid {
            grid-template-columns: repeat(2, 1fr);
        }
        
        .time-display {
            max-width: 150px;
        }
    }
    
    @media (max-width: 360px) {
        .speedometer-grid {
            display: none; /* Hide gauges on very small screens */
        }
        
        .time-display {
            right: 15px;
            left: auto;
            max-width: 140px;
        }
        
        .lock-container {
            padding-top: 100px;
        }
    }
    
    /* Landscape mode */
    @media (max-height: 600px) and (orientation: landscape) {
        .lock-container {
            padding-top: 80px;
            padding-bottom: 80px;
            align-items: flex-start;
        }
        
        .lock-box {
            max-width: 400px;
            margin: 0 auto;
        }
        
        .stats-grid {
            position: absolute;
            bottom: 10px;
        }
        
        .speedometer-grid {
            top: 10px;
        }
        
        .time-display {
            top: 10px;
        }
    }
    
    /* Prevent zoom on input focus on iOS */
    @media screen and (max-width: 767px) {
        input, textarea {
            font-size: 16px !important;
        }
    }
    
    /* Smooth scrolling for mobile */
    html {
        -webkit-overflow-scrolling: touch;
    }
    
    /* Remove blue highlight on tap for mobile */
    *:focus {
        outline: none;
    }
    
    /* Custom scrollbar for lock container */
    .lock-container::-webkit-scrollbar {
        width: 5px;
    }
    
    .lock-container::-webkit-scrollbar-track {
        background: rgba(255, 255, 255, 0.1);
        border-radius: 10px;
    }
    
    .lock-container::-webkit-scrollbar-thumb {
        background: rgba(102, 126, 234, 0.5);
        border-radius: 10px;
    }
    
    /* Loading animation for button */
    @keyframes buttonLoading {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
    
    .btn-loading::before {
        content: '';
        position: absolute;
        top: 50%;
        left: 50%;
        width: 20px;
        height: 20px;
        margin: -10px 0 0 -10px;
        border: 2px solid rgba(255, 255, 255, 0.3);
        border-top: 2px solid white;
        border-radius: 50%;
        animation: buttonLoading 1s linear infinite;
    }
    
    /* Touch feedback for mobile */
    .btn-unlock:active, .stat-card:active {
        opacity: 0.8;
    }
    
    /* Hide 3D on mobile for performance */
    @media (max-width: 768px) {
        #bg3d {
            display: none;
        }
        
        .gradient-overlay {
            opacity: 0.8;
        }
    }
    </style>
</head>
<body>
    <!-- 3D Background (hidden on mobile) -->
    <div id="bg3d"></div>
    
    <!-- Animated Gradient Overlay -->
    <div class="gradient-overlay"></div>
    
    <!-- Floating Particles -->
    <div class="particles" id="particles"></div>
    
    <!-- Time Display -->
    <div class="time-display">
        <div id="currentTime" class="neon-text" style="font-size: 16px; font-weight: 600; margin-bottom: 3px;"></div>
        <div id="currentDate" style="font-size: 11px; color: rgba(255,255,255,0.7);"></div>
    </div>
    
    <!-- Speedometer Grid -->
    <div class="speedometer-grid">
        <div class="speedometer-card">
            <div class="gauge-title">System Load</div>
            <div class="gauge-container">
                <canvas id="gauge1"></canvas>
            </div>
            <div class="gauge-value" id="gauge1Value"><?php echo $system_load; ?>%</div>
        </div>
        <div class="speedometer-card">
            <div class="gauge-title">Profit Today</div>
            <div class="gauge-container">
                <canvas id="gauge2"></canvas>
            </div>
            <div class="gauge-value" id="gauge2Value"><?php echo $profit_formatted; ?></div>
        </div>
    </div>
    
    <!-- Live Stats Grid -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-value" id="stat1"><?php echo $active_users; ?></div>
            <div class="stat-label">Active Users</div>
        </div>
        <div class="stat-card">
            <div class="stat-value" id="stat2"><?php echo $trades_today; ?></div>
            <div class="stat-label">Trades Today</div>
        </div>
        <div class="stat-card">
            <div class="stat-value" id="stat3"><?php echo $volume_formatted; ?></div>
            <div class="stat-label">24h Volume</div>
        </div>
        <div class="stat-card">
            <div class="stat-value" id="stat4"><?php echo $open_tickets; ?></div>
            <div class="stat-label">Open Tickets</div>
        </div>
    </div>
    
    <!-- Lock Screen Overlay -->
    <div class="lock-container">
        <div class="lock-box">
            <div class="avatar">
                <i class="fas fa-user-shield"></i>
            </div>
            <h1 class="neon-text">AI Trading Admin</h1>
            <div class="subtitle">Session Locked - Enter password to continue</div>
            
            <form id="unlockForm" method="POST">
                <div class="password-input">
                    <input type="password" id="password" name="password" placeholder="Enter Admin Password" autocomplete="off" autofocus inputmode="text">
                    <i class="fas fa-lock"></i>
                </div>
                
                <button type="submit" class="btn-unlock" id="unlockBtn">
                    <i class="fas fa-unlock me-2"></i> Unlock Dashboard
                </button>
                
                <div class="error-message" id="errorMsg">
                    <i class="fas fa-exclamation-circle me-1"></i> Incorrect password. Try again.
                </div>
            </form>
        </div>
    </div>

    <!-- JavaScript -->
    <script>
    // Store initial data from PHP
    const initialData = {
        systemLoad: <?php echo $system_load; ?>,
        profitToday: <?php echo $profit_today; ?>,
        activeUsers: <?php echo $active_users; ?>,
        tradesToday: <?php echo $trades_today; ?>,
        volume24h: <?php echo $volume_24h; ?>,
        openTickets: <?php echo $open_tickets; ?>
    };
    
    // Mobile detection
    const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
    const isSmallScreen = window.innerWidth < 768;
    
    // Initialize 3D Scene (only on desktop)
    let scene, camera, renderer, controls;
    let particlesGeometry, particlesMaterial, particles;
    
    function init3D() {
        if (isSmallScreen) {
            // Don't initialize 3D on mobile for performance
            return;
        }
        
        try {
            // Scene
            scene = new THREE.Scene();
            
            // Camera
            camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
            camera.position.z = 50;
            
            // Renderer
            renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true });
            renderer.setSize(window.innerWidth, window.innerHeight);
            renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); // Limit pixel ratio for performance
            document.getElementById('bg3d').appendChild(renderer.domElement);
            
            // Controls
            controls = new THREE.OrbitControls(camera, renderer.domElement);
            controls.enableDamping = true;
            controls.dampingFactor = 0.05;
            controls.rotateSpeed = 0.3;
            
            // Particles (reduced count for performance)
            const particlesCount = isMobile ? 500 : 1000;
            particlesGeometry = new THREE.BufferGeometry();
            const positions = new Float32Array(particlesCount * 3);
            const colors = new Float32Array(particlesCount * 3);
            
            for(let i = 0; i < particlesCount * 3; i += 3) {
                positions[i] = (Math.random() - 0.5) * 150;
                positions[i + 1] = (Math.random() - 0.5) * 150;
                positions[i + 2] = (Math.random() - 0.5) * 150;
                
                // Create gradient colors
                colors[i] = 0.4 + Math.random() * 0.6; // R
                colors[i + 1] = 0.3 + Math.random() * 0.4; // G
                colors[i + 2] = 0.6 + Math.random() * 0.4; // B
            }
            
            particlesGeometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
            particlesGeometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
            
            particlesMaterial = new THREE.PointsMaterial({
                size: 0.8,
                vertexColors: true,
                transparent: true,
                opacity: 0.6,
                sizeAttenuation: true
            });
            
            particles = new THREE.Points(particlesGeometry, particlesMaterial);
            scene.add(particles);
            
            // Lights
            const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
            scene.add(ambientLight);
            
            const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
            directionalLight.position.set(1, 1, 1);
            scene.add(directionalLight);
            
            // Animate
            function animate() {
                requestAnimationFrame(animate);
                
                particles.rotation.x += 0.001;
                particles.rotation.y += 0.0015;
                particles.rotation.z += 0.0003;
                
                controls.update();
                renderer.render(scene, camera);
            }
            
            animate();
            
            // Handle resize
            window.addEventListener('resize', onWindowResize);
        } catch (error) {
            console.log('3D initialization failed, using fallback background');
            document.getElementById('bg3d').style.display = 'none';
        }
    }
    
    function onWindowResize() {
        if (!isSmallScreen && camera && renderer) {
            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();
            renderer.setSize(window.innerWidth, window.innerHeight);
        }
    }
    
    // Initialize Speedometers
    let gauge1, gauge2;
    
    function initSpeedometers() {
        try {
            // Gauge 1: System Load
            const ctx1 = document.getElementById('gauge1');
            if (!ctx1) return;
            
            const canvas1 = ctx1.getContext('2d');
            const loadValue = initialData.systemLoad;
            
            gauge1 = new Chart(canvas1, {
                type: 'doughnut',
                data: {
                    datasets: [{
                        data: [loadValue, 100 - loadValue],
                        backgroundColor: [
                            loadValue > 80 ? '#ff6b6b' : 
                            loadValue > 60 ? '#ffa726' : '#43e97b',
                            'rgba(255, 255, 255, 0.1)'
                        ],
                        borderWidth: 0,
                        circumference: 270,
                        rotation: 225,
                        borderRadius: 5
                    }]
                },
                options: {
                    cutout: '75%',
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { display: false },
                        tooltip: { enabled: false }
                    },
                    animation: {
                        animateRotate: true,
                        animateScale: true,
                        duration: 1500,
                        easing: 'easeOutQuart'
                    },
                    layout: {
                        padding: 5
                    }
                }
            });
            
            // Gauge 2: Profit Today
            const ctx2 = document.getElementById('gauge2');
            if (!ctx2) return;
            
            const canvas2 = ctx2.getContext('2d');
            const profitValue = initialData.profitToday;
            const maxProfit = Math.max(profitValue * 2, 1000);
            const profitPercentage = Math.min((profitValue / maxProfit) * 100, 100);
            
            gauge2 = new Chart(canvas2, {
                type: 'doughnut',
                data: {
                    datasets: [{
                        data: [profitPercentage, 100 - profitPercentage],
                        backgroundColor: [
                            profitValue > 0 ? '#43e97b' : '#ff6b6b',
                            'rgba(255, 255, 255, 0.1)'
                        ],
                        borderWidth: 0,
                        circumference: 270,
                        rotation: 225,
                        borderRadius: 5
                    }]
                },
                options: {
                    cutout: '75%',
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { display: false },
                        tooltip: { enabled: false }
                    },
                    animation: {
                        animateRotate: true,
                        animateScale: true,
                        duration: 1500,
                        easing: 'easeOutQuart'
                    },
                    layout: {
                        padding: 5
                    }
                }
            });
        } catch (error) {
            console.log('Chart.js initialization failed');
        }
    }
    
    // Create floating particles (simplified for mobile)
    function createFloatingParticles() {
        const particlesContainer = document.getElementById('particles');
        if (!particlesContainer) return;
        
        const particleCount = isMobile ? 20 : 30;
        
        for (let i = 0; i < particleCount; i++) {
            const particle = document.createElement('div');
            const size = Math.random() * 4 + 1;
            
            particle.style.position = 'absolute';
            particle.style.width = size + 'px';
            particle.style.height = size + 'px';
            particle.style.background = `rgba(${Math.random() * 100 + 155}, ${Math.random() * 100 + 155}, 234, ${Math.random() * 0.3 + 0.2})`;
            particle.style.borderRadius = '50%';
            particle.style.left = Math.random() * 100 + '%';
            particle.style.top = Math.random() * 100 + '%';
            particle.style.boxShadow = '0 0 8px rgba(102, 126, 234, 0.6)';
            particle.style.zIndex = '0';
            
            particlesContainer.appendChild(particle);
            
            // Animate particle
            animateParticle(particle);
        }
    }
    
    function animateParticle(particle) {
        let x = parseFloat(particle.style.left);
        let y = parseFloat(particle.style.top);
        let xSpeed = (Math.random() - 0.5) * 0.3;
        let ySpeed = (Math.random() - 0.5) * 0.3;
        
        function move() {
            x += xSpeed;
            y += ySpeed;
            
            // Bounce off edges
            if (x < 0 || x > 100) xSpeed *= -1;
            if (y < 0 || y > 100) ySpeed *= -1;
            
            particle.style.left = x + '%';
            particle.style.top = y + '%';
            
            requestAnimationFrame(move);
        }
        
        move();
    }
    
    // Update time and date
    function updateTime() {
        const now = new Date();
        const timeString = now.toLocaleTimeString('en-US', { 
            hour12: true, 
            hour: '2-digit', 
            minute: '2-digit',
            second: '2-digit'
        });
        const dateString = now.toLocaleDateString('en-US', {
            weekday: 'short',
            year: 'numeric',
            month: 'short',
            day: 'numeric'
        });
        
        const timeElement = document.getElementById('currentTime');
        const dateElement = document.getElementById('currentDate');
        
        if (timeElement) timeElement.textContent = timeString;
        if (dateElement) dateElement.textContent = dateString;
    }
    
    // Load live stats from server
    function loadLiveStats() {
        function updateStats() {
            fetch('ajax/get_lock_stats.php')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Update stats cards
                        const stat1 = document.getElementById('stat1');
                        const stat2 = document.getElementById('stat2');
                        const stat3 = document.getElementById('stat3');
                        const stat4 = document.getElementById('stat4');
                        
                        if (stat1) stat1.textContent = data.active_users;
                        if (stat2) stat2.textContent = data.trades_today;
                        if (stat3) stat3.textContent = '$' + parseFloat(data.volume_24h).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
                        if (stat4) stat4.textContent = data.open_tickets;
                        
                        // Update gauges
                        if (gauge1) {
                            const loadValue = data.system_load;
                            gauge1.data.datasets[0].data = [loadValue, 100 - loadValue];
                            gauge1.data.datasets[0].backgroundColor[0] = 
                                loadValue > 80 ? '#ff6b6b' : 
                                loadValue > 60 ? '#ffa726' : '#43e97b';
                            gauge1.update();
                            
                            const gauge1Value = document.getElementById('gauge1Value');
                            if (gauge1Value) gauge1Value.textContent = loadValue + '%';
                        }
                        
                        if (gauge2) {
                            const profitValue = parseFloat(data.profit_today);
                            const maxProfit = Math.max(profitValue * 2, 1000);
                            const profitPercentage = Math.min((profitValue / maxProfit) * 100, 100);
                            gauge2.data.datasets[0].data = [profitPercentage, 100 - profitPercentage];
                            gauge2.data.datasets[0].backgroundColor[0] = profitValue > 0 ? '#43e97b' : '#ff6b6b';
                            gauge2.update();
                            
                            const gauge2Value = document.getElementById('gauge2Value');
                            if (gauge2Value) gauge2Value.textContent = '$' + profitValue.toFixed(2);
                        }
                        
                        // Add glitch effect randomly
                        if (Math.random() < 0.02 && !isMobile) {
                            const randomStat = Math.floor(Math.random() * 4) + 1;
                            const statElement = document.getElementById('stat' + randomStat);
                            if (statElement) {
                                statElement.classList.add('glitch');
                                setTimeout(() => {
                                    statElement.classList.remove('glitch');
                                }, 1000);
                            }
                        }
                    }
                })
                .catch(error => {
                    console.error('Error fetching stats:', error);
                });
            
            // Update again in 10 seconds (less frequent on mobile)
            setTimeout(updateStats, isMobile ? 10000 : 5000);
        }
        
        updateStats();
    }
    
    // Handle unlock form
    function setupForm() {
        const form = document.getElementById('unlockForm');
        if (!form) return;
        
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const password = document.getElementById('password').value;
            const unlockBtn = document.getElementById('unlockBtn');
            const errorMsg = document.getElementById('errorMsg');
            
            if (!password) {
                if (errorMsg) {
                    errorMsg.textContent = 'Please enter your password';
                    errorMsg.style.display = 'block';
                }
                return;
            }
            
            // Disable button and show loading
            if (unlockBtn) {
                unlockBtn.disabled = true;
                unlockBtn.classList.add('btn-loading');
                unlockBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i> Verifying...';
            }
            
            // Send password to server for verification
            fetch('ajax/verify_lock_password.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'password=' + encodeURIComponent(password)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Successful unlock
                    if (unlockBtn) {
                        unlockBtn.innerHTML = '<i class="fas fa-check me-2"></i> Access Granted!';
                        unlockBtn.style.background = 'linear-gradient(45deg, #43e97b, #38f9d7)';
                    }
                    
                    // Redirect to dashboard after delay
                    setTimeout(() => {
                        window.location.href = 'index.php';
                    }, 800);
                } else {
                    // Failed attempt
                    if (errorMsg) {
                        errorMsg.textContent = data.message || 'Incorrect password. Try again.';
                        errorMsg.style.display = 'block';
                    }
                    
                    if (unlockBtn) {
                        unlockBtn.disabled = false;
                        unlockBtn.classList.remove('btn-loading');
                        unlockBtn.innerHTML = '<i class="fas fa-unlock me-2"></i> Unlock Dashboard';
                    }
                    
                    // Shake animation
                    const lockBox = document.querySelector('.lock-box');
                    if (lockBox) {
                        lockBox.style.animation = 'none';
                        lockBox.style.transform = 'translateX(10px)';
                        setTimeout(() => {
                            lockBox.style.transform = 'translateX(-10px)';
                            setTimeout(() => {
                                lockBox.style.transform = 'translateX(0)';
                                lockBox.style.animation = 'float 6s ease-in-out infinite';
                            }, 50);
                        }, 50);
                    }
                    
                    // Clear password field
                    const passwordInput = document.getElementById('password');
                    if (passwordInput) {
                        passwordInput.value = '';
                        passwordInput.focus();
                    }
                }
            })
            .catch(error => {
                if (errorMsg) {
                    errorMsg.textContent = 'Network error. Please try again.';
                    errorMsg.style.display = 'block';
                }
                
                if (unlockBtn) {
                    unlockBtn.disabled = false;
                    unlockBtn.classList.remove('btn-loading');
                    unlockBtn.innerHTML = '<i class="fas fa-unlock me-2"></i> Unlock Dashboard';
                }
            });
        });
    }
    
    // Auto-lock timer (inactivity detection)
    let idleTime = 0;
    let idleInterval;
    
    function startIdleTimer() {
        if (idleInterval) clearInterval(idleInterval);
        
        idleInterval = setInterval(() => {
            idleTime++;
            if (idleTime > 29) { // 30 minutes idle
                // Already on lock screen, do nothing
            }
        }, 60000); // 1 minute
    }
    
    // Reset idle timer on user activity
    function resetIdleTimer() {
        idleTime = 0;
    }
    
    // Password visibility toggle
    function setupPasswordToggle() {
        const passwordInput = document.getElementById('password');
        const icon = document.querySelector('.password-input i');
        
        if (!passwordInput || !icon) return;
        
        passwordInput.addEventListener('input', function(e) {
            if (e.target.value) {
                icon.classList.remove('fa-lock');
                icon.classList.add('fa-key');
            } else {
                icon.classList.remove('fa-key');
                icon.classList.add('fa-lock');
            }
        });
        
        // Show/hide password on mobile (long press on icon)
        if (isMobile) {
            let touchStartTime;
            icon.style.cursor = 'pointer';
            
            icon.addEventListener('touchstart', function(e) {
                touchStartTime = Date.now();
                e.preventDefault();
            });
            
            icon.addEventListener('touchend', function(e) {
                if (Date.now() - touchStartTime > 500) { // Long press
                    const type = passwordInput.getAttribute('type');
                    passwordInput.setAttribute('type', type === 'password' ? 'text' : 'password');
                    icon.classList.toggle('fa-eye');
                    icon.classList.toggle('fa-eye-slash');
                    e.preventDefault();
                }
            });
        }
    }
    
    // Handle orientation change
    function handleOrientationChange() {
        // Wait a bit for orientation to settle
        setTimeout(() => {
            if (gauge1) gauge1.resize();
            if (gauge2) gauge2.resize();
            updateLayoutForScreenSize();
        }, 300);
    }
    
    // Update layout based on screen size
    function updateLayoutForScreenSize() {
        const isNowSmallScreen = window.innerWidth < 768;
        
        if (isNowSmallScreen && !isSmallScreen) {
            // Switched to mobile
            if (scene && renderer) {
                document.getElementById('bg3d').style.display = 'none';
            }
        }
    }
    
    // Initialize everything
    document.addEventListener('DOMContentLoaded', function() {
        // Initialize based on screen size
        updateLayoutForScreenSize();
        
        // Initialize 3D (only on desktop)
        init3D();
        
        // Initialize speedometers
        initSpeedometers();
        
        // Create floating particles
        createFloatingParticles();
        
        // Update time
        updateTime();
        
        // Setup form
        setupForm();
        
        // Setup password toggle
        setupPasswordToggle();
        
        // Start loading stats
        setTimeout(loadLiveStats, 1000);
        
        // Update time every second
        setInterval(updateTime, 1000);
        
        // Start idle timer
        startIdleTimer();
        
        // Auto-focus password input
        setTimeout(() => {
            const passwordInput = document.getElementById('password');
            if (passwordInput) {
                passwordInput.focus();
                
                // On mobile, ensure keyboard doesn't cover input
                if (isMobile) {
                    setTimeout(() => {
                        passwordInput.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    }, 300);
                }
            }
        }, 500);
        
        // Add activity listeners for idle timer
        ['mousemove', 'keydown', 'click', 'touchstart', 'scroll'].forEach(event => {
            document.addEventListener(event, resetIdleTimer);
        });
        
        // Handle orientation change
        window.addEventListener('orientationchange', handleOrientationChange);
        window.addEventListener('resize', handleOrientationChange);
    });
    
    // Prevent zoom on double tap (mobile)
    let lastTouchEnd = 0;
    document.addEventListener('touchend', function(event) {
        const now = Date.now();
        if (now - lastTouchEnd <= 300) {
            event.preventDefault();
        }
        lastTouchEnd = now;
    }, false);
    
    // Prevent pull-to-refresh on mobile
    document.addEventListener('touchmove', function(e) {
        if (e.scale !== 1) {
            e.preventDefault();
        }
    }, { passive: false });
    
    // Handle back button on mobile (prevent going back to locked state)
    window.addEventListener('popstate', function(event) {
        if (window.location.pathname.includes('lock_screen.php')) {
            window.history.forward();
        }
    });
    
    // Add to history to prevent back navigation
    if (window.history && window.history.pushState) {
        window.history.pushState(null, null, window.location.href);
        window.addEventListener('popstate', function() {
            window.history.pushState(null, null, window.location.href);
        });
    }
    </script>
</body>
</html>