<?php

declare(strict_types=1);

require_once __DIR__ . '/../library/auth.php';
require_once __DIR__ . '/helpers/result-helper.php';
require_once __DIR__ . '/services/ResultAnalyticsService.php';

// Strict Authorization check
allow_roles(['admin', 'teacher']);

$school_id  = (int) $_SESSION['school_id'];
$session_id = (int) ($_SESSION['session_id'] ?? 0);
$page_title = 'Generate Results';

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

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>Generate Results</h1>
                </div>
            </div>
        </div>
    </section>

    <section class="content">
        <div class="container-fluid">
            
            <div class="card card-outline card-primary position-relative">
                <div id="generationLoaderWrapper" class="overlay d-none">
                    <i class="fas fa-2x fa-sync-alt fa-spin text-primary"></i>
                </div>

                <div class="card-header">
                    <h3 class="card-title">Generate Student Results</h3>
                </div>

                <form id="generateResultForm" method="POST">
                    <?= csrfField(); ?>

                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label for="exam_type_id">Exam Type</label>
                                <select name="exam_type_id" id="exam_type_id" class="form-control select2" required style="width: 100%;">
                                    <option value="">Select Exam</option>
                                    <?php foreach ($examTypes as $exam): ?>
                                        <option value="<?= (int) $exam['id']; ?>">
                                            <?= htmlspecialchars($exam['exam_name'], ENT_QUOTES, 'UTF-8'); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label for="class_id">Class</label>
                                <select name="class_id" id="class_id" class="form-control select2" required style="width: 100%;">
                                    <option value="">Select Class</option>
                                    <?php foreach ($classes as $class): ?>
                                        <option value="<?= (int) $class['id']; ?>">
                                            <?= htmlspecialchars($class['class_name'], ENT_QUOTES, 'UTF-8'); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div class="col-md-4 mb-3 d-flex align-items-end">
                                <button type="submit" id="btnGenerateResults" class="btn btn-success w-100">
                                    <i class="fas fa-calculator mr-2"></i> Compile & Generate
                                </button>
                            </div>
                        </div>
                    </div>
                </form>
            </div>

            <div class="alert alert-info shadow-sm">
                <h5><i class="fas fa-info-circle mr-2"></i> Results generation pipeline routine:</h5>
                <ul class="mb-0 mt-2 pl-4">
                    <li>Calculate total obtained marks & aggregate values dynamically.</li>
                    <li>Generate accurate statistical percentage scores.</li>
                    <li>Apply system-configured dynamic grades mappings automatically.</li>
                    <li>Generate relative section/class peer ranks instantly.</li>
                    <li>Compile datasets into master final immutable results sheet.</li>
                </ul>
            </div>

        </div>
    </section>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>

<script>
(function($) {
    "use strict";
    
    $(document).ready(function() {
        if ($.fn.select2) {
            $('.select2').each(function() {
                if ($(this).hasClass("select2-hidden-accessible")) {
                    $(this).select2('destroy');
                }
                
                $(this).select2({
                    theme: 'bootstrap4',
                    width: '100%',
                    placeholder: $(this).data('placeholder') || 'Select an option',
                    allowClear: false
                });
            });
        }
    });
})(window.jQuery || jQuery);
</script>

<script src="assets/js/generate-result.js"></script>

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