<?php
session_name('super_admin_session');
if (!is_dir(dirname(__DIR__) . '/session_data/super')) {
    mkdir(dirname(__DIR__) . '/session_data/super', 0700, true);
}
session_save_path(dirname(__DIR__) . '/session_data/super');
session_set_cookie_params(['path' => '/', 'httponly' => true, 'samesite' => 'Strict']);
session_start();
error_reporting(0);
include('includes/dbconnection.php');
require_once __DIR__ . '/includes/session_term_helper.php';
// Fetch current session and term (with gap/fallback support)
$stResult = resolveCurrentSessionTerm($con);
$currentSessionId   = $stResult['session_id'];
$currentSessionName = $stResult['session_name'];
$currentTermId      = $stResult['term_id'];
$currentTermName    = $stResult['term_name'];
include('includes/flash.php');

if (!isset($_SESSION['sid'])) {
    header('location:logout.php');
    exit();
}

// CSRF token setup
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Input filters
$class = isset($_POST['class']) ? htmlspecialchars(trim($_POST['class'])) : '';
$section = isset($_POST['section']) ? htmlspecialchars(trim($_POST['section'])) : '';
$resultType = $_POST['result_type'] ?? 'Endterm';

// Switch table + status field
$resultsTable = ($resultType === 'Midterm') ? 'result2' : 'results';
$statusField = ($resultType === 'Midterm') ? 'status_test' : 'status';

