<?php
/**
 * login_page.php - Premium Login Interface
 * Fitur: Login via Email/Username, Toggle Password, Maintenance Check
 */
session_set_cookie_params(['lifetime' => 31536000, 'path' => '/']);
ini_set('session.gc_maxlifetime', 31536000);
session_start();
include '../config/database.php';

// Ambil Konfigurasi Maintenance & Nama Aplikasi
$query_cfg = mysqli_query($conn, "SELECT maintenance_mode, nama_aplikasi, logo FROM settings WHERE id = 1");
$cfg = mysqli_fetch_assoc($query_cfg);
$app_name = $cfg['nama_aplikasi'] ?? 'SIEKA AI';
$app_logo = $cfg['logo'] ?? '';

if (isset($_POST['login'])) {
    // 1. Tangkap input 'identitas' (bisa berisi email atau username)
    // Gunakan ?? '' untuk mencegah error Undefined array key
    $identitas = mysqli_real_escape_string($conn, $_POST['identitas'] ?? '');
    $password  = $_POST['password'] ?? '';

    // 2. Cari user berdasarkan username ATAU email_guru
    $query = mysqli_query($conn, "SELECT * FROM users WHERE username = '$identitas' OR email_guru = '$identitas'");
    
    if (mysqli_num_rows($query) === 1) {
        $user = mysqli_fetch_assoc($query);
        
        // 3. Verifikasi Password
        if (password_verify($password, $user['password'])) {
            
            // CEK MAINTENANCE
            if ($cfg['maintenance_mode'] == 1 && $user['role'] !== 'admin') {
                header("Location: ../maintenance.php");
                exit;
            }

            // Set Session
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['role']    = $user['role'];
            
            // Karena kolom 'nama' sudah dihapus di DB, kita gunakan 'username' untuk sesi nama
            $_SESSION['nama']    = $user['username']; 

            // Set cookie Remember Me jika dicentang
            if (isset($_POST['remember'])) {
                $token = base64_encode($user['id'] . '||' . $user['username'] . '||' . $user['role']);
                setcookie('remember_me', $token, time() + (30 * 24 * 60 * 60), "/"); // 30 hari
            }

            // Redirect sesuai role
            if ($user['role'] === 'admin') {
                header("Location: ../admin/index.php");
            } else {
                header("Location: ../index.php");
            }
            exit;
        } else {
            $error = "Password yang Anda masukkan salah!";
        }
    } else {
        $error = "Email atau Username tidak ditemukan!";
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Login | <?= htmlspecialchars($app_name) ?></title>
    
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    
    <style>
        :root {
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --glass-bg: rgba(255, 255, 255, 0.9);
        }

        body { 
            background: #f1f5f9;
            background-image: 
                radial-gradient(at 0% 0%, rgba(102, 126, 234, 0.1) 0px, transparent 50%),
                radial-gradient(at 100% 100%, rgba(118, 75, 162, 0.1) 0px, transparent 50%);
            height: 100dvh; 
            display: flex; 
            align-items: center; 
            justify-content: center; 
            font-family: 'Plus Jakarta Sans', sans-serif;
            margin: 0;
            padding: 20px;
        }

        .login-card { 
            background: var(--glass-bg); 
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            padding: 40px; 
            border-radius: 35px; 
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.1); 
            width: 100%;
            max-width: 420px; 
            border: 1px solid rgba(255, 255, 255, 0.6); 
            animation: fadeIn 0.8s ease-out;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        @keyframes elegantBlink {
            0%, 100% { opacity: 1; color: #64748b; }
            50% { opacity: 0.7; color: #667eea; text-shadow: 0 0 8px rgba(102, 126, 234, 0.4); }
        }
        .blink-elegant {
            animation: elegantBlink 2.5s ease-in-out infinite;
        }

        .brand-icon {
            width: 70px;
            height: 70px;
            background: var(--primary-gradient);
            border-radius: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 20px;
            color: white;
            font-size: 35px;
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
        }

        h3 { color: #1e293b; font-weight: 800; letter-spacing: -0.5px; }
        
        .form-label { font-weight: 700; font-size: 0.8rem; color: #64748b; text-transform: uppercase; margin-bottom: 8px; }
        
        .form-control {
            border-radius: 15px;
            padding: 12px 18px;
            border: 1px solid #e2e8f0;
            background: white;
            font-size: 1rem;
            transition: all 0.3s ease;
        }

        .form-control:focus {
            box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
            border-color: #667eea;
        }

        /* Password Eye Toggle */
        .password-wrapper { position: relative; }
        .toggle-password {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            color: #94a3b8;
            font-size: 1.2rem;
            z-index: 10;
        }

        .btn-login {
            background: var(--primary-gradient);
            border: none;
            border-radius: 15px;
            padding: 14px;
            font-weight: 700;
            color: white;
            margin-top: 10px;
            transition: all 0.3s ease;
        }

        .btn-login:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
            opacity: 0.95;
        }

        .footer-dev {
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid rgba(0,0,0,0.05);
            text-align: center;
        }

        @media (max-width: 480px) {
            .login-card { padding: 30px 20px; border-radius: 25px; }
            h3 { font-size: 1.5rem; }
        }
    </style>
</head>
<body>

<div class="login-card">
    <div class="brand-icon" <?= !empty($app_logo) && file_exists('../' . $app_logo) ? 'style="background: transparent; box-shadow: none;"' : '' ?>>
        <?php if (!empty($app_logo) && file_exists('../' . $app_logo)): ?>
            <img src="../<?= $app_logo ?>" alt="Logo" style="max-width: 100%; max-height: 100%; border-radius: 20px; box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);">
        <?php else: ?>
            <i class="bi bi-robot"></i>
        <?php endif; ?>
    </div>
    
    <div class="text-center mb-4">
        <h3>Selamat Datang</h3>
        <p class="text-muted small">Masuk ke <b><?= htmlspecialchars($app_name) ?></b></p>
    </div>

    <?php if (isset($error)): ?>
        <div class="alert alert-danger border-0 rounded-3 small py-2 text-center mb-3"><?= $error ?></div>
    <?php endif; ?>

    <?php if (isset($_GET['pesan']) && $_GET['pesan'] == 'maintenance'): ?>
        <div class="alert alert-warning border-0 rounded-3 small py-2 text-center mb-3">Sistem sedang pemeliharaan!</div>
    <?php endif; ?>

    <form action="" method="POST">
        <div class="mb-3">
            <label class="form-label">Email atau Username</label>
            <input type="text" name="identitas" class="form-control" placeholder="Masukkan email atau username" required>
        </div>
        
        <div class="mb-4">
            <label class="form-label">Password</label>
            <div class="password-wrapper">
                <input type="password" name="password" id="password-field" class="form-control" placeholder="Masukkan password" required>
                <i class="bi bi-eye-slash toggle-password" id="togglePassword"></i>
            </div>
            
            <div class="d-flex justify-content-between align-items-center mt-2">
                <div class="form-check">
                    <input type="checkbox" class="form-check-input" id="remember" name="remember" checked>
                    <label class="form-check-label small fw-bold blink-elegant" for="remember">Ingat Saya</label>
                </div>
                <a href="forgot_password.php" class="text-decoration-none small text-primary fw-bold">Lupa Password?</a>
            </div>
        </div>
        
        <div class="d-grid">
            <button type="submit" name="login" class="btn btn-login shadow">MASUK SEKARANG</button>
        </div>
    </form>
    
    <div class="text-center mt-4">
        <p class="small text-muted">Belum punya akun? <a href="register_page.php" class="text-decoration-none fw-bold text-primary">Daftar Disini</a></p>
    </div>

    <div class="footer-dev">
        <div class="fw-bold text-dark small" style="opacity: 0.6;">
            &copy; <?= date('Y') ?> All Rights Reserved<br>
            Developed by <span class="text-primary">Sikawarsito, S.Kom</span>
        </div>
    </div>
</div>

<script>
    // Logika Mata Password
    const togglePassword = document.querySelector('#togglePassword');
    const password = document.querySelector('#password-field');

    togglePassword.addEventListener('click', function () {
        const type = password.getAttribute('type') === 'password' ? 'text' : 'password';
        password.setAttribute('type', type);
        this.classList.toggle('bi-eye');
        this.classList.toggle('bi-eye-slash');
    });
</script>

</body>
</html>