<?php
if (session_status() !== PHP_SESSION_ACTIVE) {
  session_start();
}

/**
 * =========================
 * REQUIRED ACCESS CODE (Server-side)
 * =========================
 */
define('ADMIN_REQUIRED_CODE', 'AVKADMINSTOP15123354');

$admin_code_error = '';
$username_error = '';
$password_error = '';
$block_login = false;

// فحص POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // استلام البيانات
  $admin_code = isset($_POST['admin_code']) ? trim((string)$_POST['admin_code']) : '';
  $username = isset($_POST['username']) ? trim((string)$_POST['username']) : '';
  $password = isset($_POST['password']) ? trim((string)$_POST['password']) : '';

  // ✅ فحص إلزامي للكود - يجب أن يكون موجود
  if (empty($admin_code)) {
    http_response_code(403);
    $admin_code_error = '⚠️ ACCESS CODE IS REQUIRED';
    $block_login = true;
  }
  // ✅ فحص صحة الكود - يجب أن يكون مطابق تماماً
  elseif (!hash_equals(ADMIN_REQUIRED_CODE, $admin_code)) {
    http_response_code(403);
    $admin_code_error = '❌ INVALID ACCESS CODE - ACCESS DENIED';
    $block_login = true;
  }

  // إذا الكود صحيح، نكمل فحص باقي البيانات
  if (!$block_login) {
    // فحص اليوزر والباسورد (ضع الكود الأصلي هنا)
    if (empty($username)) {
      $username_error = 'Username is required';
      $block_login = true;
    }
    if (empty($password)) {
      $password_error = 'Password is required';
      $block_login = true;
    }
    
    // هنا ضع كود التحقق من قاعدة البيانات الخاص بك
    // مثال:
    /*
    if (!$block_login) {
      // كود فحص DB
      $db_check = check_admin_credentials($username, $password);
      if (!$db_check) {
        $admin_code_error = 'Invalid username or password';
        $block_login = true;
      } else {
        // تسجيل دخول ناجح
        $_SESSION['admin_logged_in'] = true;
        header('Location: dashboard.php');
        exit;
      }
    }
    */
  }
}

/**
 * لو فيه أي خطأ: نعرض صفحة اللوجين مع الخطأ
 */
?>
<!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">
    <title><?= isset($settings["site_name"]) ? htmlspecialchars($settings["site_name"]) : "VILGAX PANEL" ?> - Admin Portal</title>
    <link rel="icon" type="image/x-icon" href="<?= isset($settings["favicon"]) ? htmlspecialchars($settings["favicon"]) : "" ?>">
    
    <!-- Google Fonts & Font Awesome -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@400;500;600;700;900&family=Rajdhani:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

