<?php
session_start();

// Check if came from login page
if (!isset($_SESSION['admin_temp_id'])) {
    header('Location: login.php');
    exit();
}

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

$error = '';
$success = '';

// Handle PIN submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $pin = isset($_POST['pin']) ? trim($_POST['pin']) : '';
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? '';
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    
    // Get admin's actual PIN from database
    $admin_id = $_SESSION['admin_temp_id'];
    $sql = "SELECT * FROM admins WHERE id = '$admin_id'";
    $result = mysqli_query($conn, $sql);
    $admin = mysqli_fetch_assoc($result);
    
    // For now, using hardcoded PIN. You should store PINs in database
    $admin_pin = "1234"; // Default PIN. You should get this from database
    
    // Check PIN
    if ($pin === $admin_pin) {
        // Successful login
        $_SESSION['admin_logged_in'] = true;
        $_SESSION['admin_id'] = $admin['id'];
        $_SESSION['admin_name'] = $admin['name'];
        $_SESSION['admin_email'] = $admin['email'];
        $_SESSION['admin_role'] = $admin['role'];
        
        // Update last login
        $update_sql = "UPDATE admins SET last_login = NOW(), last_login_ip = '$ip_address' WHERE id = '$admin_id'";
        mysqli_query($conn, $update_sql);
        
        // Log admin activity
        $log_sql = "INSERT INTO admin_activities (admin_id, admin_name, admin_role, action, description, ip_address, user_agent) 
                   VALUES ('{$admin['id']}', '{$admin['name']}', '{$admin['role']}', 'Login', 
                   'Admin logged into the system', '{$ip_address}', '{$user_agent}')";
        mysqli_query($conn, $log_sql);
        
        // NOTIFICATION: Admin Login Success (ADMIN)
        $mail_subject = "Admin Login Successful - " . $admin['name'];
        $mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting'>Admin Login Notification</h2>
                            
                            <p class='message'>
                                A successful admin login has been detected on the system.
                            </p>

                            <!-- Login Details -->
                            <div class='details-section'>
                                <div class='detail-box'>
                                    <strong>Admin Name:</strong> " . $admin['name'] . "<br>
                                    <strong>Admin Email:</strong> " . $admin['email'] . "<br>
                                    <strong>Admin Role:</strong> " . $admin['role'] . "<br>
                                    <strong>Login Time:</strong> " . date('F j, Y g:i A') . "<br>
                                    <strong>IP Address:</strong> " . $ip_address . "<br>
                                    <strong>Device:</strong> " . getDeviceType($user_agent) . "<br>
                                    <strong>Browser:</strong> " . getBrowserName($user_agent) . "<br>
                                    <strong>Status:</strong> <span style='color: #28a745; font-weight: bold;'>SUCCESSFUL</span>
                                </div>
                            </div>

                            <!-- Security Alert -->
                            <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #0056b3;'>🔐 Security Check</h4>
                                <p style='color: #0056b3;'>
                                    <strong>If this was you:</strong> No action needed.<br>
                                    <strong>If you did not attempt this login:</strong> Contact system administrator immediately!
                                </p>
                            </div>

                            <!-- Admin Actions -->
                            <div style='text-align: center; margin: 30px 0;'>
                                <a href='" . $myUrl . "/admin/index.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                    Go to Dashboard
                                </a>
                                <a href='" . $myUrl . "/admin/security.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #0dcaf0; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                    Security Settings
                                </a>
                            </div>
                        </div>";

        // Send admin notification
        require_once("../proccess/admin_mailer.php");
        
        // Clear temp session
        unset($_SESSION['admin_temp_id']);
        unset($_SESSION['admin_temp_name']);
        unset($_SESSION['admin_temp_email']);
        unset($_SESSION['admin_temp_role']);
        unset($_SESSION['login_attempts']);
        unset($_SESSION['pin_attempts']);
        
        // Redirect to dashboard
        header('Location: index.php');
        exit();
    } else {
        $error = "Invalid PIN!";
        
        // Track PIN attempts
        if (!isset($_SESSION['pin_attempts'])) {
            $_SESSION['pin_attempts'] = 1;
        } else {
            $_SESSION['pin_attempts']++;
        }
        
        // Lock after 3 failed attempts
        if ($_SESSION['pin_attempts'] >= 3) {
            
            // NOTIFICATION: Failed PIN Attempts - Lockout (ADMIN)
            $mail_subject = "⚠️ SECURITY ALERT: Admin PIN Lockout";
            $mail_message = "<!-- Content Section -->
                            <div class='email-content'>
                                <h2 class='greeting'>Security Alert: PIN Lockout</h2>
                                
                                <p class='message'>
                                    <strong style='color: #dc3545;'>Multiple failed PIN attempts detected!</strong><br>
                                    An admin account has been locked due to too many incorrect PIN entries.
                                </p>

                                <!-- Lockout Details -->
                                <div class='details-section'>
                                    <div class='detail-box'>
                                        <strong>Admin Name:</strong> " . $admin['name'] . "<br>
                                        <strong>Admin Email:</strong> " . $admin['email'] . "<br>
                                        <strong>Failed Attempts:</strong> " . $_SESSION['pin_attempts'] . "<br>
                                        <strong>Lockout Time:</strong> " . date('F j, Y g:i A') . "<br>
                                        <strong>IP Address:</strong> " . $ip_address . "<br>
                                        <strong>Device:</strong> " . getDeviceType($user_agent) . "<br>
                                        <strong>Status:</strong> <span style='color: #dc3545; font-weight: bold;'>ACCOUNT LOCKED</span>
                                    </div>
                                </div>

                                <!-- Urgent Action Required -->
                                <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                    <h4 style='color: #721c24;'>🚨 URGENT ACTION REQUIRED</h4>
                                    <p style='color: #721c24;'>
                                        <strong>This account has been temporarily locked.</strong><br>
                                        The user must login again with correct credentials.<br>
                                        Check if this was an attempted security breach.
                                    </p>
                                </div>

                                <!-- Recommended Actions -->
                                <div class='next-steps'>
                                    <h3 style='color: #2c3e50;'>📋 Recommended Actions</h3>
                                    <ul style='color: #6c757d;'>
                                        <li>Verify if the admin attempted to login</li>
                                        <li>Check for unusual access patterns</li>
                                        <li>Consider changing the admin PIN</li>
                                        <li>Enable 2FA for enhanced security</li>
                                        <li>Monitor for further suspicious activity</li>
                                    </ul>
                                </div>

                                <!-- Admin Actions -->
                                <div style='text-align: center; margin: 30px 0;'>
                                    <a href='" . $myUrl . "/admin/login.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #dc3545; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                        Return to Login
                                    </a>
                                    <a href='" . $myUrl . "/admin/security-audit.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #6c757d; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                        Security Audit
                                    </a>
                                </div>
                            </div>";

            // Send admin notification
            require_once("../proccess/admin_mailer.php");
            
            session_destroy();
            header('Location: login.php?error=Too many failed PIN attempts. Please login again.');
            exit();
        }
    }
}

