<?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('studentLogin')) {
    function studentLogin(PDO $pdo, string $studentCode, string $cardNumber): bool
    {
        $studentCode = strtoupper(clean($studentCode));
        $cardNumber = strtoupper(clean($cardNumber));
        $rateKey = 'student:' . hash('sha256', strtolower($studentCode) . '|' . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
        if (tooManyLoginAttempts($rateKey)) return false;

        $cardCondition = columnExists($pdo, 'students', 'student_card_number') && columnExists($pdo, 'students', 'student_card')
            ? '(UPPER(COALESCE(student_card_number, student_card, \'\')) = ?)'
            : (columnExists($pdo, 'students', 'student_card_number') ? 'UPPER(student_card_number) = ?' : 'UPPER(student_card) = ?');

        $stmt = $pdo->prepare("SELECT * FROM students WHERE UPPER(student_code) = ? AND {$cardCondition} LIMIT 1");
        $stmt->execute([$studentCode, $cardNumber]);
        $student = $stmt->fetch(PDO::FETCH_ASSOC);

        $allowed = $student
            && in_array(strtolower((string)($student['status'] ?? 'approved')), ['approved', 'active'], true)
            && strtolower((string)($student['core_status'] ?? 'active')) !== 'suspended';

        if (!$allowed) {
            addLoginAttempt($rateKey);
            return false;
        }

        regenerateSession();
        $_SESSION['student_id'] = (int)$student['id'];
        $_SESSION['student_name'] = (string)($student['full_name'] ?? 'Student');
        $_SESSION['student_code'] = (string)($student['student_code'] ?? '');
        $_SESSION['student_level'] = (string)($student['final_level'] ?? $student['selected_level'] ?? '');
        $_SESSION['student_card_number'] = (string)($student['student_card_number'] ?? $student['student_card'] ?? '');
        $_SESSION['student_logged_in'] = true;
        $_SESSION['student_last_activity'] = time();
        clearLoginAttempts($rateKey);
        logActivity($pdo, 'student', (int)$student['id'], 'login', 'Student logged into the core periods gateway.');
        return true;
    }
}

if (!function_exists('isStudentLoggedIn')) {
    function isStudentLoggedIn(): bool
    {
        return !empty($_SESSION['student_logged_in']) && (int)($_SESSION['student_id'] ?? 0) > 0;
    }
}

if (!function_exists('requireStudent')) {
    function requireStudent(): void
    {
        if (!isStudentLoggedIn() || (isset($_SESSION['student_last_activity']) && time() - (int)$_SESSION['student_last_activity'] > SESSION_IDLE_TIMEOUT)) { studentLogout(); redirect('login.php'); }
        $_SESSION['student_last_activity'] = time();
    }
}

if (!function_exists('currentStudentId')) {
    function currentStudentId(): ?int
    {
        $id = (int)($_SESSION['student_id'] ?? 0);
        return $id > 0 ? $id : null;
    }
}

if (!function_exists('currentStudent')) {
    function currentStudent(PDO $pdo): ?array
    {
        $id = currentStudentId();
        if (!$id || !tableExists($pdo, 'students')) return null;
        $stmt = $pdo->prepare('SELECT * FROM students WHERE id = ? LIMIT 1');
        $stmt->execute([$id]);
        $student = $stmt->fetch(PDO::FETCH_ASSOC);
        $allowed = $student
            && in_array(strtolower((string)($student['status'] ?? 'approved')), ['approved','active'], true)
            && strtolower((string)($student['core_status'] ?? 'active')) !== 'suspended';
        return $allowed ? $student : null;
    }
}

if (!function_exists('studentLogout')) {
    function studentLogout(): void
    {
        foreach (array_keys($_SESSION) as $key) {
            if (str_starts_with((string)$key, 'student_') || $key === 'selected_core_course_id') unset($_SESSION[$key]);
        }
        regenerateSession();
    }
}

if (!function_exists('studentLanguage')) {
    function studentLanguage(): string { return (string)($_SESSION['lang'] ?? 'en'); }
}
if (!function_exists('setStudentLanguage')) {
    function setStudentLanguage(string $lang): void { $_SESSION['lang'] = in_array($lang, ['en', 'ar'], true) ? $lang : 'en'; }
}
if (!function_exists('studentProfileImage')) {
    function studentProfileImage(array $student): string
    {
        return !empty($student['profile_image'])
            ? url((string)$student['profile_image'])
            : asset('images/default-avatar.svg');
    }
}
if (!function_exists('studentDashboardUrl')) {
    function studentDashboardUrl(): string { return url('student/dashboard.php'); }
}
if (!function_exists('studentName')) {
    function studentName(): string { return (string)($_SESSION['student_name'] ?? 'Student'); }
}
if (!function_exists('studentLevel')) {
    function studentLevel(): string { return (string)($_SESSION['student_level'] ?? 'Unknown'); }
}
if (!function_exists('studentCardNumber')) {
    function studentCardNumber(): string { return (string)($_SESSION['student_card_number'] ?? '-'); }
}
