<?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('teacherLogin')) {
    function teacherLogin(PDO $pdo, string $email, string $password): bool
    {
        $email = strtolower(trim($email));
        $rateKey = 'teacher:' . hash('sha256', $email . '|' . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
        if (tooManyLoginAttempts($rateKey)) return false;
        $stmt = $pdo->prepare('SELECT * FROM core_teachers WHERE LOWER(email) = ? LIMIT 1');
        $stmt->execute([$email]);
        $teacher = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$teacher || strtolower((string)($teacher['status'] ?? 'active')) !== 'active' || !password_verify($password, (string)$teacher['password'])) {
            addLoginAttempt($rateKey);
            return false;
        }
        regenerateSession();
        $_SESSION['teacher_id'] = (int)$teacher['id'];
        $_SESSION['teacher_name'] = (string)($teacher['full_name'] ?: $teacher['name'] ?: 'Teacher');
        $_SESSION['teacher_email'] = (string)$teacher['email'];
        $_SESSION['teacher_last_activity'] = time();
        clearLoginAttempts($rateKey);
        logActivity($pdo, 'teacher', (int)$teacher['id'], 'login', 'Teacher logged into the dashboard.');
        return true;
    }
}
if (!function_exists('isTeacherLoggedIn')) {
    function isTeacherLoggedIn(): bool { return (int)($_SESSION['teacher_id'] ?? 0) > 0; }
}
if (!function_exists('requireTeacher')) {
    function requireTeacher(): void { if (!isTeacherLoggedIn() || (isset($_SESSION['teacher_last_activity']) && time() - (int)$_SESSION['teacher_last_activity'] > SESSION_IDLE_TIMEOUT)) { teacherLogout(); redirect('teacher/login.php'); } $_SESSION['teacher_last_activity'] = time(); }
}
if (!function_exists('currentTeacherId')) {
    function currentTeacherId(): ?int { $id = (int)($_SESSION['teacher_id'] ?? 0); return $id > 0 ? $id : null; }
}
if (!function_exists('currentTeacher')) {
    function currentTeacher(PDO $pdo): ?array
    {
        $id = currentTeacherId();
        if (!$id) return null;
        $stmt = $pdo->prepare("SELECT * FROM core_teachers WHERE id = ? AND status = 'active' LIMIT 1");
        $stmt->execute([$id]);
        return $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
    }
}
if (!function_exists('teacherLogout')) {
    function teacherLogout(): void
    {
        foreach (array_keys($_SESSION) as $key) if (str_starts_with((string)$key, 'teacher_')) unset($_SESSION[$key]);
        regenerateSession();
    }
}