<style>
    :root {
        --primary-color: #6366f1;
        --secondary-color: #8b5cf6;
        --accent-color: #06b6d4;
        --dark-bg: #0a0a0f;
        --card-bg: #121218;
        --card-border: rgba(99, 102, 241, 0.3);
        --text-primary: #e0e7ff;
        --text-secondary: #a5b4fc;
        --glow-color: #6366f1;
    }
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body {
        font-family: 'Rajdhani', sans-serif;
        background: var(--dark-bg);
        min-height: 100vh;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 1rem;
        overflow: hidden;
        position: relative;
    }
    body::before {
        content: '';
        position: fixed;
        top: 0; left: 0;
        width: 100%; height: 100%;
        background: 
            radial-gradient(ellipse at 20% 30%, rgba(99, 102, 241, 0.15) 0%, transparent 50%),
            radial-gradient(ellipse at 80% 70%, rgba(139, 92, 246, 0.15) 0%, transparent 50%),
            radial-gradient(ellipse at 50% 50%, rgba(6, 182, 212, 0.1) 0%, transparent 50%);
        animation: backgroundPulse 8s ease-in-out infinite;
        z-index: 0;
    }
    @keyframes backgroundPulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.7; } }

    .grid-background {
        position: fixed; top: 0; left: 0;
        width: 100%; height: 100%;
        background-image: 
            linear-gradient(rgba(99, 102, 241, 0.1) 1px, transparent 1px),
            linear-gradient(90deg, rgba(99, 102, 241, 0.1) 1px, transparent 1px);
        background-size: 50px 50px;
        animation: gridMove 20s linear infinite;
        z-index: 0;
    }
    @keyframes gridMove { 0% { transform: translate(0, 0); } 100% { transform: translate(50px, 50px); } }

    .particles { position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 1; pointer-events: none; }
    .particle { position: absolute; width: 2px; height: 2px; background: var(--glow-color); border-radius: 50%; box-shadow: 0 0 10px var(--glow-color); animation: float 15s infinite; }
    @keyframes float { 0%, 100% { transform: translateY(0) translateX(0); opacity: 0; } 10% { opacity: 1; } 90% { opacity: 1; } 100% { transform: translateY(-100vh) translateX(50px); opacity: 0; } }

    .login-container { width: 100%; max-width: 550px; position: relative; z-index: 10; animation: fadeInScale 0.8s cubic-bezier(0.175, 0.885, 0.32, 1.275); }
    @keyframes fadeInScale { from { opacity: 0; transform: scale(0.8) translateY(30px); } to { opacity: 1; transform: scale(1) translateY(0); } }

    .login-card {
        background: var(--card-bg);
        border-radius: 24px;
        border: 2px solid var(--card-border);
        box-shadow: 0 0 60px rgba(99, 102, 241, 0.3), inset 0 0 60px rgba(99, 102, 241, 0.05);
        overflow: hidden;
        position: relative;
    }
    .login-card::before {
        content: '';
        position: absolute;
        top: -2px; left: -2px; right: -2px; bottom: -2px;
        background: linear-gradient(45deg, var(--primary-color), var(--secondary-color), var(--accent-color), var(--primary-color));
        background-size: 300% 300%;
        border-radius: 24px;
        z-index: -1;
        animation: borderGlow 4s ease infinite;
        filter: blur(8px);
    }
    @keyframes borderGlow { 0%, 100% { background-position: 0% 50%; } 50% { background-position: 100% 50%; } }

    .login-card::after {
        content: '';
        position: absolute; top: 0; left: 0; right: 0; bottom: 0;
        border-radius: 24px;
        background: 
            radial-gradient(circle at 20% 80%, rgba(6, 182, 212, 0.4) 0%, transparent 25%),
            radial-gradient(circle at 80% 20%, rgba(139, 92, 246, 0.4) 0%, transparent 25%),
            radial-gradient(circle at 40% 40%, rgba(99, 102, 241, 0.3) 0%, transparent 30%);
        animation: fireEffect 3s ease-in-out infinite;
        z-index: -1;
        filter: blur(20px);
    }
    @keyframes fireEffect {
        0%, 100% { opacity: 0.5; transform: scale(1); }
        33% { opacity: 0.8; transform: scale(1.02) rotate(1deg); }
        66% { opacity: 0.6; transform: scale(0.98) rotate(-1deg); }
    }

    .card-header {
        background: linear-gradient(135deg, rgba(99, 102, 241, 0.2) 0%, rgba(139, 92, 246, 0.2) 100%);
        padding: 3rem 2rem 2rem;
        text-align: center;
        position: relative;
        overflow: hidden;
    }

    .card-header::before {
        content: '';
        position: absolute;
        top: -50%; left: -50%;
        width: 200%; height: 200%;
        background: radial-gradient(circle, rgba(99, 102, 241, 0.1) 0%, transparent 70%);
        animation: electricPulse 3s ease-in-out infinite;
    }
    @keyframes electricPulse {
        0%, 100% { transform: scale(1) rotate(0deg); opacity: 1; }
        50% { transform: scale(1.2) rotate(180deg); opacity: 0.5; }
    }

    .lightning { position: absolute; width: 100%; height: 100%; top: 0; left: 0; pointer-events: none; z-index: 5; }
    .bolt {
        position: absolute; width: 2px; height: 100%;
        background: linear-gradient(to bottom, transparent 0%, var(--accent-color) 30%, white 50%, var(--accent-color) 70%, transparent 100%);
        box-shadow: 0 0 10px var(--accent-color), 0 0 20px var(--accent-color), 0 0 30px var(--accent-color);
        opacity: 0;
        animation: lightning 3s infinite;
        filter: blur(1px);
    }
    @keyframes lightning {
        0%, 90%, 100% { opacity: 0; transform: scaleY(0); }
        92% { opacity: 1; transform: scaleY(1); }
        94% { opacity: 0; transform: scaleY(0.8); }
        96% { opacity: 0.8; transform: scaleY(1); }
        98% { opacity: 0; }
    }

    .energy-ring {
        position: absolute;
        width: 300px; height: 300px;
        border: 3px solid transparent;
        border-top-color: var(--accent-color);
        border-right-color: var(--primary-color);
        border-radius: 50%;
        opacity: 0.3;
        animation: energySpin 4s linear infinite;
        box-shadow: 0 0 20px var(--accent-color), inset 0 0 20px var(--primary-color);
    }
    @keyframes energySpin {
        0% { transform: rotate(0deg) scale(1); opacity: 0.3; }
        50% { transform: rotate(180deg) scale(1.1); opacity: 0.6; }
        100% { transform: rotate(360deg) scale(1); opacity: 0.3; }
    }

    .pulse-wave {
        position: absolute;
        width: 100%; height: 100%;
        border: 2px solid var(--primary-color);
        border-radius: 24px;
        opacity: 0;
        animation: pulseExpand 2s ease-out infinite;
    }
    @keyframes pulseExpand {
        0% { transform: scale(0.95); opacity: 0; }
        50% { opacity: 0.5; }
        100% { transform: scale(1.05); opacity: 0; }
    }

    .brand-logo { position: relative; z-index: 2; }
    .brand-logo a {
        color: var(--text-primary);
        font-family: 'Orbitron', sans-serif;
        font-size: 3rem;
        font-weight: 900;
        text-decoration: none;
        text-transform: uppercase;
        letter-spacing: 4px;
        display: inline-block;
        text-shadow: 0 0 20px var(--glow-color), 0 0 40px var(--glow-color), 0 0 60px var(--glow-color);
        animation: logoGlow 2s ease-in-out infinite;
    }
    @keyframes logoGlow {
        0%, 100% { text-shadow: 0 0 20px var(--glow-color), 0 0 40px var(--glow-color), 0 0 60px var(--glow-color); }
        50% { text-shadow: 0 0 30px var(--glow-color), 0 0 60px var(--glow-color), 0 0 90px var(--glow-color), 0 0 120px var(--secondary-color); }
    }

    .card-title {
        font-family: 'Orbitron', sans-serif;
        font-size: 1.8rem;
        font-weight: 700;
        margin: 1.5rem 0 0.5rem;
        color: var(--text-primary);
        letter-spacing: 2px;
        position: relative;
        z-index: 2;
    }
    .card-subtitle {
        font-size: 1.1rem;
        color: var(--text-secondary);
        font-weight: 500;
        letter-spacing: 1px;
        position: relative;
        z-index: 2;
    }

    .card-body { padding: 2.5rem; }

    .form-group { margin-bottom: 1.2rem; position: relative; }
    .form-group label {
        display: block;
        margin-bottom: 0.8rem;
        font-weight: 600;
        color: var(--text-primary);
        font-size: 1.1rem;
        letter-spacing: 1px;
        text-transform: uppercase;
    }

    .input-wrapper { position: relative; }
    .form-control {
        width: 100%;
        height: 58px;
        padding: 0.75rem 3.5rem;
        background: rgba(18, 18, 24, 0.8);
        border: 2px solid rgba(99, 102, 241, 0.3);
        border-radius: 12px;
        font-size: 1.1rem;
        font-weight: 600;
        color: var(--text-primary);
        transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
        font-family: 'Rajdhani', sans-serif;
    }
    .form-control::placeholder { color: rgba(165, 180, 252, 0.4); }
    .form-control:focus {
        border-color: var(--primary-color);
        background: rgba(18, 18, 24, 1);
        box-shadow: 0 0 20px rgba(99, 102, 241, 0.4), inset 0 0 20px rgba(99, 102, 241, 0.1);
        outline: none;
        transform: translateY(-2px);
    }

    .input-icon {
        position: absolute;
        left: 1.2rem;
        top: 50%;
        transform: translateY(-50%);
        color: var(--primary-color);
        font-size: 1.2rem;
        transition: all 0.3s;
    }

    .password-toggle {
        position: absolute;
        right: 1.2rem;
        top: 50%;
        transform: translateY(-50%);
        color: var(--text-secondary);
        cursor: pointer;
        font-size: 1.2rem;
        transition: all 0.3s;
        z-index: 10;
    }

    .btn-login {
        background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
        color: white;
        border: none;
        padding: 1.3rem;
        border-radius: 12px;
        font-size: 1.3rem;
        font-weight: 700;
        cursor: pointer;
        transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 1rem;
        letter-spacing: 2px;
        text-transform: uppercase;
        font-family: 'Orbitron', sans-serif;
        position: relative;
        overflow: hidden;
        box-shadow: 0 10px 30px rgba(99, 102, 241, 0.3);
    }
    .btn-login:hover {
        transform: translateY(-2px);
        box-shadow: 0 15px 40px rgba(99, 102, 241, 0.5);
    }

    .divider { 
        margin: 1.4rem 0; 
        font-size: 1.1rem; 
        font-weight: 600; 
        text-align: center; 
        color: var(--text-secondary); 
        letter-spacing: 2px; 
    }

    .errbox {
        margin-bottom: 1.5rem;
        padding: 1rem 1.2rem;
        border-radius: 12px;
        background: rgba(255, 0, 0, 0.15);
        border: 2px solid rgba(255, 0, 0, 0.5);
        color: #ffcccc;
        font-weight: 700;
        text-align: center;
        letter-spacing: 1px;
        font-size: 1.05rem;
        animation: errorShake 0.5s ease;
        box-shadow: 0 0 20px rgba(255, 0, 0, 0.3);
    }
    @keyframes errorShake {
        0%, 100% { transform: translateX(0); }
        25% { transform: translateX(-10px); }
        75% { transform: translateX(10px); }
    }

    /* حماية من التلاعب بالكود */
    .form-control[name="admin_code"] {
        -webkit-user-modify: read-write !important;
    }

    @media (max-width: 480px) {
        .brand-logo a { font-size: 2rem; letter-spacing: 2px; }
        .card-title { font-size: 1.4rem; }
        .card-subtitle, .form-group label { font-size: 0.95rem; }
        .form-control { height: 52px; font-size: 1rem; }
        .btn-login { padding: 1.1rem; font-size: 1.1rem; }
        .card-header { padding: 2rem 1.5rem 1.5rem; }
        .card-body { padding: 2rem 1.5rem; }
    }
