<?php
require_once __DIR__ . '/../config/database.php';

/**
 * Check if an admin is currently logged in.
 */
function isLoggedIn(): bool {
    return isset($_SESSION['admin_id']);
}

/**
 * Redirect to login if not authenticated.
 */
function requireLogin(): void {
    if (!isLoggedIn()) {
        header('Location: ../login.php');
        exit;
    }
}

/**
 * Attempt to log in an admin user.
 */
function login(string $username, string $password): bool {
    global $pdo;
    $stmt = $pdo->prepare("SELECT * FROM admin_users WHERE username = :username");
    $stmt->execute([':username' => $username]);
    $admin = $stmt->fetch();

    if ($admin && password_verify($password, $admin['password_hash'])) {
        $_SESSION['admin_id']   = $admin['id'];
        $_SESSION['admin_name'] = $admin['full_name'];
        return true;
    }
    return false;
}

/**
 * Logout the current admin.
 */
function logout(): void {
    $_SESSION = [];
    if (ini_get("session.use_cookies")) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000,
            $params["path"], $params["domain"],
            $params["secure"], $params["httponly"]
        );
    }
    session_destroy();
}