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

// Fetch current session and term
$currentSessionQuery = "
    SELECT id, session_name 
    FROM school_sessions 
    WHERE start_date <= CURDATE() 
      AND end_date >= CURDATE() 
    ORDER BY start_date ASC 
    LIMIT 1";
$currentSessionResult = $con->query($currentSessionQuery);

if ($currentSessionResult && $currentSessionResult->num_rows > 0) {
    $currentSession = $currentSessionResult->fetch_assoc();
    $currentSessionId = $currentSession['id'];
    $currentSessionName = $currentSession['session_name'];
} else {
    $currentSessionId = null;
    $currentSessionName = null;
}

$termQuery = "SELECT id, term_name FROM school_terms WHERE session_id = '$currentSessionId'
              AND start_date <= CURDATE() 
              AND end_date >= CURDATE() 
              ORDER BY start_date ASC 
              LIMIT 1";
$termResult = mysqli_query($con, $termQuery);
$termRow = mysqli_fetch_assoc($termResult);
$currentTermId = $termRow['id'] ?? null;
$currentTermName = $termRow['term_name'] ?? null;

$result = null; // Default

// Handle filter form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['view_result'])) {
    $class = $_POST['class'];
    $section = $_POST['section'];
    $term = $_POST['term'];
    $session = $_POST['session'];
    $result_type = $_POST['result_type'];

    // Pick the correct table and remarks column
    $table = ($result_type === 'Midterm') ? 'result2' : 'results';
    $remarksCol = ($result_type === 'Midterm') ? 'r.remarks_test' : 'r.remarks';
    $statusCol = ($result_type === 'Midterm') ? 'r.status_test' : 'r.status';


    $query = "SELECT r.id, r.student_id, r.subject, r.test_score, r.weekly_assessment, 
                     r.class_performance, r.exam_score, r.total_score, $remarksCol AS remarks, 
                     r.test_score2, r.test_absent, r.test2_absent, r.class_performance_absent,
                     r.exam_absent, r.weekly_assessment_absent, s.studentName 
              FROM $table r 
              INNER JOIN students s ON r.student_id = s.id 
              WHERE r.class = ? AND r.section = ? AND r.term_id = ? 
                AND r.session_id = ?"; //AND $statusCol = 'Approved'";

    $stmt = $con->prepare($query);
    $stmt->bind_param("ssii", $class, $section, $term, $session);
    $stmt->execute();
    $result = $stmt->get_result();
}

// Handle result save
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_result'])) {
    $result_type = $_POST['result_type'];
    $table = ($result_type === 'Midterm') ? 'result2' : 'results';
    $remarksCol = ($result_type === 'Midterm') ? 'remarks_test' : 'remarks';

    foreach ($_POST['test_score'] as $id => $test1) {
        // Absent flags
        $test_absent = isset($_POST['test_absent'][$id]) ? 1 : 0;
        $test2_absent = isset($_POST['test2_absent'][$id]) ? 1 : 0;
        $class_absent = isset($_POST['class_performance_absent'][$id]) ? 1 : 0;
        $weekly_absent = isset($_POST['weekly_assessment_absent'][$id]) ? 1 : 0;
        $exam_absent = isset($_POST['exam_absent'][$id]) ? 1 : 0;

        // Scores (null if absent)
        $test1 = $test_absent ? null : $test1;
        $test2 = $test2_absent ? null : ($_POST['test_score2'][$id] ?? null);
        $test3 = $class_absent ? null : ($_POST['class_performance'][$id] ?? null);
        $test4 = $weekly_absent ? null : ($_POST['weekly_assessment'][$id] ?? null);
        $exam = $exam_absent ? null : ($_POST['exam_score'][$id] ?? null);

        $remarks = $_POST['remarks'][$id] ?? '';

        // Calculate total
        if ($result_type === 'Midterm') {
            $total = (int) $test1 + (int) $test2 + (int) $test3 + (int) $test4;
        } else {
            $total = (int) $test1 + (int) $test2 + (int) $test3 + (int) $test4 + (int) $exam;
        }

        $updateQuery = "UPDATE $table 
    SET test_score = ?, test_score2 = ?, class_performance = ?, 
        weekly_assessment = ?, exam_score = ?, 
        $remarksCol = ?, 
        test_absent=?, test2_absent=?, class_performance_absent=?, 
        weekly_assessment_absent=?, exam_absent=? 
    WHERE id = ?";

        $updateStmt = $con->prepare($updateQuery);
        $updateStmt->bind_param(
            "iiiiisiiiiii",
            $test1,
            $test2,
            $test3,
            $test4,
            $exam,
            $remarks,
            $test_absent,
            $test2_absent,
            $class_absent,
            $weekly_absent,
            $exam_absent,
            $id
        );


        $updateStmt->execute();
    }


    flash_alert('Results updated successfully.');
    header('Location: edit_result.php');
    exit;
    exit;
}

