<?php
require_once __DIR__ . '/config.php';
if (isAdminLoggedIn()) {
    header('Location: index.php');
    exit;
}
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    if (!$username || !$password) {
        $error = 'Please enter username and password.';
    } else {
        $pdo = getDB();
        $stmt = $pdo->prepare("SELECT id, username, password FROM admin_users WHERE username = ? LIMIT 1");
        $stmt->execute([$username]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($user && password_verify($password, $user['password'])) {
            $_SESSION['admin_id'] = $user['id'];
            $_SESSION['admin_username'] = $user['username'];
            header('Location: index.php');
            exit;
        }
        $error = 'Invalid username or password.';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Login</title>
    <link rel="stylesheet" href="<?php echo ADMIN_SITE_ROOT; ?>/assets/css/style.css">
    <link rel="stylesheet" href="<?php echo ADMIN_SITE_ROOT; ?>/assets/css/admin.css?v=4">
    <style>
        .login-box { max-width: 380px; margin: 80px auto; padding: 32px; border: 1px solid #e2e8f0; border-radius: 16px; background: #fff; box-shadow: 0 8px 32px rgba(30,58,95,0.1); }
        .login-box h1 { margin-bottom: 20px; }
        .login-box label { display: block; margin-top: 10px; }
        .login-box input { width: 100%; padding: 8px; margin-top: 4px; box-sizing: border-box; }
        .login-box button { margin-top: 16px; padding: 10px 20px; cursor: pointer; }
        .admin-error { color: #c00; margin-top: 10px; }
    </style>
</head>
<body>
<div class="login-box">
    <h1>Admin Login</h1>
    <?php if ($error): ?>
    <p class="admin-error"><?php echo htmlspecialchars($error); ?></p>
    <?php endif; ?>
    <form method="post">
        <label>Username</label>
        <input type="text" name="username" required autofocus>
        <label>Password</label>
        <input type="password" name="password" required>
        <button type="submit">Login</button>
    </form>
</div>
</body>
</html>