// Handle approval (single student)
if (isset($_POST['approve_one']) && !empty($_POST['approve_student_id'])) {
    $studentId = (int) $_POST['approve_student_id'];

    $approveStmt = $con->prepare("
        UPDATE $resultsTable 
        SET $statusField = 'Approved' 
        WHERE student_id = ? 
          AND class = ? AND section = ? 
          AND session_id = ? AND term_id = ?
    ");
    $approveStmt->bind_param("issii", $studentId, $class, $section, $currentSessionId, $currentTermId);

    if ($approveStmt->execute()) {
        $success = "Student result approved successfully.";
    } else {
        $error = "Failed to approve student result.";
    }

    flash_alert(isset($success) ? $success : $error, 'approve_result.php?class=' . urlencode($class) . '&section=' . urlencode($section));
    header('Location: approve_result.php?class=' . urlencode($class) . '&section=' . urlencode($section));
    exit;
}

// Handle approval (all students)
if (isset($_POST['approve_all'])) {
    $check = $con->prepare("
        SELECT COUNT(*) as count 
        FROM $resultsTable 
        WHERE class = ? AND section = ? 
          AND session_id = ? AND term_id = ? 
          AND $statusField = 'Submitted to Admin'
    ");
    $check->bind_param("ssii", $class, $section, $currentSessionId, $currentTermId);

    $check->execute();
    $res = $check->get_result()->fetch_assoc();

    if ($res['count'] > 0) {
        $update = $con->prepare("
            UPDATE $resultsTable 
            SET $statusField = 'Approved' 
            WHERE class = ? AND section = ? 
              AND session_id = ? AND term_id = ? 
              AND $statusField = 'Submitted to Admin'
        ");
        $update->bind_param("ssii", $class, $section, $currentSessionId, $currentTermId);

        if ($update->execute()) {
            $success = "Results for $class - $section successfully approved and locked.";
        } else {
            $error = "There was an error while approving the results.";
        }
    } else {
        $error = "No eligible results found for approval in the selected class and section.";
    }

    flash_alert(isset($success) ? $success : $error, 'approve_result.php');
    header('Location: approve_result.php');
    exit;
}

// Fetch students only if class and section are selected
$students = [];
if (!empty($class) && !empty($section)) {
    $query = "
        SELECT r.student_id, 
               s.studentName,
               SUM(r.total_score) AS total_score, 
               SUM(
                   IFNULL(r.test_score, 0) + 
                   IFNULL(r.test_score2, 0) + 
                   IFNULL(r.class_performance, 0) + 
                   IFNULL(r.weekly_assessment, 0)
               ) AS total_test,
               MAX(r.remarks) AS remarks,
               MAX(r.remarks_test) AS remarks_test,
               MAX(r.$statusField) AS status
        FROM $resultsTable r 
        JOIN students s ON r.student_id = s.id 
        WHERE r.session_id = ? AND r.term_id = ? 
          AND r.class = ? AND r.section = ? 
          AND r.$statusField = 'Submitted to Admin'
          AND s.status < 3
        GROUP BY r.student_id, s.studentName
    ";
    $stmt = $con->prepare($query);
    $stmt->bind_param("iiss", $currentSessionId, $currentTermId, $class, $section);

    $stmt->execute();
    $result = $stmt->get_result();
    $students = $result->fetch_all(MYSQLI_ASSOC);
}


// Result Notification test
$notifQueryt = "
    SELECT r.class, r.section, COUNT(DISTINCT student_id) as student_count
    FROM result2 r
    INNER JOIN students s ON s.id = r.student_id
    WHERE r.session_id = ? AND r.term_id = ? 
      AND r.status_test = 'Submitted to Admin'
      AND s.status < 3
    GROUP BY r.class, r.section
";
$notifStmtt = $con->prepare($notifQueryt);
$notifStmtt->bind_param("ii", $currentSessionId, $currentTermId);

$notifStmtt->execute();
$notifResultt = $notifStmtt->get_result();
$pendingResultstest = $notifResultt->fetch_all(MYSQLI_ASSOC);

// Result Notification Exam
$notifQuery = "
    SELECT r.class, r.section, COUNT(DISTINCT student_id) as student_count
    FROM results r
    INNER JOIN students s ON s.id = r.student_id
    WHERE r.session_id = ? AND r.term_id = ? 
      AND r.status = 'Submitted to Admin'
      AND s.status < 3
    GROUP BY r.class, r.section
";
$notifStmt = $con->prepare($notifQuery);
$notifStmt->bind_param("ii", $currentSessionId, $currentTermId);

$notifStmt->execute();
$notifResult = $notifStmt->get_result();
$pendingResults = $notifResult->fetch_all(MYSQLI_ASSOC);

// Count TOTAL submitted + approved Midterm results
$midtermTotalStmt = $con->prepare("
    SELECT COUNT(*) AS total 
    FROM result2 r
    INNER JOIN students s ON s.id = r.student_id
    WHERE r.session_id = ? AND r.term_id = ?
      AND r.status_test IN ('Submitted to Admin','Approved')
      AND s.status < 3
");
$midtermTotalStmt->bind_param("ii", $currentSessionId, $currentTermId);
$midtermTotalStmt->execute();
$midtermTotal = $midtermTotalStmt->get_result()->fetch_assoc()['total'] ?? 0;

// Count TOTAL submitted + approved Exam results
$examTotalStmt = $con->prepare("
    SELECT COUNT(*) AS total 
    FROM results r
    INNER JOIN students s ON s.id = r.student_id
    WHERE r.session_id = ? AND r.term_id = ?
      AND r.status IN ('Submitted to Admin','Approved')
      AND s.status < 3
");
$examTotalStmt->bind_param("ii", $currentSessionId, $currentTermId);
$examTotalStmt->execute();
$examTotal = $examTotalStmt->get_result()->fetch_assoc()['total'] ?? 0;


// Pending Midterm results (already have this)
$pendingMidterm = $pendingResultstest;  // array

// Pending Exam results (already have this)
$pendingExam = $pendingResults;         // array
?>


<!DOCTYPE html>
<html>
<?php @include("includes/head.php"); ?>
<style>
    .dashboard-header {
        font-size: 1.4rem;
        font-weight: bold;
        text-align: center;
        margin-bottom: 15px;
    }

    .card {
        border-radius: 10px;
        transition: 0.3s ease-in-out;
    }

    .card:hover {
        transform: translateY(-3px);
    }

    .card-header {
        font-size: 1.2rem;
        font-weight: bold;
    }

    .bg-review {
        background-color: #17a2b8 !important;
        color: white !important;
    }

    .table thead {
        background-color: #f8f9fa;
        font-weight: bold;
    }
</style>

<body class="hold-transition sidebar-mini layout-fixed">
    <div class="wrapper">
        <?php @include("includes/header.php"); ?>
        <?php @include("includes/sidebar.php"); ?>

        <div class="content-wrapper">
            <section class="content-header premium-header">
                <div class="container-fluid">
                    <div class="header-glass-card">
                        <div class="row align-items-center">
                            <div class="col-md-8">
                                <div class="title-section">
                                    <div class="icon-box bg-primary-gradient shadow-sm">
                                        <i class="fas fa-clipboard-list"></i>
                                    </div>
                                    <div>
                                        <h1 class="premium-title text-primary">
                                            Result Management
                                            <span class="premium-subtitle text-secondary">Approve Result -
                                                <?= htmlspecialchars($currentTermName) ?>
                                                (<?= htmlspecialchars($currentSessionName) ?>)</span>
                                        </h1>
                            <div class="mt-1">
                              <?php if ($currentSessionName): ?>
                                <span class="badge badge-primary mr-1">
                                  <i class="fas fa-calendar-alt"></i>
                                  <?= htmlspecialchars($currentSessionName) ?>
                                </span>
                              <?php endif; ?>
                              <?php if ($currentTermName): ?>
                                <span class="badge badge-success">
                                  <i class="fas fa-bookmark"></i>
                                  <?= htmlspecialchars($currentTermName) ?>
                                </span>
                              <?php else: ?>
                                <span class="badge badge-warning">
                                  <i class="fas fa-exclamation-triangle"></i> No active term
                                </span>
                              <?php endif; ?>
                            </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <nav aria-label="breadcrumb">
                                    <ol class="breadcrumb premium-breadcrumb">
                                        <li class="breadcrumb-item"><a href="dashboard.php"
                                                class="text-primary">Home</a></li>
                                        <li class="breadcrumb-item active" aria-current="page">Approve Result</li>
                                    </ol>
                                </nav>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
            <?php if (!empty($pendingResultstest)): ?>
                <section class="content">
                    <div class="container-fluid">
                        <div class="card shadow-sm border-0">
                            <div class="card-header bg-primary text-white">
                                <h3 class="card-title font-weight-bold">
                                    <i class="fas fa-bell"></i> Mid Term Results Awaiting Approval
                                </h3>
                                <div class="card-tools">
                                    <a href="approval_tracking.php">
                                        <button type="button" class="btn btn-sm btn-primary">
                                            <i class="fas fa-tasks"></i> Track Approval Status
                                        </button>
                                    </a>
                                </div>
                            </div>
                            <div class="card-body">
                                <table id="example1" class="table table-bordered table-hover table-striped">
                                    <thead>
                                        <tr>
                                            <th>#</th>
                                            <th>Class - Arm</th>
                                            <th>Students Submitted</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php $counter = 1;
                                        foreach ($pendingResultstest as $res): ?>
                                            <tr>
                                                <td><?= $counter++ ?></td>
                                                <td>
                                                    <a
                                                        href="approve_result.php?class=<?= urlencode($res['class']) ?>&section=<?= urlencode($res['section']) ?>">
                                                        <strong><?= htmlspecialchars($res['class']) ?> -
                                                            <?= htmlspecialchars($res['section']) ?></strong>
                                                    </a>
                                                </td>
                                                <td><?= $res['student_count'] ?> students submitted</td>
                                                <td>
                                                    <form method="post" style="display:inline-block;">
                                                        <input type="hidden" name="class" value="<?= $res['class']; ?>">
                                                        <input type="hidden" name="section" value="<?= $res['section']; ?>">
                                                        <input type="hidden" name="result_type" value="<?= 'Midterm'; ?>">
                                                        <button type="submit" name="submit" class="btn btn-info btn-xs">
                                                            <i class="fas fa-eye"></i> View Results
                                                        </button>
                                                    </form>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </section>
            <?php endif; ?>


            <?php if (!empty($pendingResults)): ?>
                <section class="content">
                    <div class="container-fluid">
                        <div class="card shadow-sm border-0">
                            <div class="card-header bg-primary text-white">
                                <h3 class="card-title font-weight-bold">
                                    <i class="fas fa-bell"></i> End of Term Results Awaiting Approval
                                </h3>
                                <div class="card-tools">
                                    <a href="approval_tracking.php">
                                        <button type="button" class="btn btn-sm btn-primary">
                                            <i class="fas fa-tasks"></i> Track Approval Status
                                        </button>
                                    </a>
                                </div>
                            </div>
                            <div class="card-body">
                                <table id="example1" class="table table-bordered table-hover table-striped">
                                    <thead>
                                        <tr>
                                            <th>#</th>
                                            <th>Class - Arm</th>
                                            <th>Students Submitted</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php $counter = 1;
                                        foreach ($pendingResults as $res): ?>
                                            <tr>
                                                <td><?= $counter++ ?></td>
                                                <td>
                                                    <a
                                                        href="approve_result.php?class=<?= urlencode($res['class']) ?>&section=<?= urlencode($res['section']) ?>">
                                                        <strong><?= htmlspecialchars($res['class']) ?> -
                                                            <?= htmlspecialchars($res['section']) ?></strong>
                                                    </a>
                                                </td>
                                                <td><?= $res['student_count'] ?> students submitted</td>
                                                <td>
                                                    <form method="post" style="display:inline-block;">
                                                        <input type="hidden" name="class" value="<?= $res['class']; ?>">
                                                        <input type="hidden" name="section" value="<?= $res['section']; ?>">
                                                        <input type="hidden" name="result_type" value="<?= 'Endterm'; ?>">
                                                        <button type="submit" name="submit" class="btn btn-info btn-xs">
                                                            <i class="fas fa-eye"></i> View Results
                                                        </button>
                                                    </form>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </section>
            <?php endif; ?>





            <section class="content">
                <div class="container-fluid">
                    <?php if (isset($success)): ?>
                        <div class="alert alert-success"><?= $success; ?></div>
                    <?php elseif (isset($error)): ?>
                        <div class="alert alert-danger"><?= $error; ?></div>
                    <?php endif; ?>

                    <div class="card shadow-sm border-0">
                        <div class="card-header bg-primary text-white">
                            <h3 class="card-title font-weight-bold"><i class="fas fa-clipboard-list"></i> Approve
                                Students' Result</h3>
                            <div class="card-tools">
                                <a href="approval_tracking.php">
                                    <button type="button" class="btn btn-sm btn-primary">
                                        <i class="fas fa-tasks"></i> Track Approval Status
                                    </button>
                                </a>
                            </div>
                        </div>

                        <div class="card-body">
                            <form method="POST">
                                <div class="row p-0 m-0">
                                    <div class="form-group col-md-4">
                                        <label>Class:</label>
                                        <select id="classSelector" name="class" class="form-control select2" required>
                                            <option value="">Select Class</option>
                                            <?php
                                            $classResult = $con->query("SELECT DISTINCT class FROM class_section ORDER BY class");
                                            while ($row = $classResult->fetch_assoc()) {
                                                $selected = ($row['class'] == $class) ? "selected" : "";
                                                echo "<option value='{$row['class']}' $selected>{$row['class']}</option>";
                                            }
                                            ?>
                                        </select>
                                    </div>

                                    <div class="form-group col-md-4">
                                        <label>Arm:</label>
                                        <select id="sectionSelector" name="section" class="form-control select2"
                                            required>
                                            <option value="">Select Arm</option>
                                            <?php
                                            if (!empty($class)) {
                                                $secRes = $con->query("SELECT DISTINCT section FROM class_section WHERE class = '$class'");
                                                while ($sec = $secRes->fetch_assoc()) {
                                                    $selected = ($sec['section'] == $section) ? "selected" : "";
                                                    echo "<option value='{$sec['section']}' $selected>{$sec['section']}</option>";
                                                }
                                            }
                                            ?>
                                        </select>
                                    </div>
                                    <div class="form-group col-md-4">
                                        <label>Result Type:</label>
                                        <select name="result_type" class="form-control select2" required>
                                            <option value="Endterm" <?= (($_POST['result_type'] ?? '') == 'Endterm') ? 'selected' : '' ?>>End of Term</option>
                                            <option value="Midterm" <?= (($_POST['result_type'] ?? '') == 'Midterm') ? 'selected' : '' ?>>Mid Term</option>
                                        </select>
                                    </div>
                                    <div class="form-group col-md-12 text-center">
                                        <button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> Load
                                            Results</button>
                                    </div>
                                </div>

                                <?php if (!empty($students)): ?>
                                    <table class="table table-bordered table-hover table-striped">
                                        <thead>
                                            <tr>
                                                <th>#</th>
                                                <th>Student Name</th>
                                                <th>Total Score</th>
                                                <th>Remarks</th>
                                                <th>Action</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php $sn = 1;
                                            foreach ($students as $student): ?>
                                                <tr>
                                                    <td><?= $sn++; ?></td>
                                                    <td><?= htmlspecialchars($student['studentName']); ?></td>

                                                    <?php if ($resultType === 'Midterm'): ?>
                                                        <td><?= htmlspecialchars($student['total_test']); ?></td>
                                                        <td><?= htmlspecialchars($student['remarks_test']); ?></td>
                                                    <?php else: ?>
                                                        <td><?= htmlspecialchars($student['total_score']); ?></td>
                                                        <td><?= htmlspecialchars($student['remarks']); ?></td>
                                                    <?php endif; ?>

                                                    <td>
                                                        <?php if ($student[$statusField] === 'Approved'): ?>
                                                            <button class="btn btn-secondary btn-xs" disabled>Approved</button>
                                                        <?php else: ?>
                                                            <form method="post" style="display:inline-block;">
                                                                <input type="hidden" name="approve_student_id"
                                                                    value="<?= $student['student_id']; ?>">
                                                                <input type="hidden" name="class" value="<?= $class; ?>">
                                                                <input type="hidden" name="section" value="<?= $section; ?>">
                                                                <input type="hidden" name="result_type" value="<?= $resultType; ?>">
                                                                <button type="submit" name="approve_one"
                                                                    class="btn btn-success btn-xs">
                                                                    <i class="fas fa-check-circle"></i> Approve
                                                                </button>
                                                            </form>
                                                        <?php endif; ?>

                                                        <button type="button" class="btn btn-primary btn-xs viewResultBtn"
                                                            data-student="<?= $student['student_id']; ?>"
                                                            data-name="<?= htmlspecialchars($student['studentName']); ?>">
                                                            <i class="fas fa-eye"></i> View Result
                                                        </button>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>

                                        </tbody>
                                    </table>
                                    <div class="text-center">
                                        <button type="submit" name="approve_all" class="btn btn-success mt-3">
                                            <i class="fas fa-check-circle"></i> Approve All & Lock
                                        </button>
                                    </div>
                                <?php elseif (!empty($class) && !empty($section)): ?>
                                    <p class="text-muted" style="color: red;">No results found for the selected class and
                                        arm.</p>
                                <?php else: ?>
                                    <p class="text-muted">Select class and arm to view and approve result.</p>
                                <?php endif; ?>
                            </form>
                        </div>
                    </div>
                </div>
            </section>
            <?php
            // Check if there are any results at all (either midterm or exam) for this session/term
            $totalResultsQuery = "
    SELECT COUNT(*) 
    FROM (
        SELECT student_id FROM result2 WHERE session_id=? AND term_id=?
        UNION ALL
        SELECT student_id FROM results WHERE session_id=? AND term_id=?
    ) AS all_results
";
            $totalStmt = $con->prepare($totalResultsQuery);
            $totalStmt->bind_param("iiii", $currentSessionId, $currentTermId, $currentSessionId, $currentTermId);
            $totalStmt->execute();
            $totalStmt->bind_result($totalResults);
            $totalStmt->fetch();
            $totalStmt->close();
            ?>

            <?php
            $midtermPendingCount = count($pendingResultstest);
            ?>
            <?php if ($midtermTotal == 0): ?>
                <div class="alert alert-info text-center">
                    <i class="fas fa-info-circle"></i> No midterm results submitted yet.
                </div>

            <?php elseif ($midtermPendingCount > 0): ?>
                <div class="alert alert-warning text-center">
                    <i class="fas fa-exclamation-circle"></i> Some midterm results are awaiting approval.
                </div>

            <?php else: ?>
                <div class="alert alert-primary text-center">
                    <i class="fas fa-check-circle"></i> All midterm results have been approved.
                </div>
            <?php endif; ?>

            <?php
            $examPendingCount = count($pendingResults);
            ?>
            <?php if ($examTotal == 0): ?>
                <div class="alert alert-info text-center">
                    <i class="fas fa-info-circle"></i> No exam results submitted yet.
                </div>

            <?php elseif ($examPendingCount > 0): ?>
                <div class="alert alert-warning text-center">
                    <i class="fas fa-exclamation-circle"></i> Some exam results are awaiting approval.
                </div>

            <?php else: ?>
                <div class="alert alert-primary text-center">
                    <i class="fas fa-check-circle"></i> All exam results have been approved.
                </div>
            <?php endif; ?>

        </div>

        <?php @include("includes/footer.php"); ?>
    </div>
    <?php @include("includes/foot.php"); ?>
    <script>
        // Use window.load to ensure select2.min.js is fully parsed before init
        $(window).on('load', function () {
            if (typeof $.fn.select2 === 'undefined') {
                console.error('Select2 not loaded');
                return;
            }
            $('.select2').select2();

            $('#classSelector').on('change', function () {
                var selectedClass = $(this).val();
                if (selectedClass) {
                    $.ajax({
                        url: 'fetch_sections.php',
                        type: 'POST',
                        data: { class_name: selectedClass },
                        success: function (response) {
                            $('#sectionSelector').html(response);
                            $('#sectionSelector').trigger('change.select2');
                        }
                    });
                } else {
                    $('#sectionSelector').html('<option value="">Select Arm</option>');
                    $('#sectionSelector').trigger('change.select2');
                }
            });
        });

        $(document).on('click', '.viewResultBtn', function (e) {
            e.preventDefault();
            var studentId = $(this).data('student');
            var studentName = $(this).data('name');

            $('#modalStudentName').text(studentName);
            $('#modalResultContent').html('<p class="text-center">Loading...</p>');

            $.ajax({
                url: 'fetch_student_subject_results.php',
                method: 'POST',
                data: {
                    student_id: studentId,
                    session_id: <?= (int) $currentSessionId ?>,
                    term_id: <?= (int) $currentTermId ?>,
                    result_type: "<?= $resultType ?>"
                },
                success: function (data) {
                    $('#modalResultContent').html(data);
                }
            });


            if ($('#viewResultModal').hasClass('show')) {
                $('#viewResultModal').modal('hide');
            }

            $('#viewResultModal').modal('show');
        });
    </script>

    <!-- Modal -->
    <div class="modal fade" id="viewResultModal" tabindex="-1" role="dialog" aria-labelledby="viewResultModalLabel"
        aria-hidden="true">
        <div class="modal-dialog modal-xl modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header bg-info text-white">
                    <h5 class="modal-title" id="viewResultModalLabel">Student Result - <span
                            id="modalStudentName"></span></h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body" id="modalResultContent">
                    <p class="text-center">Loading...</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
</body>

</html>