<?php
// includes/admin_auth.php
declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

$mysqli = $mysqli ?? ($conn ?? null);

if ($mysqli instanceof mysqli) {
    $timeoutMinutes = (int)elms_setting($mysqli, 'session_timeout_minutes', '60');
    $timeoutSeconds = max(5, $timeoutMinutes) * 60;

    $lastActivity = (int)($_SESSION['last_activity_at'] ?? time());

    if (!empty($_SESSION['admin_id']) && (time() - $lastActivity) > $timeoutSeconds) {
        session_unset();
        session_destroy();
        header('Location: /elms/auth/login.php?timeout=1');
        exit;
    }

    $_SESSION['last_activity_at'] = time();
}


if (isset($mysqli) && $mysqli instanceof mysqli) {
    if (elms_setting_on($mysqli, 'maintenance_mode', 'off')) {
        $role = $_SESSION['role'] ?? $_SESSION['admin_role'] ?? '';

        if (!in_array($role, ['super_admin', 'admin'], true)) {
            http_response_code(503);
            exit('ELMS is currently under maintenance. Please try again later.');
        }
    }
}

$ADMIN_ALLOWED_ROLES = ['super_admin', 'admin', 'manager'];

function admin_normalize_role(string $role): string
{
    $role = strtolower(trim($role));

    return match ($role) {
        'superadmin'   => 'super_admin',
        'super admin'  => 'super_admin',
        'administrator'=> 'admin',
        default        => $role,
    };
}

function admin_login_url(): string
{
    return '/elms/auth/login.php';
}

function admin_current_session_user(): array
{
    $id = $_SESSION['admin_id']
        ?? ($_SESSION['admin']['id'] ?? null)
        ?? null;

    $name = $_SESSION['admin_name']
        ?? ($_SESSION['admin']['name'] ?? null)
        ?? ($_SESSION['admin']['full_name'] ?? null)
        ?? 'Admin';

    $role = $_SESSION['admin_role']
        ?? ($_SESSION['admin']['role'] ?? null)
        ?? '';

    /*
     * Fallback only for old admin login systems.
     * Do NOT use coordinator/student user role as admin role.
     */
    if ($role === '' && isset($_SESSION['admin'])) {
        $role = $_SESSION['role'] ?? $_SESSION['user_role'] ?? '';
    }

    return [
        'id'   => $id,
        'name' => (string)$name,
        'role' => admin_normalize_role((string)$role),
    ];
}

$ADMIN_USER = admin_current_session_user();

if (empty($ADMIN_USER['role'])) {
    header("Location: " . admin_login_url());
    exit;
}

if (!in_array($ADMIN_USER['role'], $ADMIN_ALLOWED_ROLES, true)) {
    http_response_code(403);
    ?>
    <!doctype html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>403 - Access Denied</title>
        <style>
            body{font-family:Arial,sans-serif;background:#f8fafc;margin:0;padding:40px;color:#111827}
            .box{max-width:560px;background:#fff;border:1px solid #e5e7eb;border-radius:16px;padding:24px;box-shadow:0 10px 30px rgba(15,23,42,.08)}
            h2{margin:0 0 10px;color:#b91c1c}
            p{margin:8px 0;color:#374151}
            a{display:inline-block;margin-top:14px;background:#2563eb;color:#fff;text-decoration:none;padding:10px 14px;border-radius:10px;font-weight:700}
            code{background:#f1f5f9;padding:3px 6px;border-radius:6px}
        </style>
    </head>
    <body>
        <div class="box">
            <h2>403 - Access Denied</h2>
            <p>You do not have permission to access Admin Portal.</p>
            <p>Current role: <code><?= htmlspecialchars($ADMIN_USER['role'], ENT_QUOTES, 'UTF-8') ?></code></p>
            <p>Allowed roles: <code>super_admin</code>, <code>admin</code>, <code>manager</code></p>
            <a href="/elms/admin/logout.php">Logout and login as Admin</a>
        </div>
    </body>
    </html>
    <?php
    exit;
}

$_SESSION['admin_id']   = $ADMIN_USER['id'] ?? ($_SESSION['admin_id'] ?? 1);
$_SESSION['admin_name'] = $ADMIN_USER['name'];
$_SESSION['admin_role'] = $ADMIN_USER['role'];

if (!function_exists('h')) {
    function h($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('admin_id')) {
    function admin_id(): int
    {
        return (int)($_SESSION['admin_id'] ?? 0);
    }
}

if (!function_exists('admin_name')) {
    function admin_name(): string
    {
        return (string)($_SESSION['admin_name'] ?? 'Admin');
    }
}

if (!function_exists('admin_role')) {
    function admin_role(): string
    {
        return admin_normalize_role((string)($_SESSION['admin_role'] ?? ''));
    }
}

if (!function_exists('admin_can')) {
    function admin_can(array|string $roles): bool
    {
        $roles = is_array($roles) ? $roles : [$roles];
        $roles = array_map('admin_normalize_role', $roles);

        return in_array(admin_role(), $roles, true);
    }
}