// Helper functions
function getBrowserName($user_agent) {
    if (strpos($user_agent, 'Chrome') !== false) return 'Chrome';
    if (strpos($user_agent, 'Firefox') !== false) return 'Firefox';
    if (strpos($user_agent, 'Safari') !== false) return 'Safari';
    if (strpos($user_agent, 'Edge') !== false) return 'Edge';
    if (strpos($user_agent, 'Opera') !== false) return 'Opera';
    return 'Unknown Browser';
}

function getDeviceType($user_agent) {
    if (strpos($user_agent, 'Mobile') !== false) return 'Mobile';
    if (strpos($user_agent, 'Tablet') !== false) return 'Tablet';
    if (strpos($user_agent, 'iPad') !== false) return 'iPad';
    return 'Desktop';
}
?>

<!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">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../images/favicon.ico">

    <title>AI Trading - PIN Verification</title>
  
	<!-- Vendors Style-->
	<link rel="stylesheet" href="css/vendors_css.css">
	  
	<!-- Style-->  
	<link rel="stylesheet" href="css/style.css">
	<link rel="stylesheet" href="css/skin_color.css">
	
	<!-- Font Awesome -->
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
	
	<!-- ApexCharts for gauges -->
	<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>

    <style>
    * {
        -webkit-tap-highlight-color: transparent;
        box-sizing: border-box;
    }
    
    body {
        margin: 0;
        padding: 0;
        overflow-x: 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;
        min-height: 100vh;
        width: 100%;
        position: relative;
        touch-action: pan-y;
    }
    
    @keyframes gradientBG {
        0% { background-position: 0% 50%; }
        50% { background-position: 100% 50%; }
        100% { background-position: 0% 50%; }
    }
    
    .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; }
    }
    
    /* MAIN CONTAINER - MOBILE FIRST */
    .main-container {
        display: flex;
        flex-direction: column;
        min-height: 100vh;
        padding: 15px;
        position: relative;
        z-index: 1;
    }
    
    /* HEADER SECTION - Time Display */
    .header-section {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 20px;
        flex-wrap: wrap;
        gap: 15px;
    }
    
    .time-display {
        color: white;
        background: rgba(0, 0, 0, 0.3);
        padding: 12px 15px;
        border-radius: 10px;
        backdrop-filter: blur(10px);
        -webkit-backdrop-filter: blur(10px);
        border: 1px solid rgba(255, 255, 255, 0.1);
        flex: 1;
        min-width: 200px;
        order: 1;
    }
    
    .time-display #currentDate {
        font-size: 12px;
        color: rgba(255, 255, 255, 0.8);
        margin-bottom: 3px;
    }
    
    .time-display #currentTime {
        font-size: 18px;
        font-weight: 600;
        color: white;
        text-shadow: 0 0 10px rgba(102, 126, 234, 0.5);
    }
    
    .time-display small {
        font-size: 11px;
        color: rgba(255, 255, 255, 0.6);
        display: block;
        margin-top: 5px;
    }
    
    /* GAUGES SECTION - Only show on larger screens */
    .gauges-section {
        display: none;
        gap: 15px;
        order: 2;
    }
    
    .speedometer-card {
        background: rgba(255, 255, 255, 0.1);
        backdrop-filter: blur(10px);
        -webkit-backdrop-filter: blur(10px);
        border-radius: 15px;
        padding: 15px;
        width: 140px;
        height: 140px;
        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;
    }
    
    /* MAIN CONTENT - Centered Login Box */
    .content-section {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        flex: 1;
        padding: 20px 0;
        min-height: calc(100vh - 250px);
    }
    
    .lock-box {
        background: rgba(255, 255, 255, 0.1);
        backdrop-filter: blur(20px);
        -webkit-backdrop-filter: blur(20px);
        border-radius: 25px;
        padding: 25px;
        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: 2;
        margin: 0 auto;
    }
    
    @keyframes float {
        0%, 100% { transform: translateY(0px); }
        50% { transform: translateY(-8px); }
    }
    
    .avatar {
        width: 80px;
        height: 80px;
        margin: 0 auto 15px;
        border-radius: 50%;
        background: linear-gradient(45deg, #667eea, #764ba2);
        display: flex;
        align-items: center;
        justify-content: center;
        border: 4px 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 12px rgba(102, 126, 234, 0); }
    }
    
    .avatar i {
        font-size: 32px;
        color: white;
    }
    
    h1 {
        color: white;
        margin-bottom: 5px;
        font-weight: 600;
        font-size: 20px;
        line-height: 1.3;
    }
    
    .subtitle {
        color: rgba(255, 255, 255, 0.7);
        margin-bottom: 20px;
        font-size: 13px;
        line-height: 1.4;
    }
    
    /* PIN Input Styles */
    .pin-display {
        display: flex;
        justify-content: center;
        gap: 12px;
        margin: 20px 0;
    }
    
    .pin-digit {
        width: 55px;
        height: 55px;
        border-radius: 12px;
        background: rgba(255, 255, 255, 0.1);
        border: 2px solid rgba(255, 255, 255, 0.2);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 22px;
        font-weight: bold;
        color: white;
        transition: all 0.3s;
    }
    
    .pin-digit.active {
        border-color: #667eea;
        background: rgba(102, 126, 234, 0.2);
        box-shadow: 0 0 15px rgba(102, 126, 234, 0.4);
        transform: scale(1.1);
    }
    
    .pin-digit.filled {
        background: linear-gradient(45deg, #667eea, #764ba2);
        border-color: transparent;
    }
    
    .pin-keypad {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 12px;
        margin-top: 20px;
    }
    
    .pin-key {
        height: 55px;
        border-radius: 12px;
        background: rgba(255, 255, 255, 0.1);
        border: 2px solid rgba(255, 255, 255, 0.2);
        color: white;
        font-size: 18px;
        font-weight: bold;
        cursor: pointer;
        transition: all 0.3s;
        display: flex;
        align-items: center;
        justify-content: center;
        -webkit-user-select: none;
        user-select: none;
    }
    
    .pin-key:hover {
        background: rgba(255, 255, 255, 0.2);
        transform: translateY(-2px);
    }
    
    .pin-key:active {
        transform: scale(0.95);
    }
    
    .pin-key.clear {
        background: rgba(255, 107, 107, 0.2);
        border-color: rgba(255, 107, 107, 0.3);
        color: #ff6b6b;
    }
    
    .pin-key.backspace {
        background: rgba(255, 193, 7, 0.2);
        border-color: rgba(255, 193, 7, 0.3);
        color: #ffc107;
    }
    
    .pin-key.submit {
        background: linear-gradient(45deg, #667eea, #764ba2);
        border-color: transparent;
        color: white;
        grid-column: span 2;
    }
    
    /* Alerts and Info */
    .error-alert {
        background: rgba(255, 107, 107, 0.1);
        border: 1px solid rgba(255, 107, 107, 0.3);
        border-radius: 10px;
        padding: 12px;
        margin: 15px 0;
        text-align: left;
    }
    
    .error-alert i {
        color: #ff6b6b;
        margin-right: 8px;
    }
    
    .error-alert h6 {
        color: white;
        margin: 0 0 5px 0;
        font-size: 12px;
    }
    
    .error-alert small {
        color: rgba(255, 255, 255, 0.7);
        font-size: 11px;
        line-height: 1.4;
    }
    
    .admin-info {
        color: rgba(255, 255, 255, 0.8);
        font-size: 13px;
        margin: 15px 0;
        padding: 12px;
        background: rgba(0, 0, 0, 0.2);
        border-radius: 10px;
        text-align: left;
    }
    
    .security-alert {
        background: rgba(13, 202, 240, 0.1);
        border: 1px solid rgba(13, 202, 240, 0.3);
        border-radius: 10px;
        padding: 12px;
        margin: 15px 0;
        text-align: left;
    }
    
    .security-alert i {
        color: #0dcaf0;
        margin-right: 8px;
    }
    
    .security-alert h6 {
        color: white;
        margin: 0 0 5px 0;
        font-size: 12px;
    }
    
    .security-alert small {
        color: rgba(255, 255, 255, 0.7);
        font-size: 11px;
        line-height: 1.4;
    }
    
    /* Back Button */
    .back-btn {
        display: block;
        width: 100%;
        padding: 12px;
        background: rgba(255, 255, 255, 0.1);
        border: 1px solid rgba(255, 255, 255, 0.2);
        border-radius: 12px;
        color: white;
        font-size: 14px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s;
        text-align: center;
        text-decoration: none;
        margin-top: 15px;
    }
    
    .back-btn:hover {
        background: rgba(255, 255, 255, 0.2);
        transform: translateY(-2px);
    }
    
    /* STATS SECTION - Bottom Stats */
    .stats-section {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 12px;
        margin-top: 20px;
        order: 4;
    }
    
    .stat-card {
        background: rgba(255, 255, 255, 0.1);
        backdrop-filter: blur(10px);
        -webkit-backdrop-filter: blur(10px);
        border-radius: 12px;
        padding: 15px 10px;
        color: white;
        border: 1px solid rgba(255, 255, 255, 0.1);
        text-align: center;
        min-height: 70px;
        display: flex;
        flex-direction: column;
        justify-content: center;
    }
    
    .stat-value {
        font-size: 18px;
        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;
    }
    
    /* Animations */
    @keyframes shake {
        0%, 100% { transform: translateX(0); }
        10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
        20%, 40%, 60%, 80% { transform: translateX(5px); }
    }
    
    .shake {
        animation: shake 0.5s ease-in-out;
    }
    
    /* RESPONSIVE BREAKPOINTS */
    
    /* Small phones (under 360px) */
    @media (max-width: 359px) {
        .main-container {
            padding: 10px;
        }
        
        .lock-box {
            padding: 20px 15px;
            border-radius: 20px;
        }
        
        .pin-digit {
            width: 45px;
            height: 45px;
            font-size: 18px;
        }
        
        .pin-key {
            height: 50px;
            font-size: 16px;
        }
        
        .avatar {
            width: 70px;
            height: 70px;
        }
        
        .avatar i {
            font-size: 28px;
        }
        
        h1 {
            font-size: 18px;
        }
        
        .subtitle {
            font-size: 12px;
        }
        
        .time-display {
            min-width: 100%;
            order: 1;
        }
        
        .stats-section {
            grid-template-columns: repeat(2, 1fr);
            gap: 10px;
        }
    }
    
    /* Tablets and larger phones (768px and up) */
    @media (min-width: 768px) {
        .main-container {
            padding: 25px;
        }
        
        .header-section {
            margin-bottom: 30px;
        }
        
        .gauges-section {
            display: flex;
            order: 2;
        }
        
        .lock-box {
            padding: 30px;
            max-width: 450px;
        }
        
        .avatar {
            width: 100px;
            height: 100px;
            margin-bottom: 20px;
        }
        
        .avatar i {
            font-size: 40px;
        }
        
        h1 {
            font-size: 24px;
        }
        
        .subtitle {
            font-size: 14px;
            margin-bottom: 25px;
        }
        
        .pin-digit {
            width: 65px;
            height: 65px;
            font-size: 24px;
        }
        
        .pin-key {
            height: 65px;
            font-size: 20px;
        }
        
        .time-display {
            min-width: 250px;
        }
        
        .stats-section {
            grid-template-columns: repeat(4, 1fr);
            gap: 15px;
            margin-top: 30px;
        }
        
        .stat-card {
            padding: 20px 15px;
            min-height: 90px;
        }
        
        .stat-value {
            font-size: 22px;
        }
        
        .stat-label {
            font-size: 12px;
        }
    }
    
    /* Desktop (1024px and up) */
    @media (min-width: 1024px) {
        .main-container {
            padding: 40px;
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .content-section {
            min-height: calc(100vh - 300px);
        }
        
        .lock-box {
            max-width: 500px;
            padding: 40px;
        }
        
        .pin-digit {
            width: 70px;
            height: 70px;
        }
        
        .pin-key {
            height: 70px;
        }
        
        .stats-section {
            margin-top: 40px;
        }
    }
    
    /* Landscape mode */
    @media (max-height: 600px) and (orientation: landscape) {
        .main-container {
            padding: 10px;
        }
        
        .content-section {
            min-height: auto;
            padding: 10px 0;
        }
        
        .lock-box {
            max-width: 90%;
            padding: 20px;
            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: 60px;
            height: 60px;
            margin-bottom: 10px;
        }
        
        .avatar i {
            font-size: 24px;
        }
        
        h1 {
            font-size: 18px;
            margin-bottom: 3px;
        }
        
        .subtitle {
            font-size: 11px;
            margin-bottom: 15px;
        }
        
        .pin-display {
            margin: 15px 0;
        }
        
        .pin-digit {
            width: 45px;
            height: 45px;
            font-size: 18px;
        }
        
        .pin-keypad {
            margin-top: 15px;
            gap: 10px;
        }
        
        .pin-key {
            height: 45px;
            font-size: 16px;
        }
        
        .stats-section {
            display: none; /* Hide stats in landscape on small screens */
        }
    }
    
    /* Very tall screens */
    @media (min-height: 900px) {
        .content-section {
            min-height: calc(100vh - 350px);
        }
        
        .lock-box {
            max-width: 450px;
        }
    }
    
    /* Prevent zoom on iOS */
    @media screen and (max-width: 767px) {
        input, textarea, .pin-key {
            font-size: 16px !important;
        }
    }
    
    /* Custom scrollbar */
    ::-webkit-scrollbar {
        width: 5px;
    }
    
    ::-webkit-scrollbar-track {
        background: rgba(255, 255, 255, 0.1);
        border-radius: 10px;
    }
    
    ::-webkit-scrollbar-thumb {
        background: rgba(102, 126, 234, 0.5);
        border-radius: 10px;
    }
    
    /* Loading animation */
    @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;
    }
    
    /* Particles container */
    .particles {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        pointer-events: none;
        z-index: 0;
    }
    
    /* Ensure touch feedback works */
    .pin-key, .back-btn {
        -webkit-tap-highlight-color: rgba(255, 255, 255, 0.1);
    }
    
    /* Hide focus outlines for mouse users, keep for keyboard */
    .pin-key:focus:not(:focus-visible),
    .back-btn:focus:not(:focus-visible) {
        outline: none;
    }
    </style>
</head>
	
<body>
    <!-- Animated Background -->
    <div class="gradient-overlay"></div>
    
    <!-- Main Container -->
    <div class="main-container">
        
        <!-- Header with Time and Gauges -->
        <div class="header-section">
            <div class="time-display">
                <div id="currentDate"></div>
                <div id="currentTime"></div>
                <small>AI Trading Admin Portal</small>
            </div>
            
            <div class="gauges-section">
                <!-- Gauges will be added via JavaScript -->
            </div>
        </div>
        
        <!-- Main Content - Login Box -->
        <div class="content-section">
            <div class="lock-box">
                <div class="avatar">
                    <i class="fas fa-user-shield"></i>
                </div>
                
                <h1>SECURITY VERIFICATION</h1>
                <div class="subtitle">
                    Hello, <strong><?php echo htmlspecialchars($_SESSION['admin_temp_name']); ?></strong>
                    <br>Enter your 4-digit PIN to access the admin panel
                </div>
                
                <?php if ($error): ?>
                    <div class="error-alert shake">
                        <h6><i class="fas fa-exclamation-circle"></i> Invalid PIN!</h6>
                        <small>
                            Attempt <?php echo isset($_SESSION['pin_attempts']) ? $_SESSION['pin_attempts'] : 1; ?> of 3.
                            <?php if (isset($_SESSION['pin_attempts']) && $_SESSION['pin_attempts'] >= 2): ?>
                                <br>One more failed attempt will lock you out.
                            <?php endif; ?>
                        </small>
                    </div>
                <?php endif; ?>
                
                <div class="admin-info">
                    <i class="fas fa-id-badge"></i> Role: <?php echo ucfirst(str_replace('_', ' ', $_SESSION['admin_temp_role'])); ?>
                    <br><i class="fas fa-envelope"></i> <?php echo htmlspecialchars($_SESSION['admin_temp_email']); ?>
                </div>
                
                <form action="" method="POST" id="pinForm">
                    <!-- Hidden PIN input for form submission -->
                    <input type="hidden" name="pin" id="hiddenPin">
                    
                    <!-- PIN Display -->
                    <div class="pin-display">
                        <?php for ($i = 0; $i < 4; $i++): ?>
                            <div class="pin-digit" id="pinDigit<?php echo $i; ?>"></div>
                        <?php endfor; ?>
                    </div>
                    
                    <!-- Keypad -->
                    <div class="pin-keypad">
                        <?php for ($i = 1; $i <= 9; $i++): ?>
                            <div class="pin-key" data-key="<?php echo $i; ?>"><?php echo $i; ?></div>
                        <?php endfor; ?>
                        
                        <div class="pin-key clear" id="clearPin">
                            <i class="fas fa-times"></i>
                        </div>
                        <div class="pin-key" data-key="0">0</div>
                        <div class="pin-key backspace" id="backspacePin">
                            <i class="fas fa-backspace"></i>
                        </div>
                        
                        <button type="submit" class="pin-key submit" id="submitPin">
                            <i class="fas fa-unlock-alt me-2"></i> VERIFY
                        </button>
                    </div>
                </form>
                
                <div class="security-alert">
                    <h6><i class="fas fa-shield-alt"></i> SECURITY NOTICE</h6>
                    <small>
                        Never share your PIN with anyone. 
                        All access attempts are logged and monitored.
                    </small>
                </div>
                
                <a href="login.php" class="back-btn">
                    <i class="fas fa-arrow-left me-2"></i> BACK TO LOGIN
                </a>
            </div>
        </div>
        
        <!-- Stats Section -->
        <div class="stats-section">
            <div class="stat-card">
                <div class="stat-value">$<?php echo rand(1000, 9999); ?></div>
                <div class="stat-label">Total Profit</div>
            </div>
            <div class="stat-card">
                <div class="stat-value"><?php echo rand(50, 200); ?></div>
                <div class="stat-label">Live Trades</div>
            </div>
            <div class="stat-card">
                <div class="stat-value"><?php echo rand(100, 500); ?></div>
                <div class="stat-label">Active Users</div>
            </div>
            <div class="stat-card">
                <div class="stat-value"><?php echo rand(85, 98); ?>%</div>
                <div class="stat-label">Success Rate</div>
            </div>
        </div>
        
    </div>

	<!-- Vendor JS -->
	<script src="js/vendors.min.js"></script>
	<script src="../assets/icons/feather-icons/feather.min.js"></script>
	
	<!-- SweetAlert2 -->
	<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
	
	<script>
	$(document).ready(function() {
		// Initialize variables
		let pin = '';
		let currentDigit = 0;
		
		// Update date and time
		function updateDateTime() {
			const now = new Date();
			const dateStr = now.toLocaleDateString('en-US', { 
				weekday: 'short', 
				year: 'numeric', 
				month: 'short', 
				day: 'numeric' 
			});
			const timeStr = now.toLocaleTimeString('en-US', { 
				hour12: true, 
				hour: '2-digit', 
				minute: '2-digit',
				second: '2-digit'
			});
			
			$('#currentDate').text(dateStr);
			$('#currentTime').text(timeStr);
		}
		
		// Update time every second
		updateDateTime();
		setInterval(updateDateTime, 1000);
		
		// Update PIN display
		function updatePinDisplay() {
			// Clear all digits
			$('.pin-digit').removeClass('filled active');
			
			// Fill digits with entered numbers
			for (let i = 0; i < pin.length; i++) {
				$('#pinDigit' + i).addClass('filled').text('•');
			}
			
			// Highlight current digit
			if (currentDigit < 4) {
				$('#pinDigit' + currentDigit).addClass('active');
			}
			
			// Update hidden input
			$('#hiddenPin').val(pin);
		}
		
		// Handle number key presses
		$('.pin-key[data-key]').click(function() {
			if (pin.length < 4) {
				const key = $(this).data('key');
				pin += key;
				currentDigit = pin.length;
				updatePinDisplay();
				
				// Auto-focus submit button when 4 digits are entered
				if (pin.length === 4) {
					setTimeout(() => {
						$('#submitPin').focus();
					}, 100);
				}
			}
		});
		
		// Handle backspace
		$('#backspacePin').click(function() {
			if (pin.length > 0) {
				pin = pin.slice(0, -1);
				currentDigit = pin.length;
				updatePinDisplay();
			}
		});
		
		// Handle clear
		$('#clearPin').click(function() {
			pin = '';
			currentDigit = 0;
			updatePinDisplay();
		});
		
		// Handle keyboard input
		$(document).keydown(function(e) {
			const key = e.key;
			
			// Number keys 0-9
			if (/^[0-9]$/.test(key) && pin.length < 4) {
				pin += key;
				currentDigit = pin.length;
				updatePinDisplay();
			}
			
			// Backspace
			if (key === 'Backspace' && pin.length > 0) {
				e.preventDefault();
				pin = pin.slice(0, -1);
				currentDigit = pin.length;
				updatePinDisplay();
			}
			
			// Enter to submit
			if (key === 'Enter' && pin.length === 4) {
				$('#pinForm').submit();
			}
			
			// Escape to clear
			if (key === 'Escape') {
				pin = '';
				currentDigit = 0;
				updatePinDisplay();
			}
		});
		
		// Form validation
		$('#pinForm').submit(function(e) {
			if (pin.length !== 4) {
				e.preventDefault();
				
				// Add shake effect to PIN display
				$('.pin-display').addClass('shake');
				setTimeout(() => {
					$('.pin-display').removeClass('shake');
				}, 500);
				
				return false;
			}
			
			// Show loading state
			$('#submitPin').html('<i class="fas fa-spinner fa-spin me-2"></i> VERIFYING...');
			$('#submitPin').prop('disabled', true);
			$('#submitPin').addClass('btn-loading');
		});
		
		// Initialize PIN display
		updatePinDisplay();
		
		// Create floating particles
		function createParticles() {
			const particlesContainer = $('<div class="particles"></div>');
			$('body').append(particlesContainer);
			
			for (let i = 0; i < 15; i++) {
				const particle = $('<div class="particle"></div>');
				particle.css({
					position: 'fixed',
					width: Math.random() * 4 + 1 + 'px',
					height: Math.random() * 4 + 1 + 'px',
					background: `rgba(${Math.floor(Math.random() * 100 + 156)}, ${Math.floor(Math.random() * 100 + 156)}, 255, ${Math.random() * 0.2 + 0.1})`,
					borderRadius: '50%',
					left: Math.random() * 100 + '%',
					top: Math.random() * 100 + '%',
					zIndex: 1,
					animation: `floatParticle ${Math.random() * 20 + 10}s linear infinite`
				});
				particlesContainer.append(particle);
			}
			
			// Add CSS for particle animation
			$('head').append(`
				<style>
					@keyframes floatParticle {
						0% { transform: translate(0, 0) rotate(0deg); opacity: 0; }
						10% { opacity: 1; }
						90% { opacity: 1; }
						100% { transform: translate(${Math.random() * 100 - 50}vw, ${Math.random() * 100 - 50}vh) rotate(360deg); opacity: 0; }
					}
				</style>
			`);
		}
		
		// Only create particles on larger screens
		if (window.innerWidth > 768) {
			createParticles();
		}
		
		// Auto-lock timer warning
		<?php if (isset($_SESSION['pin_attempts']) && $_SESSION['pin_attempts'] >= 2): ?>
			let warningTimer = 30;
			const warningInterval = setInterval(() => {
				if (warningTimer <= 0) {
					clearInterval(warningInterval);
					Swal.fire({
						icon: 'warning',
						title: 'Security Lockout',
						text: 'Too many failed attempts. Redirecting to login...',
						confirmButtonColor: '#ffc107',
						background: 'rgba(15, 12, 41, 0.9)',
						color: 'white'
					}).then(() => {
						window.location.href = 'login.php';
					});
				}
				warningTimer--;
			}, 1000);
		<?php endif; ?>
		
		// Initialize gauges on desktop
		if (window.innerWidth >= 768) {
			initializeGauges();
		}
		
		function initializeGauges() {
			const gaugesContainer = $('.gauges-section');
			
			// Create gauge containers
			const gauge1 = $(`
				<div class="speedometer-card">
					<div class="gauge-title">Users Online</div>
					<div class="gauge-container" id="gaugeUsers"></div>
					<div class="gauge-value"><?php echo rand(100, 500); ?></div>
				</div>
			`);
			
			const gauge2 = $(`
				<div class="speedometer-card">
					<div class="gauge-title">Success Rate</div>
					<div class="gauge-container" id="gaugeSuccess"></div>
					<div class="gauge-value"><?php echo rand(85, 98); ?>%</div>
				</div>
			`);
			
			gaugesContainer.append(gauge1, gauge2);
			
			// Initialize ApexCharts gauges
			setTimeout(() => {
				if (typeof ApexCharts !== 'undefined') {
					// Users Gauge
					new ApexCharts(document.querySelector("#gaugeUsers"), {
						series: [<?php echo rand(60, 90); ?>],
						chart: { type: 'radialBar', height: 100 },
						plotOptions: {
							radialBar: {
								hollow: { size: '70%' },
								track: { background: 'rgba(255,255,255,0.1)' },
								dataLabels: { show: false }
							}
						},
						fill: {
							type: 'gradient',
							gradient: {
								shade: 'dark',
								type: 'horizontal',
								shadeIntensity: 0.5,
								gradientToColors: ['#667eea'],
								stops: [0, 100]
							}
						},
						stroke: { lineCap: 'round' }
					}).render();
					
					// Success Gauge
					new ApexCharts(document.querySelector("#gaugeSuccess"), {
						series: [<?php echo rand(85, 98); ?>],
						chart: { type: 'radialBar', height: 100 },
						plotOptions: {
							radialBar: {
								hollow: { size: '70%' },
								track: { background: 'rgba(255,255,255,0.1)' },
								dataLabels: { show: false }
							}
						},
						fill: {
							type: 'gradient',
							gradient: {
								shade: 'dark',
								type: 'horizontal',
								shadeIntensity: 0.5,
								gradientToColors: ['#43e97b'],
								stops: [0, 100]
							}
						},
						stroke: { lineCap: 'round' }
					}).render();
				}
			}, 100);
		}
		
		// Handle window resize
		let resizeTimer;
		$(window).resize(function() {
			clearTimeout(resizeTimer);
			resizeTimer = setTimeout(function() {
				// Update gauges visibility
				if (window.innerWidth >= 768 && $('.gauges-section').children().length === 0) {
					initializeGauges();
				} else if (window.innerWidth < 768) {
					$('.gauges-section').empty();
				}
			}, 250);
		});
	});
	</script>
	
</body>
</html>