<?php
/**
 * TOPBD — Admin Authentication & Security
 */

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/functions.php';

function is_admin_logged_in(): bool {
    return !empty($_SESSION['admin_user_id']) && !empty($_SESSION['admin_logged_in']);
}

function require_admin(): void {
    if (!is_admin_logged_in()) {
        header('Location: login.php');
        exit;
    }
}

function admin_login(string $username, string $password): bool {
    $db = get_db();
    $stmt = $db->prepare("SELECT id, username, email, password_hash FROM admins WHERE username = ? OR email = ? LIMIT 1");
    $stmt->execute([$username, $username]);
    $admin = $stmt->fetch();

    if ($admin && password_verify($password, $admin['password_hash'])) {
        $_SESSION['admin_user_id'] = $admin['id'];
        $_SESSION['admin_username'] = $admin['username'];
        $_SESSION['admin_logged_in'] = true;
        $_SESSION['last_activity'] = time();

        // Update last login
        $update = $db->prepare("UPDATE admins SET last_login = NOW() WHERE id = ?");
        $update->execute([$admin['id']]);
        return true;
    }
    return false;
}

function admin_logout(): void {
    unset($_SESSION['admin_user_id'], $_SESSION['admin_username'], $_SESSION['admin_logged_in']);
    session_destroy();
}
