<?php
declare(strict_types=1);

require_once __DIR__ . '/api/db_pdo.php';
require_once __DIR__ . '/api/auth.php';

start_admin_session();
ensure_admin_table($pdo);

if (is_admin_logged_in()) {
    header('Location: index.php');
    exit;
}

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

$error = '';

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

    if (!hash_equals((string)$_SESSION['csrf_token'], $token)) {
        $error = 'Sesi form tidak valid. Muat ulang halaman lalu coba lagi.';
    } elseif ($username === '' || $password === '') {
        $error = 'Username dan password wajib diisi.';
    } else {
        $stmt = $pdo->prepare("SELECT * FROM admins WHERE username = ? AND is_active = 1 LIMIT 1");
        $stmt->execute([$username]);
        $admin = $stmt->fetch();

        if ($admin && password_verify($password, $admin['password_hash'])) {
            session_regenerate_id(true);
            $_SESSION['admin_id'] = (int)$admin['id'];
            $_SESSION['admin_username'] = $admin['username'];
            $_SESSION['admin_name'] = $admin['nama'];
            unset($_SESSION['csrf_token']);

            header('Location: index.php');
            exit;
        }

        $error = 'Username atau password salah.';
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login Admin - WebGIS Peduli</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@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">
    <link rel="stylesheet" href="assets/css/login.css">
</head>
<body>
    <main class="login-page">
        <section class="login-panel">
            <div class="brand-mark">
                <i class="fas fa-map-location-dot"></i>
            </div>
            <p class="eyebrow">Admin Area</p>
            <h1>Masuk ke WebGIS Peduli</h1>
            <p class="subtitle">Gunakan akun admin untuk mengelola data peta, warga, dan rumah ibadah.</p>

            <?php if ($error !== ''): ?>
                <div class="alert-error">
                    <i class="fas fa-circle-exclamation"></i>
                    <span><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></span>
                </div>
            <?php endif; ?>

            <form method="POST" class="login-form" autocomplete="off">
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars((string)$_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8') ?>">

                <label class="input-group">
                    <span>Username</span>
                    <div class="input-shell">
                        <i class="fas fa-user"></i>
                        <input type="text" name="username" placeholder="admin" required autofocus>
                    </div>
                </label>

                <label class="input-group">
                    <span>Password</span>
                    <div class="input-shell">
                        <i class="fas fa-lock"></i>
                        <input type="password" name="password" placeholder="Masukkan password" required>
                    </div>
                </label>

                <button type="submit" class="btn-login">
                    <span>Masuk</span>
                    <i class="fas fa-arrow-right"></i>
                </button>
            </form>

            <p class="login-hint">Akun awal: <strong>admin</strong> / <strong>admin123</strong></p>
        </section>
    </main>
</body>
</html>
