<?php
/** EnglishSpeak — Teacher authentication guard. */

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

/**
 * Build an absolute web URL for a path stored relative to the project root
 * (e.g. "uploads/word-library/images/apple-1.png" → "/EnglishSpeak/uploads/word-library/images/apple-1.png").
 */
if (!function_exists('es_url')) {
    function es_url(string $relative = ''): string
    {
        static $base = null;

        if ($base === null) {
            $projectRoot = str_replace('\\', '/', (string)(realpath(dirname(__DIR__, 2)) ?: dirname(__DIR__, 2)));
            $docRoot     = str_replace('\\', '/', (string)(realpath($_SERVER['DOCUMENT_ROOT'] ?? '') ?: ''));
            $base = '';
            if ($docRoot !== '' && strpos($projectRoot . '/', rtrim($docRoot, '/') . '/') === 0) {
                $base = rtrim(substr($projectRoot, strlen(rtrim($docRoot, '/'))), '/');
            }
        }

        $rel = ltrim(str_replace('\\', '/', $relative), '/');
        return $base . '/' . $rel;
    }
}

if (empty($_SESSION['user_id']) || !in_array($_SESSION['user_role'] ?? '', ['teacher', 'admin'], true)) {
    $returnTo = $_SERVER['REQUEST_URI'] ?? '';
    $query = $returnTo !== '' ? '?return=' . rawurlencode($returnTo) : '';
    header('Location: ../login.php' . $query);
    exit;
}

/*
 * Re-check the account in the database on every protected Teacher/Admin request.
 * This prevents an old session from continuing after Admin locks the account
 * or while a newly entered school is still waiting for approval.
 */
try {
    if (!isset($pdo) || !($pdo instanceof PDO)) {
        $dbCandidates = [
            dirname(__DIR__) . '/config/database.php',
            dirname(__DIR__) . '/config/db.php',
            dirname(__DIR__) . '/includes/db.php',
            dirname(__DIR__) . '/includes/database.php',
        ];

        foreach ($dbCandidates as $dbFile) {
            if (is_file($dbFile)) {
                require_once $dbFile;
                if (isset($pdo) && $pdo instanceof PDO) {
                    break;
                }
            }
        }
    }

    if (isset($pdo) && $pdo instanceof PDO) {
        $authStmt = $pdo->prepare(
            "SELECT id, role, status
             FROM users
             WHERE id = :id
             LIMIT 1"
        );
        $authStmt->execute(['id' => (int)$_SESSION['user_id']]);
        $authUser = $authStmt->fetch(PDO::FETCH_ASSOC);

        $sessionRole = (string)($_SESSION['user_role'] ?? '');
        $dbRole = (string)($authUser['role'] ?? '');
        $dbStatus = (string)($authUser['status'] ?? '');

        if (
            !$authUser ||
            !in_array($dbRole, ['teacher', 'admin'], true) ||
            $dbRole !== $sessionRole ||
            $dbStatus !== 'active'
        ) {
            $_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();

            $returnTo = $_SERVER['REQUEST_URI'] ?? '';
            $query = $returnTo !== '' ? '?return=' . rawurlencode($returnTo) : '';
            header('Location: ../login.php' . $query);
            exit;
        }
    }
} catch (Throwable $e) {
    // Keep the existing authentication flow if this guard is loaded before
    // the project's PDO connection. Pages that already provide $pdo are
    // checked immediately without changing the rest of the application.
}
