<?php
declare(strict_types=1);

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

if (!function_exists('isAdminLoggedIn')) {
    function isAdminLoggedIn(): bool { return (int)($_SESSION['core_admin_id'] ?? 0) > 0; }
}
if (!function_exists('requireAdmin')) {
    function requireAdmin(): void { if (!isAdminLoggedIn() || (isset($_SESSION['admin_last_activity']) && time() - (int)$_SESSION['admin_last_activity'] > SESSION_IDLE_TIMEOUT)) { adminLogout(); redirect('admin/login.php'); } $_SESSION['admin_last_activity'] = time(); }
}
if (!function_exists('currentAdminId')) {
    function currentAdminId(): int { return (int)($_SESSION['core_admin_id'] ?? 0); }
}
if (!function_exists('currentAdmin')) {
    function currentAdmin(PDO $pdo): ?array
    {
        $id = currentAdminId();
        if ($id <= 0) return null;
        $stmt = $pdo->prepare("SELECT * FROM core_admins WHERE id = ? AND COALESCE(status,'active') = 'active' LIMIT 1");
        $stmt->execute([$id]);
        return $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
    }
}
if (!function_exists('adminLogin')) {
    function adminLogin(PDO $pdo, string $email, string $password): bool
    {
        $email = strtolower(trim($email));
        $rateKey = 'admin:' . hash('sha256', $email . '|' . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
        if (tooManyLoginAttempts($rateKey)) return false;
        $stmt = $pdo->prepare('SELECT * FROM core_admins WHERE LOWER(email) = ? LIMIT 1');
        $stmt->execute([$email]);
        $admin = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$admin || strtolower((string)($admin['status'] ?? 'active')) !== 'active' || empty($admin['password']) || !password_verify($password, (string)$admin['password'])) {
            addLoginAttempt($rateKey);
            return false;
        }
        regenerateSession();
        $_SESSION['core_admin_id'] = (int)$admin['id'];
        $_SESSION['core_admin_name'] = (string)($admin['full_name'] ?? $admin['name'] ?? 'Admin');
        $_SESSION['core_admin_email'] = (string)($admin['email'] ?? '');
        $_SESSION['admin_last_activity'] = time();
        clearLoginAttempts($rateKey);
        logActivity($pdo, 'admin', (int)$admin['id'], 'login', 'Administrator logged into the dashboard.');
        return true;
    }
}
if (!function_exists('adminLogout')) {
    function adminLogout(): void
    {
        foreach (array_keys($_SESSION) as $key) if (str_starts_with((string)$key, 'core_admin_') || str_starts_with((string)$key, 'admin_')) unset($_SESSION[$key]);
        regenerateSession();
    }
}
if (!function_exists('loginAdmin')) {
    function loginAdmin(PDO $pdo, string $email, string $password): bool { return adminLogin($pdo, $email, $password); }
}
if (!function_exists('logoutAdmin')) {
    function logoutAdmin(): void { adminLogout(); }
}
