<?php

declare(strict_types=1);

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

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

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

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

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

$page_title = 'Result Reports';

/*
|--------------------------------------------------------------------------
| FILTERS
|--------------------------------------------------------------------------
*/

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

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

/*
|--------------------------------------------------------------------------
| FETCH EXAMS
|--------------------------------------------------------------------------
*/

$examStmt = $pdo->prepare("
    SELECT
        id,
        exam_name
    FROM exam_types
    WHERE school_id = ?
    AND status = 'Active'
    ORDER BY display_order ASC,
    exam_name ASC
");

$examStmt->execute([$school_id]);

$examTypes = $examStmt->fetchAll(PDO::FETCH_ASSOC);

/*
|--------------------------------------------------------------------------
| FETCH CLASSES
|--------------------------------------------------------------------------
*/

$classStmt = $pdo->prepare("
    SELECT
        id,
        class_name
    FROM classes
    WHERE school_id = ?
    ORDER BY sort_order ASC,
    class_name ASC
");

$classStmt->execute([$school_id]);

$classes = $classStmt->fetchAll(PDO::FETCH_ASSOC);

/*
|--------------------------------------------------------------------------
| REPORT DATA
|--------------------------------------------------------------------------
*/

$total_students = 0;

$pass_students = 0;

$fail_students = 0;

$average_percentage = 0;

$topper = null;

$results = [];

if (
    $exam_type_id > 0 &&
    $class_id > 0
) {

    $resultStmt = $pdo->prepare("
        SELECT

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

            s.name,

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

    $resultStmt->execute([

        $school_id,
        $session_id,
        $exam_type_id,
        $class_id

    ]);

    $results = $resultStmt->fetchAll(PDO::FETCH_ASSOC);

    /*
    |--------------------------------------------------------------------------
    | TOTALS
    |--------------------------------------------------------------------------
    */

    $total_students = count($results);

    $percentageSum = 0;

    foreach ($results as $row) {

        $percentageSum += (float) $row['percentage'];

        if ($row['result_status'] === 'Pass') {

            $pass_students++;

        } else {

            $fail_students++;
        }
    }

    /*
    |--------------------------------------------------------------------------
    | TOPPER
    |--------------------------------------------------------------------------
    */

    if (!empty($results)) {

        $topper = $results[0];
    }

    /*
    |--------------------------------------------------------------------------
    | AVERAGE
    |--------------------------------------------------------------------------
    */

    if ($total_students > 0) {

        $average_percentage = round(

            $percentageSum / $total_students,

            2
        );
    }
}

require_once __DIR__ . '/../include/header.php';

require_once __DIR__ . '/../include/sidebar.php';
?>

<div class="content-wrapper">

    <section class="content-header">

        <div class="container-fluid">

            <div class="row mb-2">

                <div class="col-sm-6">

                    <h1>

                        Result Reports

                    </h1>

                </div>

            </div>

        </div>

    </section>

    <section class="content">

        <div class="container-fluid">

            <!-- FILTER -->

            <div class="card card-outline card-primary">

                <div class="card-header">

                    <h3 class="card-title">

                        Filter Reports

                    </h3>

                </div>

                <div class="card-body">

                    <form method="GET">

                        <div class="row">

                            <div class="col-md-4 mb-3">

                                <label>

                                    Exam Type

                                </label>

                                <select
                                    name="exam_type_id"
                                    class="form-control select2"
                                    required
                                >

                                    <option value="">

                                        Select Exam

                                    </option>

                                    <?php foreach ($examTypes as $exam): ?>

                                        <option
                                            value="<?= (int) $exam['id']; ?>"
                                            <?= $exam_type_id === (int) $exam['id'] ? 'selected' : ''; ?>
                                        >

                                            <?= htmlspecialchars($exam['exam_name']); ?>

                                        </option>

                                    <?php endforeach; ?>

                                </select>

                            </div>

                            <div class="col-md-4 mb-3">

                                <label>

                                    Class

                                </label>

                                <select
                                    name="class_id"
                                    class="form-control select2"
                                    required
                                >

                                    <option value="">

                                        Select Class

                                    </option>

                                    <?php foreach ($classes as $class): ?>

                                        <option
                                            value="<?= (int) $class['id']; ?>"
                                            <?= $class_id === (int) $class['id'] ? 'selected' : ''; ?>
                                        >

                                            <?= htmlspecialchars($class['class_name']); ?>

                                        </option>

                                    <?php endforeach; ?>

                                </select>

                            </div>

                            <div class="col-md-4 mb-3 d-flex align-items-end">

                                <button
                                    type="submit"
                                    class="btn btn-primary w-100"
                                >

                                    <i class="fas fa-chart-bar mr-1"></i>

                                    Generate Report

                                </button>

                            </div>

                        </div>

                    </form>

                </div>

            </div>

            <?php if ($exam_type_id > 0 && $class_id > 0): ?>

                <!-- STATS -->

                <div class="row">

                    <div class="col-md-3">

                        <div class="small-box bg-info">

                            <div class="inner">

                                <h3>

                                    <?= $total_students; ?>

                                </h3>

                                <p>

                                    Total Students

                                </p>

                            </div>

                            <div class="icon">

                                <i class="fas fa-users"></i>

                            </div>

                        </div>

                    </div>

                    <div class="col-md-3">

                        <div class="small-box bg-success">

                            <div class="inner">

                                <h3>

                                    <?= $pass_students; ?>

                                </h3>

                                <p>

                                    Pass Students

                                </p>

                            </div>

                            <div class="icon">

                                <i class="fas fa-check"></i>

                            </div>

                        </div>

                    </div>

                    <div class="col-md-3">

                        <div class="small-box bg-danger">

                            <div class="inner">

                                <h3>

                                    <?= $fail_students; ?>

                                </h3>

                                <p>

                                    Fail Students

                                </p>

                            </div>

                            <div class="icon">

                                <i class="fas fa-times"></i>

                            </div>

                        </div>

                    </div>

                    <div class="col-md-3">

                        <div class="small-box bg-warning">

                            <div class="inner">

                                <h3>

                                    <?= $average_percentage; ?>%

                                </h3>

                                <p>

                                    Average Percentage

                                </p>

                            </div>

                            <div class="icon">

                                <i class="fas fa-chart-line"></i>

                            </div>

                        </div>

                    </div>

                </div>

                <!-- TOPPER -->

                <?php if ($topper): ?>

                    <div class="card card-outline card-success">

                        <div class="card-header">

                            <h3 class="card-title">

                                Class Topper

                            </h3>

                        </div>

                        <div class="card-body">

                            <h4>

                                <?= htmlspecialchars($topper['name']); ?>

                            </h4>

                            <p>

                                Roll No:
                                <?= htmlspecialchars($topper['roll_no']); ?>

                            </p>

                            <p>

                                Percentage:
                                <?= htmlspecialchars($topper['percentage']); ?>%

                            </p>

                        </div>

                    </div>

                <?php endif; ?>

            <?php endif; ?>

        </div>

    </section>

</div>

<link
    rel="stylesheet"
    href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css"
>

<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>

    $(document).ready(function () {

        $('.select2').select2({
            width: '100%'
        });
    });

</script>

<?php require_once __DIR__ . '/../include/footer.php'; ?>