<?php

declare(strict_types=1);

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

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

require_once __DIR__ . '/services/ResultAnalyticsService.php';

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

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

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

$page_title = 'Merit List';

/*
|--------------------------------------------------------------------------
| 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);

/*
|--------------------------------------------------------------------------
| FETCH RESULTS
|--------------------------------------------------------------------------
*/

$results = [];

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

    $resultStmt = $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
    ");

    $resultStmt->execute([

        $school_id,
        $session_id,
        $exam_type_id,
        $class_id

    ]);

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

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>

                        Merit List

                    </h1>

                </div>

                <?php if (!empty($results)): ?>

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

                        <button
                            onclick="window.print()"
                            class="btn btn-primary"
                        >

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

                            Print Merit List

                        </button>

                    </div>

                <?php endif; ?>

            </div>

        </div>

    </section>

    <section class="content">

        <div class="container-fluid">

            <?php include __DIR__ . '/partials/result-filter.php'; ?>

            <?php if (!empty($results)): ?>

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

                    <div class="card-header">

                        <h3 class="card-title">

                            Class Merit List

                        </h3>

                    </div>

                    <div class="card-body table-responsive">

                        <table
                            id="meritTable"
                            class="table table-bordered table-striped"
                        >

                            <thead>

                                <tr>

                                    <th>

                                        Rank

                                    </th>

                                    <th>

                                        Photo

                                    </th>

                                    <th>

                                        Roll No

                                    </th>

                                    <th>

                                        Student Name

                                    </th>

                                    <th>

                                        Percentage

                                    </th>

                                    <th>

                                        Grade

                                    </th>

                                    <th>

                                        Status

                                    </th>

                                </tr>

                            </thead>

                            <tbody>

                                <?php foreach ($results as $row): ?>

                                    <?php

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

                                    ?>

                                    <tr>

                                        <td>

                                            <strong>

                                                <?= (int) $row['rank_position']; ?>

                                            </strong>

                                        </td>

                                        <td class="text-center">

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

                                        </td>

                                        <td>

                                            <?= htmlspecialchars($row['roll_no']); ?>

                                        </td>

                                        <td>

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

                                        </td>

                                        <td>

                                            <?= htmlspecialchars($row['percentage']); ?>%

                                        </td>

                                        <td>

                                            <?= htmlspecialchars($row['overall_grade']); ?>

                                        </td>

                                        <td>

                                            <?php if ($row['result_status'] === 'Pass'): ?>

                                                <span class="badge badge-success">

                                                    Pass

                                                </span>

                                            <?php else: ?>

                                                <span class="badge badge-danger">

                                                    Fail

                                                </span>

                                            <?php endif; ?>

                                        </td>

                                    </tr>

                                <?php endforeach; ?>

                            </tbody>

                        </table>

                    </div>

                </div>

            <?php endif; ?>

        </div>

    </section>

</div>

<link
    rel="stylesheet"
    href="https://cdn.datatables.net/1.13.8/css/dataTables.bootstrap4.min.css"
>

<link
    rel="stylesheet"
    href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.bootstrap4.min.css"
>

<script src="https://cdn.datatables.net/1.13.8/js/jquery.dataTables.min.js"></script>

<script src="https://cdn.datatables.net/1.13.8/js/dataTables.bootstrap4.min.js"></script>

<script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>

<script src="https://cdn.datatables.net/responsive/2.5.0/js/responsive.bootstrap4.min.js"></script>

<script>

    $(document).ready(function () {

        $('#meritTable').DataTable({

            responsive: true,

            autoWidth: false,

            pageLength: 25,

            ordering: true
        });
    });

</script>

<link
    rel="stylesheet"
    href="assets/css/print.css"
>

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