<?php
session_start();
include_once 'config/db.php';

// Handle login form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $admin_username = $_POST['username'];
    $admin_password = $_POST['password'];

    // Fetch admin credentials from the database
    $stmt = $pdo->prepare("SELECT * FROM admins WHERE username = :username");
    $stmt->execute([':username' => $admin_username]);
    $admin = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($admin) {
        if (password_verify($admin_password, $admin['password_hash'])) {
            // Login successful
            $_SESSION['admin_logged_in'] = true;
            $_SESSION['admin_username'] = $admin_username;
            header('Location: admin_dashboard.php');
            exit;
        } else {
            // Password does not match
            $error = "Invalid password.";
        }
    } else {
        // Username not found
        $error = "Invalid username.";
    }
}
?>

<!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>
    <script src="https://cdn.tailwindcss.com"></script> <!-- Tailwind CSS CDN -->
</head>
<body class="bg-gray-100 flex items-center justify-center min-h-screen">
    <div class="bg-white p-8 rounded-lg shadow-lg w-full sm:w-96">
        <h1 class="text-2xl font-semibold text-center text-gray-800 mb-6">Admin Login</h1>
        
        <?php if (isset($error)) : ?>
            <p class="text-red-500 text-center mb-4"><?= $error ?></p>
        <?php endif; ?>

        <form method="POST" action="" class="space-y-4">
            <div class="relative">
                <input type="text" name="username" class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:outline-none" placeholder="Username" required>
                <i class="fas fa-user absolute left-4 top-3 text-gray-500"></i>
            </div>
            <div class="relative">
                <input type="password" name="password" class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:outline-none" placeholder="Password" required>
                <i class="fas fa-lock absolute left-4 top-3 text-gray-500"></i>
            </div>
            <button type="submit" class="w-full py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 focus:outline-none">Login</button>
        </form>
    </div>
</body>
</html>
