<?php
session_start();
include '../config/database.php';
// Jika filter_status.php adalah file lama yang tidak terpakai, bisa Anda hapus baris include di bawah ini nantinya
include 'filter_status.php'; 

// --- 1. AMBIL DATA IDENTITAS SEKOLAH ---
$query_identitas = mysqli_query($koneksi, "SELECT * FROM tbl_identitas WHERE id=1");
$d_identitas     = mysqli_fetch_assoc($query_identitas);

// Path Logo & Favicon
$path_logo    = $base_url . "uploads/identitas/" . $d_identitas['logo_utama'];
$path_favicon = $base_url . "uploads/identitas/" . $d_identitas['favicon'];

// --- LOGIKA CEK SESSION ---
if (isset($_SESSION['id_siswa'])) {
    header("Location: index.php");
    exit();
}

$error = "";
$email_input = ""; 

// --- LOGIKA PROSES LOGIN ---
if (isset($_POST['btn_login'])) {
    
    // Verifikasi CSRF Token
    if (!isset($_POST['csrf_token']) || !verify_csrf_token($_POST['csrf_token'])) {
        $error = "Token keamanan tidak valid. Silakan muat ulang halaman.";
    } else {
        // Simpan email agar tidak hilang, tapi sanitasi dulu
        $email_input = htmlspecialchars($_POST['email']); 

    // 1. Validasi Captcha
    if ($_POST['captcha'] != $_SESSION['captcha_code']) {
        $error = "Kode Keamanan (Captcha) salah!";
    } else {
        
        // --- SECURITY UPGRADE: FILTER INPUT ---
        $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
        $pass  = mysqli_real_escape_string($koneksi, $_POST['password']);

        // --- SECURITY UPGRADE: PREPARED STATEMENT ---
        $stmt = mysqli_prepare($koneksi, "SELECT id, nama_siswa, email, password, status_verifikasi FROM tbl_ppdb WHERE email = ?");
        
        // Bind Parameter: 's' artinya string
        mysqli_stmt_bind_param($stmt, "s", $email);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);

        if ($data = mysqli_fetch_assoc($result)) {
            
            // 3. Cek Status Verifikasi Email
            if ($data['status_verifikasi'] == '0') {
                $error = "<strong>Akun Belum Aktif!</strong><br>Silakan cek email Anda untuk verifikasi akun sebelum login.";
            } 
            // 4. Cek Password (Verifikasi Hash)
            else if (password_verify($pass, $data['password'])) {
                
                // --- SECURITY UPGRADE: SESSION FIXATION PROTECTION ---
                session_regenerate_id(true);

                // LOGIN SUKSES
                $_SESSION['id_siswa']    = $data['id'];
                $_SESSION['nama_siswa']  = $data['nama_siswa'];
                $_SESSION['email_siswa'] = $data['email'];
                $_SESSION['status_login_siswa'] = true; // Flag tambahan biar aman
                
                header("Location: index.php");
                exit();

            } else {
                $error = "Password yang Anda masukkan salah.";
            }
        } else {
            $error = "Email tidak terdaftar dalam sistem kami.";
        }
        
        mysqli_stmt_close($stmt);
    }
}
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <base href="<?= htmlspecialchars($base_url ?? '') ?>spmb/">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <title>Login SPMB - <?= htmlspecialchars($d_identitas['nama_website']) ?></title>
    
    <link rel="shortcut icon" href="<?= htmlspecialchars($path_favicon) ?>" type="image/x-icon">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        /* AMBIL WARNA DARI DATABASE */
        :root {
            --primary-bg: <?= !empty($d_identitas['warna_utama']) ? $d_identitas['warna_utama'] : '#166534' ?>;
            --navbar-bg: <?= !empty($d_identitas['warna_navbar']) ? $d_identitas['warna_navbar'] : '#14532d' ?>;
            --accent-color: <?= !empty($d_identitas['warna_sekunder']) ? $d_identitas['warna_sekunder'] : '#facc15' ?>;
        }

        body { 
            background-color: #f0f2f5; 
            display: flex;
            flex-direction: column;
            min-height: 100vh;
        }
        .main-content {
            flex: 1;
            display: flex;
            align-items: center; 
            justify-content: center;
            padding: 40px 15px;
        }
        .login-card { 
            width: 100%;
            max-width: 420px; 
            border-radius: 12px; 
            border: none;
        }
        .card-header { 
            background: linear-gradient(135deg, var(--primary-bg), var(--navbar-bg)) !important; 
            color: white; 
            border-radius: 12px 12px 0 0 !important;
            padding: 25px 20px;
        }
        .logo-login {
            width: 60px;
            height: 60px;
            background: white;
            border-radius: 50%;
            padding: 5px;
            object-fit: contain;
            margin-bottom: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        .captcha-box { display: flex; align-items: center; gap: 10px; }
        
        /* OVERRIDE BOOTSTRAP CLASSES */
        .btn-success { background-color: var(--primary-bg) !important; border-color: var(--primary-bg) !important; }
        .btn-success:hover { filter: brightness(110%); }
        .btn-outline-success { color: var(--primary-bg) !important; border-color: var(--primary-bg) !important; }
        .btn-outline-success:hover { background-color: var(--primary-bg) !important; color: white !important; }
        .text-success { color: var(--primary-bg) !important; }

        footer { background-color: #fff; padding: 15px 0; border-top: 1px solid #dee2e6; text-align: center; font-size: 0.9rem; color: #6c757d; }
    </style>
</head>
<body>

    <div class="main-content">
        <div class="card shadow-lg login-card">
            <div class="card-header text-center">
                <img src="<?= htmlspecialchars($path_logo) ?>" alt="Logo" class="logo-login">
                <h5 class="mb-0 fw-bold">Login Calon Siswa</h5>
                <small><?= htmlspecialchars($d_identitas['nama_website']) ?></small>
            </div>
            
            <div class="card-body p-4">
                
                <?php if($error): ?>
                    <div class="alert alert-danger alert-dismissible fade show text-sm shadow-sm" role="alert">
                        <i class="fas fa-exclamation-circle me-1"></i> <?= $error ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <form method="POST" action="">
                    <input type="hidden" name="csrf_token" value="<?= generate_csrf_token() ?>">
                    <div class="mb-3">
                        <label class="form-label text-muted small fw-bold">EMAIL TERDAFTAR</label>
                        <div class="input-group shadow-sm">
                            <span class="input-group-text bg-white border-end-0"><i class="fas fa-envelope text-secondary"></i></span>
                            <input type="email" name="email" class="form-control border-start-0 ps-0" placeholder="nama@email.com" required value="<?= htmlspecialchars($email_input) ?>">
                        </div>
                    </div>

                    <div class="mb-3">
                        <div class="d-flex justify-content-between">
                            <label class="form-label text-muted small fw-bold">PASSWORD LOGIN</label>
                        </div>
                        <div class="input-group shadow-sm">
                            <span class="input-group-text bg-white border-end-0"><i class="fas fa-lock text-secondary"></i></span>
                            <input type="password" name="password" id="passInput" class="form-control border-start-0 ps-0" placeholder="******" required>
                            <button class="btn btn-outline-secondary bg-white border-start-0" type="button" id="togglePass">
                                <i class="fas fa-eye text-secondary" id="iconEye"></i>
                            </button>
                        </div>
                    </div>

                    <div class="mb-4">
                        <label class="form-label text-muted small fw-bold">KODE KEAMANAN</label>
                        <div class="captcha-box">
                            <img src="captcha.php" alt="Captcha" class="rounded shadow-sm border border-gray-200">
                            <input type="text" name="captcha" class="form-control shadow-sm" placeholder="Ketik Kode" required autocomplete="off">
                        </div>
                    </div>

                    <button type="submit" name="btn_login" class="btn btn-success w-100 py-2.5 fw-bold shadow">
                        MASUK APLIKASI
                    </button>
                </form>
            </div>
            
            <div class="card-footer text-center bg-white py-3 border-0 rounded-bottom">
                <small class="text-muted">Belum punya akun?</small><br>
                <a href="register" class="btn btn-outline-success btn-sm mt-2 px-4 rounded-pill fw-bold">Buat Akun Baru</a><br>
                <a href="lupa_password" class="pt-2"><small>Reset Ulang Password</small></a>
                <div class="mt-3">
                    <a href="../index.php" class="text-secondary small text-decoration-none hover-opacity">
                        <i class="fas fa-arrow-left"></i> Kembali ke Beranda
                    </a>
                </div>
            </div>
        </div>
    </div>

    <footer>
        <div class="container">
            <strong>Copyright &copy; <?= date('Y') ?> <a href="#" class="text-success text-decoration-none"><?= htmlspecialchars($d_identitas['nama_website']) ?></a>.</strong>
            <br>
            <small>Sistem Manajemen PPDB Terpadu - Powered by <strong><a href="https://gobook.ptgbk.id" style="text-decoration:none">Gobook Softindo</a></strong></small>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        const togglePass = document.querySelector('#togglePass');
        const password = document.querySelector('#passInput');
        const icon = document.querySelector('#iconEye');
        
        togglePass.addEventListener('click', function (e) {
            const type = password.getAttribute('type') === 'password' ? 'text' : 'password';
            password.setAttribute('type', type);
            icon.classList.toggle('fa-eye');
            icon.classList.toggle('fa-eye-slash');
        });
    </script>

</body>
</html>