<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once 'connection.php';

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

    // Escape input
    $username = mysqli_real_escape_string($conn, $username);

    // Look up the user
    $sql = "SELECT * FROM admin_users WHERE username = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 1) {
        $user = $result->fetch_assoc();

        // Verify password against stored hash
        if (password_verify($password, $user['password'])) {
            // Login success
            $_SESSION['admin_logged_in'] = true;
            $_SESSION['admin_username'] = $username;
            header("Location: admin_dashboard.php");
            exit();
        }
    }

    // Login failed
    header("Location: admin_login.html?error=Invalid+credentials");
    exit();
}
?>
