<?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'];
error_reporting(0);

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


// Fetch current session and term
// Fetch active session ordered by earliest start_date
$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;
}

// Fetch the current term
$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'];
$currentTermName = $termRow['term_name'];


$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'];
    $subject = $_POST['subject'];
    $result_type = $_POST['result_type'];


    if ($result_type === 'Endterm') {

        $query = "SELECT r.id, r.student_id, r.subject, r.test_score, r.test_score2, r.weekly_assessment, r.class_performance, r.exam_score, r.total_score, r.remarks, s.studentName,
        r.test_absent, r.test2_absent, r.class_performance_absent, r.weekly_assessment_absent, r.exam_absent
              FROM results 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 r.subject = ? AND r.status = 'Approved'";

        $stmt = $con->prepare($query);
        $stmt->bind_param("ssiis", $class, $section, $term, $session, $subject);
        $stmt->execute();
        $result = $stmt->get_result();
    } else {
        $query = "SELECT r.id, r.student_id, r.subject, r.test_score, r.test_score2, r.weekly_assessment, r.class_performance, r.exam_score, r.total_score, r.remarks_test, s.studentName,
        r.test_absent, r.test2_absent, r.class_performance_absent, r.weekly_assessment_absent, r.exam_absent
              FROM result2 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 r.subject = ? AND r.status_test = 'Approved'";

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

?>

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

    .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">View 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">Previous 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-file-alt"></i> View 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-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 ($row3 = $classResult->fetch_assoc()) {
                                                $selected = ($row3['class'] == $class) ? "selected" : "";
                                                echo "<option value='{$row3['class']}' $selected>{$row3['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>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 ($row2 = $sessionResult->fetch_assoc()) {
                                                $selected = ($row2['id'] == $session) ? "selected" : "";
                                                echo "<option value='{$row2['id']}' $selected>{$row2['session_name']}</option>";
                                            }
                                            ?>
                                        </select>
                                    </div>

                                    <div class="form-group col-md-4">
                                        <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>Subject:</label>
                                        <select id="subject" name="subject" class="form-control select2" required>
                                            <option value="">Select Subject</option>
                                            <?php
                                            $query = "SELECT name FROM subject_name ORDER BY name DESC";
                                            $stmt1 = $con->prepare($query);
                                            $stmt1->execute();
                                            $result1 = $stmt1->get_result();
                                            while ($row1 = $result1->fetch_assoc()) {
                                                echo "<option value='{$row1['name']}'>{$row1['name']}</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="">---Select Result Type---</option>
                                            <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-file-alt"></i> <?= htmlspecialchars($_POST['subject']) ?> Result for
                                    <?= htmlspecialchars($_POST['class']) ?> - <?= htmlspecialchars($_POST['section']) ?>
                                </h3>
                            </div>

                            <div class="card-body">

                                <table id="example11" class="table table-bordered table-hover table-striped">
                                    <thead>
                                        <tr>
                                            <th>#</th>
                                            <th>Student Name</th>
                                            <?php if ($result_type === 'Midterm'): ?>
                                                <th>1st C.A. Test (10)</th>
                                                <th>2nd C.A. Test (10)</th>
                                                <th>Ex. & Projects (5)</th>
                                                <th>Assignment (5)</th>
                                                <th>Total (30)</th>
                                            <?php else: ?>
                                                <th>C.A. Test (10)</th>
                                                <th>Ex. & Projects (15)</th>
                                                <th>Assignment (5)</th>
                                                <th>Exam (70)</th>
                                                <th>Total (100)</th>
                                            <?php endif; ?>
                                        </tr>
                                    </thead>

                                    <tbody>
                                        <?php $sn = 1; ?>
                                        <?php while ($row = $result->fetch_assoc()): ?>
                                            <?php
                                            // Handle scores safely
                                            $test_score = ($row['test_absent'] == "1") ? 'AB' : (int) $row['test_score'];
                                            $test_score2 = ($row['test2_absent'] == "1") ? 'AB' : (int) $row['test_score2'];
                                            $class_performance = ($row['class_performance_absent'] == "1") ? 'AB' : (int) $row['class_performance'];
                                            $weekly_assessment = ($row['weekly_assessment_absent'] == "1") ? 'AB' : (int) $row['weekly_assessment'];
                                            $exam = ($row['exam_absent'] == "1") ? 'AB' : (int) $row['exam_score'];

                                            // Total for Endterm
                                            $scores_exam = [$test_score, $class_performance, $weekly_assessment, $exam];
                                            $numeric_scores_exam = array_filter($scores_exam, 'is_numeric');
                                            $total_exam = count($numeric_scores_exam) ? array_sum($numeric_scores_exam) : 'AB';

                                            // Total for Midterm
                                            $scores_test = [$test_score, $test_score2, $class_performance, $weekly_assessment];
                                            $numeric_scores_test = array_filter($scores_test, 'is_numeric');
                                            $total_test = count($numeric_scores_test) ? array_sum($numeric_scores_test) : 'AB';
                                            ?>
                                            <tr>
                                                <td><?= $sn++ ?></td>
                                                <td><?= htmlspecialchars($row['studentName']) ?></td>

                                                <?php if ($result_type === 'Midterm'): ?>
                                                    <td><?= $test_score ?></td>
                                                    <td><?= $test_score2 ?></td>
                                                    <td><?= $class_performance ?></td>
                                                    <td><?= $weekly_assessment ?></td>
                                                    <td><?= $total_test ?></td>
                                                <?php else: ?>
                                                    <td><?= $test_score ?></td>
                                                    <td><?= $class_performance ?></td>
                                                    <td><?= $weekly_assessment ?></td>
                                                    <td><?= $exam ?></td>
                                                    <td><?= $total_exam ?></td>
                                                <?php endif; ?>
                                            </tr>
                                        <?php endwhile; ?>
                                    </tbody>

                                </table>
                            </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>
        <!-- Footer -->
        <?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>
</body>

</html>