<?php
declare(strict_types=1);

function examsTerms(): array
{
    return ['First Term', 'Second Term', 'Third Term'];
}

function examsGetClasses(mysqli $conn): array
{
    $classes = [];
    // Primary: active classes from Class Management
    $stmt = $conn->prepare("SELECT class_name FROM classes WHERE is_active = 1 ORDER BY class_name");
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $classes[] = (string) $row['class_name'];
    }
    $stmt->close();
    // Fallback: include any student class not yet registered in Class Management
    $stmt2 = $conn->prepare("SELECT DISTINCT class FROM students WHERE class IS NOT NULL AND class != '' ORDER BY class");
    $stmt2->execute();
    $result2 = $stmt2->get_result();
    while ($row = $result2->fetch_assoc()) {
        if (!in_array($row['class'], $classes)) $classes[] = (string) $row['class'];
    }
    $stmt2->close();
    sort($classes);
    return $classes;
}

function examsGetSubjects(mysqli $conn): array
{
    $subjects = [];
    $stmt = $conn->prepare("SELECT id, subject_name, subject_code FROM subjects ORDER BY subject_name");
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $subjects[] = $row;
    }
    $stmt->close();
    return $subjects;
}

function examsGetTeachers(mysqli $conn): array
{
    $teachers = [];
    $stmt = $conn->prepare("SELECT id, full_name, email FROM staff WHERE status = 'active' ORDER BY full_name");
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $teachers[] = $row;
    }
    $stmt->close();
    return $teachers;
}

function examsGetSettings(mysqli $conn): array
{
    $settings = [];
    $result = $conn->query("SELECT setting_key, setting_value FROM settings");
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $settings[(string) $row['setting_key']] = (string) $row['setting_value'];
        }
    }
    return $settings;
}

function examsGetGrade(mysqli $conn, float $score): string
{
    $stmt = $conn->prepare("SELECT grade_name FROM grade_boundaries WHERE ? BETWEEN min_score AND max_score ORDER BY max_score DESC LIMIT 1");
    $stmt->bind_param('d', $score);
    $stmt->execute();
    $result = $stmt->get_result();
    $grade = 'N/A';
    if ($row = $result->fetch_assoc()) {
        $grade = (string) ($row['grade_name'] ?? 'N/A');
    }
    $stmt->close();
    return $grade;
}

function examsUpdatePaperTotalMarks(mysqli $conn, int $paperId): void
{
    $stmt = $conn->prepare("SELECT COALESCE(SUM(marks),0) AS total_marks FROM exam_paper_questions WHERE paper_id = ?");
    $stmt->bind_param('i', $paperId);
    $stmt->execute();
    $result = $stmt->get_result();
    $total = 0;
    if ($row = $result->fetch_assoc()) {
        $total = (int) $row['total_marks'];
    }
    $stmt->close();

    $update = $conn->prepare("UPDATE exam_papers SET total_marks = ? WHERE id = ?");
    $update->bind_param('ii', $total, $paperId);
    $update->execute();
    $update->close();
}

function examsRenderSidebar(string $active = 'questions'): string
{
    $items = [
        ['../dashboard.php',                  'fas fa-tachometer-alt',   'Dashboard'],
        ['../students.php',                   'fas fa-user-graduate',    'Students'],
        ['../fees.php',                       'fas fa-money-bill-wave',  'Fees'],
        ['../expenses.php',                   'fas fa-receipt',          'Expenses'],
        ['../reports.php',                    'fas fa-chart-bar',        'Reports'],
        ['../modules/reports/index.php',      'fas fa-file-alt',         'Terminal Reports'],
        ['../modules/timetable/index.php',    'fas fa-calendar-alt',     'Timetable'],
        ['../staff.php',                      'fas fa-chalkboard-teacher','Staff'],
        ['../parent_accounts.php',            'fas fa-users',            'Parent Accounts'],
        ['../user_management.php',            'fas fa-users-cog',        'User Management'],
        ['../alerts.php',                     'fas fa-bell',             'Alerts'],
        ['../settings.php',                   'fas fa-cog',              'Settings'],
        ['../ai_dashboard.php',               'fas fa-brain',            'RBC AI Agent'],
        ['../ai_analytics.php',               'fas fa-robot',            'AI Analytics'],
        ['../logout.php',                     'fas fa-sign-out-alt',     'Logout'],
    ];

    $examChildren = [
        'questions' => ['index.php', 'Question Bank'],
        'ai' => ['ai_generator.php', 'AI Generator'],
        'paper-generator' => ['exam_paper_generator.php', 'AI Paper Generator'],
        'exam-review' => ['view_exams.php', 'Exam Workflow Board'],
        'ai-settings' => ['ai_settings.php', 'AI Settings'],
        'papers' => ['paper_builder.php', 'Paper Builder'],
        'schedules' => ['schedules.php', 'Schedules'],
        'results' => ['results.php', 'Results'],
    ];

    ob_start();
    ?>
    <nav id="sidebar" class="sidebar">
        <div class="sidebar-header">
            <h3><i class="fas fa-graduation-cap me-2"></i>EduTrack</h3>
        </div>
        <ul class="list-unstyled components">
            <?php foreach ($items as [$href, $icon, $label]): ?>
                <li class="nav-item">
                    <a href="<?= htmlspecialchars($href) ?>" class="nav-link">
                        <i class="<?= htmlspecialchars($icon) ?> me-2"></i><?= htmlspecialchars($label) ?>
                    </a>
                </li>
            <?php endforeach; ?>
            <li class="nav-item">
                <a class="nav-link<?= $active !== '' ? ' active' : '' ?>" data-bs-toggle="collapse" href="#examsMenu" role="button" aria-expanded="true">
                    <i class="fas fa-file-alt me-2"></i>Exams
                    <i class="fas fa-chevron-down ms-auto"></i>
                </a>
                <div class="collapse show" id="examsMenu">
                    <ul class="nav flex-column ms-3">
                        <?php foreach ($examChildren as $key => [$href, $label]): ?>
                            <li class="nav-item">
                                <a class="nav-link<?= $active === $key ? ' active' : '' ?>" href="<?= htmlspecialchars($href) ?>">
                                    <?= htmlspecialchars($label) ?>
                                </a>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            </li>
        </ul>
    </nav>
    <?php
    return (string) ob_get_clean();
}

function examsRenderTabs(string $active): string
{
    $tabs = [
        'questions' => ['index.php', 'Question Bank'],
        'papers' => ['paper_builder.php', 'Exam Papers'],
        'ai' => ['ai_generator.php', 'AI Generator'],
        'paper-generator' => ['exam_paper_generator.php', 'AI Paper Generator'],
        'exam-review' => ['view_exams.php', 'Exam Workflow Board'],
        'ai-settings' => ['ai_settings.php', 'AI Settings'],
        'schedules' => ['schedules.php', 'Schedules'],
        'results' => ['results.php', 'Results'],
    ];

    ob_start();
    ?>
    <ul class="nav nav-tabs mb-4">
        <?php foreach ($tabs as $key => [$href, $label]): ?>
            <li class="nav-item">
                <a class="nav-link<?= $active === $key ? ' active' : '' ?>" href="<?= htmlspecialchars($href) ?>"><?= htmlspecialchars($label) ?></a>
            </li>
        <?php endforeach; ?>
    </ul>
    <?php
    return (string) ob_get_clean();
}
