<?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
);

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

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

try {

    /*
    |--------------------------------------------------------------------------
    | FETCH RESULT STATS
    |--------------------------------------------------------------------------
    */

    $statsStmt = $pdo->prepare("
        SELECT

            COUNT(*) AS total_students,

            SUM(
                CASE
                    WHEN result_status = 'Pass'
                    THEN 1
                    ELSE 0
                END
            ) AS pass_students,

            SUM(
                CASE
                    WHEN result_status = 'Fail'
                    THEN 1
                    ELSE 0
                END
            ) AS fail_students,

            AVG(percentage) AS average_percentage,

            MAX(percentage) AS highest_percentage,

            MIN(percentage) AS lowest_percentage

        FROM exam_results

        WHERE school_id = ?
        AND session_id = ?
        AND exam_type_id = ?
        AND class_id = ?
    ");

    $statsStmt->execute([

        $school_id,
        $session_id,
        $exam_type_id,
        $class_id

    ]);

    $stats = $statsStmt->fetch(PDO::FETCH_ASSOC);

    if (!$stats) {

        throw new Exception(
            'No result data found!'
        );
    }

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

    jsonResponse(

        true,

        'Result statistics fetched successfully!',

        [

            'total_students' => (int) (
                $stats['total_students'] ?? 0
            ),

            'pass_students' => (int) (
                $stats['pass_students'] ?? 0
            ),

            'fail_students' => (int) (
                $stats['fail_students'] ?? 0
            ),

            'average_percentage' => round(
                (float) (
                    $stats['average_percentage'] ?? 0
                ),
                2
            ),

            'highest_percentage' => round(
                (float) (
                    $stats['highest_percentage'] ?? 0
                ),
                2
            ),

            'lowest_percentage' => round(
                (float) (
                    $stats['lowest_percentage'] ?? 0
                ),
                2
            )
        ]
    );

} catch (Throwable $e) {

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