</style>
</head>
<body>

    <div class="grid-background"></div>
    <div class="particles" id="particles"></div>

    <div class="login-container">
        <div class="login-card" id="login-box">
            <div class="lightning" id="lightning"></div>
            <div class="pulse-wave"></div>
            <div class="pulse-wave" style="animation-delay: 1s;"></div>
            <div class="energy-ring" style="top: -100px; right: -100px;"></div>
            <div class="energy-ring" style="bottom: -100px; left: -100px; animation-delay: 2s; animation-duration: 5s;"></div>

            <div class="card-header">
                <div class="brand-logo">
                    <a href="https://TakePanel.com" target="_blank" rel="noopener">
                        VILGAX PANEL
                    </a>
                </div>
                <h3 class="card-title">QUANTUM ACCESS</h3>
                <p class="card-subtitle">Neural Authentication Required</p>
            </div>

            <div class="card-body">
                <form id="loginForm" action="" method="post" onsubmit="return validateForm()">

                    <?php if (!empty($admin_code_error)) : ?>
                        <div class="errbox">
                            <i class="fas fa-exclamation-triangle"></i> <?= htmlspecialchars($admin_code_error) ?>
                        </div>
                    <?php endif; ?>

                    <?php if (!empty($username_error)) : ?>
                        <div class="errbox">
                            <i class="fas fa-exclamation-triangle"></i> <?= htmlspecialchars($username_error) ?>
                        </div>
                    <?php endif; ?>

                    <?php if (!empty($password_error)) : ?>
                        <div class="errbox">
                            <i class="fas fa-exclamation-triangle"></i> <?= htmlspecialchars($password_error) ?>
                        </div>
                    <?php endif; ?>

                    <div class="form-group">
                        <label for="AdminUsers_login">USERNAME</label>
                        <div class="input-wrapper">
                            <input class="form-control" 
                                   name="username" 
                                   id="AdminUsers_login" 
                                   type="text" 
                                   maxlength="300" 
                                   required 
                                   placeholder="Enter identification code"
                                   autocomplete="username">
                            <i class="fas fa-user input-icon"></i>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="AdminUsers_passwd">PASSWORD</label>
                        <div class="input-wrapper">
                            <input class="form-control" 
                                   name="password" 
                                   id="AdminUsers_passwd" 
                                   type="password" 
                                   maxlength="300" 
                                   required 
                                   placeholder="Enter security key"
                                   autocomplete="current-password">
                            <i class="fas fa-lock input-icon"></i>
                            <i class="fas fa-eye password-toggle" id="togglePassword"></i>
                        </div>
                    </div>

                    <!-- ✅ Access Code (إجباري - محمي من التلاعب) -->
                    <div class="form-group" id="accessCodeGroup">
                        <label for="AdminUsers_code">
                            ACCESS CODE <span style="color: #ff6b6b;">*</span>
                        </label>
                        <div class="input-wrapper">
                            <input class="form-control" 
                                   name="admin_code" 
                                   id="AdminUsers_code" 
                                   type="text"
                                   maxlength="80" 
                                   required 
                                   placeholder="Enter master access code"
                                   autocomplete="off"
                                   data-validation="required">
                            <i class="fas fa-key input-icon"></i>
                        </div>
                    </div>

                    <button type="submit" class="btn-login" id="submitBtn">
                        <i class="fas fa-bolt"></i>
                        <span>INITIALIZE SEQUENCE</span>
                    </button>

                    <div class="divider">🔐 SECURE ACCESS REQUIRED</div>
                </form>
            </div>
        </div>
    </div>

    <script>
        // ✅ حماية من حذف حقل Access Code
        function validateForm() {
            const accessCodeInput = document.getElementById('AdminUsers_code');
            const accessCodeGroup = document.getElementById('accessCodeGroup');
            
            // فحص إذا الحقل موجود
            if (!accessCodeInput) {
                alert('❌ SECURITY VIOLATION DETECTED!\n\nAccess code field is required and cannot be removed.');
                return false;
            }
            
            // فحص إذا الحقل موجود في DOM
            if (!document.body.contains(accessCodeInput)) {
                alert('❌ TAMPERING DETECTED!\n\nForm structure has been modified.');
                return false;
            }
            
            // فحص القيمة
            const accessCode = accessCodeInput.value.trim();
            if (accessCode === '') {
                alert('⚠️ ACCESS CODE REQUIRED\n\nPlease enter the master access code.');
                accessCodeInput.focus();
                return false;
            }
            
            // فحص طول الكود
            if (accessCode.length < 10) {
                alert('⚠️ INVALID CODE FORMAT\n\nAccess code must be valid.');
                accessCodeInput.focus();
                return false;
            }
            
            return true;
        }

        // ✅ حماية إضافية: مراقبة التغييرات في DOM
        document.addEventListener('DOMContentLoaded', function() {
            const form = document.getElementById('loginForm');
            const accessCodeGroup = document.getElementById('accessCodeGroup');
            
            // مراقبة حذف العنصر
            const observer = new MutationObserver(function(mutations) {
                mutations.forEach(function(mutation) {
                    if (mutation.type === 'childList') {
                        const accessCodeInput = document.getElementById('AdminUsers_code');
                        if (!accessCodeInput || !document.body.contains(accessCodeInput)) {
                            // إعادة تحميل الصفحة إذا تم حذف الحقل
                            alert('⚠️ SECURITY ALERT: Form tampering detected. Page will reload Fuck your mother Turkish son of bitch :D .');
                            location.reload();
                        }
                    }
                });
            });
            
            // بدء المراقبة
            if (form) {
                observer.observe(form, {
                    childList: true,
                    subtree: true
                });
            }

            // Toggle Password Visibility
            const togglePassword = document.querySelector('#togglePassword');
            const password = document.querySelector('#AdminUsers_passwd');
            if (togglePassword) {
                togglePassword.addEventListener('click', function () {
                    const type = password.getAttribute('type') === 'password' ? 'text' : 'password';
                    password.setAttribute('type', type);
                    this.classList.toggle('fa-eye-slash');
                });
            }

            // Particles Animation
            const particlesContainer = document.getElementById('particles');
            const particleCount = 50;
            for (let i = 0; i < particleCount; i++) {
                const particle = document.createElement('div');
                particle.className = 'particle';
                particle.style.left = Math.random() * 100 + '%';
                particle.style.animationDelay = Math.random() * 15 + 's';
                particle.style.animationDuration = (Math.random() * 10 + 10) + 's';
                particlesContainer.appendChild(particle);
            }

            // Lightning Animation
            const lightningContainer = document.getElementById('lightning');
            const boltCount = 5;
            for (let i = 0; i < boltCount; i++) {
                const bolt = document.createElement('div');
                bolt.className = 'bolt';
                bolt.style.left = (i * 20 + 10) + '%';
                bolt.style.animationDelay = (Math.random() * 3) + 's';
                bolt.style.animationDuration = (Math.random() * 2 + 2) + 's';
                lightningContainer.appendChild(bolt);
            }

            // منع النسخ واللصق في حقل Access Code
            const accessCodeInput = document.getElementById('AdminUsers_code');
            if (accessCodeInput) {
                // السماح بالنسخ واللصق ولكن مع التحقق
                accessCodeInput.addEventListener('paste', function(e) {
                    // يمكن السماح بالصق ولكن سيتم التحقق من الكود في السيرفر
                });
            }
        });

        // ✅ منع إرسال النموذج باستخدام Console
        (function() {
            const originalSubmit = HTMLFormElement.prototype.submit;
            HTMLFormElement.prototype.submit = function() {
                if (this.id === 'loginForm') {
                    if (!validateForm()) {
                        return false;
                    }
                }
                originalSubmit.call(this);
            };
        })();
    </script>
</body>
</html>