?>

<!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">Edit Result</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="teacher_dashboard.php"
                                                class="text-primary">Home</a></li>
                                        <li class="breadcrumb-item active" aria-current="page">Edit Result</li>
                                    </ol>
                                </nav>
                            </div>
                        </div>
                    </div>
                </div>
            </section>

            <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-edit"></i> Edit Students' Result
                            </h3>
                        </div>

                        <div class="card-body">
                            <!-- Class/Section Selection Form -->
                            <form method="POST" action="">
                                <div class="row p-0 m-0">
                                    <div class="form-group col-md-6">
                                        <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'] == ($_POST['class'] ?? '')) ? "selected" : "";
                                                echo "<option value='{$row['class']}' $selected>{$row['class']}</option>";
                                            }
                                            ?>
                                        </select>
                                    </div>

                                    <div class="form-group col-md-6">
                                        <label>Arm:</label>
                                        <select id="sectionSelector" name="section" class="form-control select2"
                                            required>
                                            <option value="">Select Arm</option>
                                            <?php
                                            if (!empty($_POST['class'])) {
                                                $classSel = $_POST['class'];
                                                $secRes = $con->query("SELECT DISTINCT section FROM class_section WHERE class = '$classSel'");
                                                while ($sec = $secRes->fetch_assoc()) {
                                                    $selected = ($sec['section'] == ($_POST['section'] ?? '')) ? "selected" : "";
                                                    echo "<option value='{$sec['section']}' $selected>{$sec['section']}</option>";
                                                }
                                            }
                                            ?>
                                        </select>
                                    </div>

                                    <div class="form-group col-md-6">
                                        <label>Session:</label>
                                        <select id="sessionSelector" name="session" class="form-control select2"
                                            required>
                                            <option value="">Select Session</option>
                                            <?php
                                            $sessionResult = $con->query("SELECT DISTINCT id, session_name FROM school_sessions ORDER BY session_name DESC");
                                            while ($row = $sessionResult->fetch_assoc()) {
                                                $selected = ($row['id'] == ($_POST['session'] ?? '')) ? "selected" : "";
                                                echo "<option value='{$row['id']}' $selected>{$row['session_name']}</option>";
                                            }
                                            ?>
                                        </select>
                                    </div>

                                    <div class="form-group col-md-6">
                                        <label>Term:</label>
                                        <select id="termSelector" name="term" class="form-control select2" required>
                                            <option value="">Select Term</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 mt-3">
                                        <button type="submit" class="btn btn-primary" name="view_result"><i
                                                class="fas fa-eye"></i> View Results</button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </section>

            <!-- Results Table -->
            <?php if (isset($_POST['view_result']) && $result && $result->num_rows > 0): ?>
                <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-edit"></i> Edit Students' Result for
                                    <?= htmlspecialchars($_POST['class']) ?> - <?= htmlspecialchars($_POST['section']) ?>
                                </h3>
                            </div>

                            <div class="card-body">
                                <form method="POST">
                                    <input type="hidden" name="class" value="<?= htmlspecialchars($_POST['class']) ?>">
                                    <input type="hidden" name="section" value="<?= htmlspecialchars($_POST['section']) ?>">
                                    <input type="hidden" name="term" value="<?= htmlspecialchars($_POST['term']) ?>">
                                    <input type="hidden" name="session" value="<?= htmlspecialchars($_POST['session']) ?>">
                                    <input type="hidden" name="result_type"
                                        value="<?= htmlspecialchars($_POST['result_type']) ?>">

                                    <table id="example11" class="table table-bordered table-hover table-striped">
                                        <thead>
                                            <tr>
                                                <th>#</th>
                                                <th>Student</th>
                                                <th>Subject</th>
                                                <?php if (isset($_POST['result_type']) && $_POST['result_type'] === 'Midterm'): ?>
                                                    <th>1<sup>st</sup> C.A Test (10)</th>
                                                    <th>2<sup>nd</sup> C.A Test (10)</th>
                                                    <th>Class Ex. & Projects (5)</th>
                                                <?php else: ?>
                                                    <th>C.A Test (10)</th>
                                                    <th>Class Ex. & Projects (15)</th>
                                                <?php endif; ?>

                                                <th>Assignment (5)</th>

                                                <?php if (isset($_POST['result_type']) && $_POST['result_type'] === 'Midterm'): ?>
                                                    <th>Total (30)</th>
                                                <?php else: ?>
                                                    <th>Exam (70)</th>
                                                    <th>Total (100)</th>
                                                <?php endif; ?>
                                            </tr>

                                        </thead>
                                        <tbody>
                                            <?php $sn = 1; ?>
                                            <?php while ($row = $result->fetch_assoc()): ?>
                                                <tr>
                                                    <td><?= $sn++ ?></td>
                                                    <td><?= htmlspecialchars($row['studentName']) ?></td>
                                                    <td><?= htmlspecialchars($row['subject']) ?></td>

                                                    <?php if (isset($_POST['result_type']) && $_POST['result_type'] === 'Midterm'): ?>
                                                        <!-- 1st CA Test -->
                                                        <td>
                                                            <div class="input-group">
                                                                <input type="number" name="test_score[<?= $row['id'] ?>]"
                                                                    value="<?= htmlspecialchars($row['test_score']) ?>"
                                                                    class="form-control score-input" <?= $row['test_absent'] ? 'disabled' : '' ?>>
                                                                <div class="input-group-append">
                                                                    <div class="input-group-text">
                                                                        <input type="checkbox" name="test_absent[<?= $row['id'] ?>]"
                                                                            value="1" class="absent-toggle" <?= $row['test_absent'] ? 'checked' : '' ?>>
                                                                        <small>AB</small>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </td>

                                                        <!-- 2nd CA Test -->
                                                        <td>
                                                            <div class="input-group">
                                                                <input type="number" name="test_score2[<?= $row['id'] ?>]"
                                                                    value="<?= htmlspecialchars($row['test_score2']) ?>"
                                                                    class="form-control score-input" <?= $row['test2_absent'] ? 'disabled' : '' ?>>
                                                                <div class="input-group-append">
                                                                    <div class="input-group-text">
                                                                        <input type="checkbox"
                                                                            name="test2_absent[<?= $row['id'] ?>]" value="1"
                                                                            class="absent-toggle" <?= $row['test2_absent'] ? 'checked' : '' ?>>
                                                                        <small>AB</small>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </td>

                                                        <!-- Class Performance (5 marks for Midterm) -->
                                                        <td>
                                                            <div class="input-group">
                                                                <input type="number" name="class_performance[<?= $row['id'] ?>]"
                                                                    value="<?= htmlspecialchars($row['class_performance']) ?>"
                                                                    class="form-control score-input"
                                                                    <?= $row['class_performance_absent'] ? 'disabled' : '' ?>>
                                                                <div class="input-group-append">
                                                                    <div class="input-group-text">
                                                                        <input type="checkbox"
                                                                            name="class_performance_absent[<?= $row['id'] ?>]"
                                                                            value="1" class="absent-toggle"
                                                                            <?= $row['class_performance_absent'] ? 'checked' : '' ?>>
                                                                        <small>AB</small>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </td>
                                                    <?php else: ?>
                                                        <!-- Single CA Test (10 marks) -->
                                                        <td>
                                                            <div class="input-group">
                                                                <input type="number" name="test_score[<?= $row['id'] ?>]"
                                                                    value="<?= htmlspecialchars($row['test_score']) ?>"
                                                                    class="form-control score-input" <?= $row['test_absent'] ? 'disabled' : '' ?>>
                                                                <div class="input-group-append">
                                                                    <div class="input-group-text">
                                                                        <input type="checkbox" name="test_absent[<?= $row['id'] ?>]"
                                                                            value="1" class="absent-toggle" <?= $row['test_absent'] ? 'checked' : '' ?>>
                                                                        <small>AB</small>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </td>

                                                        <!-- Class Ex. & Projects (15 marks) -->
                                                        <td>
                                                            <div class="input-group">
                                                                <input type="number" name="class_performance[<?= $row['id'] ?>]"
                                                                    value="<?= htmlspecialchars($row['class_performance']) ?>"
                                                                    class="form-control score-input"
                                                                    <?= $row['class_performance_absent'] ? 'disabled' : '' ?>>
                                                                <div class="input-group-append">
                                                                    <div class="input-group-text">
                                                                        <input type="checkbox"
                                                                            name="class_performance_absent[<?= $row['id'] ?>]"
                                                                            value="1" class="absent-toggle"
                                                                            <?= $row['class_performance_absent'] ? 'checked' : '' ?>>
                                                                        <small>AB</small>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </td>
                                                    <?php endif; ?>

                                                    <!-- Assignment (5 marks, common to both types) -->
                                                    <td>
                                                        <div class="input-group">
                                                            <input type="number" name="weekly_assessment[<?= $row['id'] ?>]"
                                                                value="<?= htmlspecialchars($row['weekly_assessment']) ?>"
                                                                class="form-control score-input"
                                                                <?= $row['weekly_assessment_absent'] ? 'disabled' : '' ?>>
                                                            <div class="input-group-append">
                                                                <div class="input-group-text">
                                                                    <input type="checkbox"
                                                                        name="weekly_assessment_absent[<?= $row['id'] ?>]"
                                                                        value="1" class="absent-toggle"
                                                                        <?= $row['weekly_assessment_absent'] ? 'checked' : '' ?>>
                                                                    <small>AB</small>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </td>

                                                    <?php if (isset($_POST['result_type']) && $_POST['result_type'] === 'Midterm'): ?>
                                                        <!-- Total (30 marks) -->
                                                        <td><?= htmlspecialchars($row['total_score']) ?></td>
                                                    <?php else: ?>
                                                        <!-- Exam (70 marks) -->
                                                        <td>
                                                            <div class="input-group">
                                                                <input type="number" name="exam_score[<?= $row['id'] ?>]"
                                                                    value="<?= htmlspecialchars($row['exam_score']) ?>"
                                                                    class="form-control score-input" <?= $row['exam_absent'] ? 'disabled' : '' ?>>
                                                                <div class="input-group-append">
                                                                    <div class="input-group-text">
                                                                        <input type="checkbox" name="exam_absent[<?= $row['id'] ?>]"
                                                                            value="1" class="absent-toggle" <?= $row['exam_absent'] ? 'checked' : '' ?>>
                                                                        <small>AB</small>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </td>
                                                        <!-- Total (100 marks) -->
                                                        <td><?= htmlspecialchars($row['total_score']) ?></td>
                                                    <?php endif; ?>

                                                    <!-- Hidden Remarks -->
                                                    <input type="hidden" name="remarks[<?= $row['id'] ?>]"
                                                        value="<?= htmlspecialchars($row['remarks']) ?>" class="form-control">
                                                </tr>


                                            <?php endwhile; ?>
                                        </tbody>


                                    </table>

                                    <div class="text-center mt-3">
                                        <button type="submit" name="save_result" class="btn btn-primary"><i
                                                class="fas fa-save"></i> Save Changes</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </section>
            <?php elseif (isset($_POST['view_result'])): ?>
                <section class="content">
                    <div class="container-fluid">
                        <div class="card shadow-sm border-0">
                            <div class="card-body">
                                <div class="alert alert-warning mt-4">No results found for selected class.</div>
                            </div>
                        </div>
                    </div>
                </section>
            <?php endif; ?>
        </div>

        <?php @include("includes/footer.php"); ?>
        <?php @include("includes/foot.php"); ?>
    </div>
    <script src="dist/js/select2.min.js"></script>

    <script>
        $(document).ready(function () {
            $('.select2').select2();

            $('#classSelector').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);
                        }
                    });
                } else {
                    $('#sectionSelector').html('<option value="">Select Arm</option>');
                }
            });

            $('#sessionSelector').change(function () {
                var selectedClass = $(this).val();
                if (selectedClass) {
                    $.ajax({
                        url: 'fetch_session.php',
                        type: 'POST',
                        data: {
                            class_name: selectedClass
                        },
                        success: function (response) {
                            $('#termSelector').html(response);
                        }
                    });
                } else {
                    $('#termSelector').html('<option value="">Select Term</option>');
                }
            });
        });

        $(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 ?>
                },
                success: function (data) {
                    $('#modalResultContent').html(data);
                }
            });

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

            $('#viewResultModal').modal('show');
        });
    </script>
    <script>
        $(document).ready(function () {
            $(document).on('change', '.absent-toggle', function () {
                let input = $(this).closest('.input-group').find('.score-input');
                if ($(this).is(':checked')) {
                    input.val(''); // clear score
                    input.prop('disabled', true);
                } else {
                    input.prop('disabled', false);
                }
            });
        });
    </script>

</body>

</html>