<?php
// login.php
session_start();
require 'config/database.php';

$nama_sekolah_tampil = 'MA Darul Ulum Palangka Raya'; // Default
$logo_file = null; // Default

try {
    // Ambil data pengaturan sekolah dari db_pilkasim
    // Menggunakan key dari file Anda: 'nama_sekolah' dan 'logo_aplikasi'
    $stmt_pengaturan = $pdo->query("SELECT setting_key, setting_value FROM pengaturan WHERE setting_key IN ('nama_sekolah', 'logo_aplikasi')");
    $pengaturan_db = $stmt_pengaturan->fetchAll(PDO::FETCH_KEY_PAIR);
    
    $nama_sekolah_tampil = htmlspecialchars($pengaturan_db['nama_sekolah'] ?? 'MA Darul Ulum');
    $logo_file = $pengaturan_db['logo_aplikasi'] ?? null; 

} catch (PDOException $e) {
    // Jika gagal, biarkan default, jangan tampilkan error di login
    error_log("Gagal mengambil data pengaturan login: " . $e->getMessage());
}

// Cek jika user sudah login
if (isset($_SESSION['user_id']) && isset($_SESSION['role'])) {
    if ($_SESSION['role'] === 'admin') {
        header("Location: admin/dashboard.php");
        exit();
    }
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';

    if (empty($username) || empty($password)) {
        $error = 'Username dan password tidak boleh kosong!';
    } else {
        try {
            $stmt = $pdo->prepare("SELECT id, username, password, nama_lengkap, role FROM users WHERE username = ?");
            $stmt->execute([$username]);
            $user = $stmt->fetch();

            if ($user && password_verify($password, $user['password'])) {
                // Login berhasil
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['nama_lengkap'] = $user['nama_lengkap'];
                $_SESSION['role'] = $user['role'];
                
                if ($user['role'] === 'admin') {
                    header("Location: admin/dashboard.php");
                } else {
                    $error = 'Halaman ini hanya untuk Admin.';
                }
                exit();
            } else {
                $error = 'Username atau password salah!';
            }
        } catch (PDOException $e) {
            $error = "Terjadi masalah dengan koneksi database.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login Admin - PILKASIM</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/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: #4A8BDF; /* Biru Tua */
            --dark: #2c5b9c;    /* Biru Lebih Tua (untuk hover) */
            --accent: #A0006D; /* Terong */
            --bg-light: #EFFAFD; /* Biru Pucat */
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: var(--bg-light);
            background-image: radial-gradient(circle, #ffffff 0%, var(--bg-light) 100%);
            padding: 1rem;
        }

        .login-card {
            max-width: 420px;
            width: 100%;
            background: white;
            border: none;
            border-radius: 1rem; /* 16px */
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
            overflow: hidden; /* Penting untuk border-radius */
        }

        .login-header {
            background-color: var(--primary);
            color: white;
            padding: 2rem;
            text-align: center;
        }

        .logo-circle {
            width: 70px;
            height: 70px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 1rem;
            font-size: 2.5rem;
            color: white;
        }
        .logo-circle img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 50%;
        }

        .login-header h3 {
            margin: 0;
            font-weight: 700;
        }
        .login-header p {
            margin: 0.25rem 0 0;
            opacity: 0.9;
            font-size: 0.9rem;
        }

        .login-body {
            padding: 2rem;
        }
        
        .form-label {
            font-weight: 500;
            font-size: 0.875rem;
        }

        .input-group .form-control {
            border-left: 0;
            padding-left: 0.5rem;
        }
        .input-group .form-control:focus {
            box-shadow: none;
            border-color: var(--primary);
        }
        
        .input-group .input-group-text {
            background-color: #f8f9fa;
            border-right: 0;
            color: var(--primary);
        }
        
        .input-group {
            transition: all 0.2s ease-in-out;
        }
        .input-group:focus-within {
             box-shadow: 0 0 0 0.25rem rgba(74, 139, 223, 0.25);
        }

        .btn-login {
            display: block;
            width: 100%;
            padding: 0.75rem;
            background-color: var(--primary);
            color: white;
            border: none;
            border-radius: 0.5rem;
            font-weight: 600;
            font-size: 1rem;
            transition: all 0.2s ease;
            margin-top: 1.5rem;
        }
        .btn-login:hover {
            background-color: var(--dark);
        }
        .btn-login:disabled {
            opacity: 0.7;
            cursor: wait;
        }
        
        .login-footer {
            text-align: center;
            padding: 1.5rem;
            background: #f8f9fa;
            font-size: 0.8rem;
            color: #6c757d;
        }
    </style>
</head>
<body>
    <div class="login-card">
        <div class="login-header">
            <div class="logo-circle">
                <?php if ($logo_file && file_exists('assets/img/logo/' . $logo_file)): ?>
                    <img src="assets/img/logo/<?= htmlspecialchars($logo_file) ?>" alt="Logo">
                <?php else: ?>
                    <i class="bi bi-person-check-fill"></i>
                <?php endif; ?>
            </div>
            <h3>ADMIN PILKASIM</h3>
            <p><b><?= $nama_sekolah_tampil ?></b></p>
        </div>

        <div class="login-body">
            <?php if ($error): ?>
                <div class="alert alert-danger d-flex align-items-center" role="alert">
                    <i class="bi bi-exclamation-triangle-fill me-2"></i>
                    <div>
                        <?= htmlspecialchars($error) ?>
                    </div>
                </div>
            <?php endif; ?>

            <form action="login.php" method="post" id="loginForm">
                <div class="mb-3">
                     <label for="username" class="form-label">Username</label>
                     <div class="input-group">
                        <span class="input-group-text"><i class="bi bi-person"></i></span>
                        <input type="text" class="form-control" id="username" name="username" required>
                     </div>
                </div>
                 <div class="mb-3">
                    <label for="password" class="form-label">Password</label>
                     <div class="input-group">
                        <span class="input-group-text"><i class="bi bi-shield-lock"></i></span>
                        <input type="password" class="form-control" id="password" name="password" required>
                     </div>
                </div>
                <button type="submit" class="btn-login" id="loginBtn">
                    <span class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
                    <span class="login-text">Login</span>
                </button>
            </form>
        </div>

        <div class="login-footer">
            <p class="mb-0">© <?= date('Y'); ?> PILKASIM. All rights reserved.</p>
        </div>
    </div>

    <script>
        document.getElementById('loginForm')?.addEventListener('submit', function() {
            const btn = document.getElementById('loginBtn');
            const spinner = btn.querySelector('.spinner-border');
            const text = btn.querySelector('.login-text');
            
            btn.disabled = true;
            spinner.classList.remove('d-none');
            text.textContent = 'Memproses...';
        });
        
        // Perbaikan: Fokus ke 'username', bukan 'nis_token'
        document.getElementById('username')?.focus();
    </script>
</body>
</html>