<?php

declare(strict_types=1);

require_once __DIR__ . '/../../library/auth.php';

require_once __DIR__ . '/../helpers/result-helper.php';

allow_roles(['admin', 'teacher']);

requirePostRequest();

verifyCsrfToken();

$school_id = (int) $_SESSION['school_id'];

$session_id = (int) ($_SESSION['session_id'] ?? 0);

/*
|--------------------------------------------------------------------------
| VALIDATE INPUTS
|--------------------------------------------------------------------------
*/

$exam_type_id = validateId(
    $_POST['exam_type_id'] ?? 0
);

$class_id = validateId(
    $_POST['class_id'] ?? 0
);

$limit = validateId(
    $_POST['limit'] ?? 10
);

if (
    $exam_type_id <= 0 ||
    $class_id <= 0 ||
    $session_id <= 0
) {

    jsonResponse(
        false,
        'Invalid request data!'
    );
}

/*
|--------------------------------------------------------------------------
| LIMIT PROTECTION
|--------------------------------------------------------------------------
*/

if ($limit <= 0 || $limit > 50) {

    $limit = 10;
}

try {

    /*
    |--------------------------------------------------------------------------
    | FETCH TOP STUDENTS
    |--------------------------------------------------------------------------
    */

    $stmt = $pdo->prepare("
        SELECT

            er.rank_position,
            er.percentage,
            er.overall_grade,
            er.result_status,

            s.name,
            s.photo,

            ss.roll_no

        FROM exam_results er

        INNER JOIN students s
            ON s.id = er.student_id
            AND s.school_id = er.school_id

        INNER JOIN student_sessions ss
            ON ss.student_id = er.student_id
            AND ss.school_id = er.school_id
            AND ss.session_id = er.session_id
            AND ss.class_id = er.class_id

        WHERE er.school_id = ?
        AND er.session_id = ?
        AND er.exam_type_id = ?
        AND er.class_id = ?

        ORDER BY
            er.rank_position ASC,
            er.percentage DESC

        LIMIT {$limit}
    ");

    $stmt->execute([

        $school_id,
        $session_id,
        $exam_type_id,
        $class_id

    ]);

    $students = $stmt->fetchAll(PDO::FETCH_ASSOC);

    /*
    |--------------------------------------------------------------------------
    | EMPTY CHECK
    |--------------------------------------------------------------------------
    */

    if (empty($students)) {

        jsonResponse(
            false,
            'No topper data found!'
        );
    }

    /*
    |--------------------------------------------------------------------------
    | BUILD HTML
    |--------------------------------------------------------------------------
    */

    $html = '';

    foreach ($students as $student) {

        $photo = !empty($student['photo'])
            ? WEB_ROOT . 'student/uploads/' . $student['photo']
            : 'https://placehold.co/60x60?text=Photo';

        $statusBadge = $student['result_status'] === 'Pass'
            ? '<span class="badge badge-success">Pass</span>'
            : '<span class="badge badge-danger">Fail</span>';

        $html .= '

            <tr>

                <td>
                    ' . (int) $student['rank_position'] . '
                </td>

                <td class="text-center">

                    <img
                        src="' . htmlspecialchars($photo) . '"
                        class="img-thumbnail"
                        width="50"
                        alt="Student Photo"
                    >

                </td>

                <td>

                    <strong>
                        ' . htmlspecialchars($student['name']) . '
                    </strong>

                    <br>

                    <small class="text-muted">

                        Roll No:
                        ' . htmlspecialchars($student['roll_no']) . '

                    </small>

                </td>

                <td>
                    ' . htmlspecialchars($student['percentage']) . '%
                </td>

                <td>
                    ' . htmlspecialchars($student['overall_grade']) . '
                </td>

                <td>
                    ' . $statusBadge . '
                </td>

            </tr>
        ';
    }

    /*
    |--------------------------------------------------------------------------
    | RESPONSE
    |--------------------------------------------------------------------------
    */

    jsonResponse(

        true,

        'Top students fetched successfully!',

        [
            'html' => $html
        ]
    );

} catch (Throwable $e) {

    jsonResponse(
        false,
        $e->getMessage()
    );
}