<?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'];

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

// Fetch current session and term


if ($_SERVER["REQUEST_METHOD"] == "POST") {


    $session_id = $_POST['session_id'];  // Selected session
    $term_id = $_POST['term_id'];
    $class = $_POST['class'];  // Get the class from URL parameter
    $section = $_POST['section'];
    $result_type =$_POST['result_type'];


    $sessionRow = mysqli_fetch_assoc(mysqli_query($con, "SELECT id, session_name FROM school_sessions WHERE id = '$session_id' ORDER BY id DESC LIMIT 1"));
    $currentSessionId = $sessionRow['id'];
    $currentSessionName = $sessionRow['session_name'];

    $termRow = mysqli_fetch_assoc(mysqli_query($con, "SELECT id, term_name FROM school_terms WHERE id = $term_id AND session_id = '$currentSessionId' ORDER BY id DESC LIMIT 1"));
    $currentTermId = $termRow['id'];
    $currentTermName = $termRow['term_name'];


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

    // Fetch all subjects for this class
    $subject_stmt = $con->prepare("
    SELECT DISTINCT subject 
    FROM results 
    WHERE class = ? AND section = ? AND term_id = $currentTermId AND session_id = $currentSessionId
");
    $subject_stmt->bind_param("ss", $class, $section);
    $subject_stmt->execute();
    $subject_result = $subject_stmt->get_result();
    $subjects = $subject_result->fetch_all(MYSQLI_ASSOC);

    // Fetch results for each subject
    $results_by_subject = [];
    $result_type_by_subject = [];

    foreach ($subjects as $subject) {
        $subject_name = $subject['subject'];

        // First try fetching end-of-term results
        $end_stmt = $con->prepare("
        SELECT s.studentName, s.studentno, r.test_score, r.test_score2, r.class_performance, r.weekly_assessment, r.exam_score, r.total_score,
        r.test_absent, r.test2_absent, r.class_performance_absent, r.weekly_assessment_absent, r.exam_absent
        FROM results r
        JOIN students s ON r.student_id = s.id
        WHERE r.class = ? AND r.section = ? AND r.subject = ?
        AND r.status = 'Approved'
        AND r.term_id = ? AND r.session_id = ?
    ");
        $end_stmt->bind_param("sssii", $class, $section, $subject_name, $currentTermId, $currentSessionId);
        $end_stmt->execute();
        $end_results = $end_stmt->get_result();

        if ($end_results->num_rows > 0) {
            $results_by_subject[$subject_name] = $end_results->fetch_all(MYSQLI_ASSOC);
            $result_type_by_subject[$subject_name] = 'Endterm';
        } 
    }
}
else{
    // Fetch all subjects for this class
    $subject_stmt = $con->prepare("
    SELECT DISTINCT subject 
    FROM result2 
    WHERE class = ? AND section = ? AND term_id = $currentTermId AND session_id = $currentSessionId
");
    $subject_stmt->bind_param("ss", $class, $section);
    $subject_stmt->execute();
    $subject_result = $subject_stmt->get_result();
    $subjects = $subject_result->fetch_all(MYSQLI_ASSOC);

    // Fetch results for each subject
    $results_by_subject = [];
    $result_type_by_subject = [];

    foreach ($subjects as $subject) {
        $subject_name = $subject['subject'];

        // First try fetching end-of-term results
        $end_stmt = $con->prepare("
        SELECT s.studentName, s.studentno, r.test_score, r.test_score2, r.class_performance, r.weekly_assessment, r.exam_score, r.total_score,
        r.test_absent, r.test2_absent, r.class_performance_absent, r.weekly_assessment_absent, r.exam_absent
        FROM result2 r
        JOIN students s ON r.student_id = s.id
        WHERE r.class = ? AND r.section = ? AND r.subject = ?
        AND r.status_test = 'Approved'
        AND r.term_id = ? AND r.session_id = ?
    ");
        $end_stmt->bind_param("sssii", $class, $section, $subject_name, $currentTermId, $currentSessionId);
        $end_stmt->execute();
        $end_results = $end_stmt->get_result();

        if ($end_results->num_rows > 0) {
            $results_by_subject[$subject_name] = $end_results->fetch_all(MYSQLI_ASSOC);
            $result_type_by_subject[$subject_name] = 'Midterm';
        }
    }
}
}
?>

<!DOCTYPE html>
<html>
<?php @include("includes/head.php"); ?>

<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">
            <!-- Content Header (Page header) -->
             <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">Score broadsheet - <?= $class ?> - <?= ($section) ?></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">Broadsheet</li>
                        </ol>
                    </nav>
                </div>
            </div>
        </div>
    </div>
</section> 
            <section class="content">
                <div class="container-fluid">
                    <div class="card shadow-sm">
                        <div class="card-header bg-primary text-white">
                            <h5 class="card-title font-weight-bold">
                                <i class="fas fa-file-alt"></i> Check Previous Term and Session Broadsheet
                            </h5>

                        </div>
                        <div class="card-body">

                            <!-- Result Filter Form -->
                            <form method="POST" class="mb-4" action="">
                                <div class="row">
                                    <div class="form-group col-md-6">
                                        <label>Class:</label>
                                        <select id="classSelector" name="class" class="form-control select2" required>
                                            <option value="">Select a 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-6">
                                        <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-6">
                                        <label for="session_id">Academic Session</label>
                                        <select name="session_id" id="session_id" class="form-control select2" required>
                                            <option value="">-- Select Session --</option>
                                            <?php
                                            $query = "SELECT id, session_name FROM school_sessions ORDER BY session_name DESC";
                                            $stmt1 = $con->prepare($query);
                                            $stmt1->execute();
                                            $result = $stmt1->get_result();
                                            while ($row1 = $result->fetch_assoc()) {
                                                echo "<option value='{$row1['id']}'>{$row1['session_name']}</option>";
                                            }
                                            ?>
                                        </select>
                                    </div>

                                    <div class="form-group col-md-6">
                                        <label for="term_id">Term</label>
                                        <select name="term_id" id="term_id" class="form-control select2" required>
                                            <option value="">-- Select Term --</option>
                                        </select>
                                    </div>
                                    <div class="form-group col-md-6">
                                        <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>
                                <div class="form-group col-md-12 text-center">
                                    <button type="submit" class="btn btn-primary mt-3"><i class="fas fa-check-circle"></i> View Result</button>
                                </div>
                            </form>
                            <!-- End of Result Filter Form -->
                        </div>
                    </div>
                </div>
            </section>
            <?php if ($_SERVER["REQUEST_METHOD"] == "POST"): ?>


                <section class="content">
                    <div class="container-fluid">
                        <div class="card border-primary">
                            <div class="card-header bg-primary text-white">
                                <h5 class="mb-0"><i class="fas fa-chalkboard"></i> <?= $class ?> - <?= ($section) ?> Class Result Broadsheet </h5>
                            </div>
                            <?php if (empty($subjects)): ?>
                                <div class="alert alert-warning m-3">
                                    <strong>No results found!</strong> There are currently no subjects or results available for <?= $class ?> - <?= ($section) ?> in <?= $currentSessionName ?>, <?= $currentTermName ?>.
                                </div>
                            <?php else: ?>
                                <?php foreach ($results_by_subject as $subject => $results): ?>
                                    <div class="card mt-3">
                                        <div class="card-header font-weight-bold bg-primary text-white">
                                            <h6 class="mb-0">
                                                <i class="fas fa-book-open"></i> <?= htmlspecialchars($subject); ?> - <?= $result_type_by_subject[$subject] ?> Results
                                            </h6>
                                        </div>
                                        <div class="card-body">
                                            <?php if (empty($results)): ?>
                                                <div class="alert alert-info">
                                                    No results have been submitted for <?= htmlspecialchars($subject); ?> yet.
                                                </div>
                                            <?php else: ?>
                                                <table class="table table-bordered table-hover example11">
                                                    <thead>
                                                        <tr>
                                                            <th>Admission No.</th>
                                                            <th>Student Name</th>

                                                            <?php if ($result_type_by_subject[$subject] === 'Midterm'): ?>                                
                                                                <th>1st C.A. Test (10)</th>
                                                                <th>2nd C.A. Test (10)</th>
                                                                <th>Ex. & Projects (5)</th>
                                                            <?php else: ?>
                                                                <th>C.A. Test (10)</th>
                                                                <th>Ex. & Projects (15)</th>
                                                            <?php endif; ?>

                                                            <th>Assignment (5)</th>

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

                                                    </thead>

                                                   <tbody>
                                                        <?php foreach ($results as $result): ?>
                                                            <?php
                                                            // Determine each score display (with AB if absent)
                                                            $test_score        = ($result['test_absent'] == "1") ? 'AB' : (int)$result['test_score'];
                                                            $test_score2       = ($result['test2_absent'] == "1") ? 'AB' : (int)$result['test_score2'];
                                                            $class_performance = ($result['class_performance_absent'] == "1") ? 'AB' : (int)$result['class_performance'];
                                                            $weekly_assessment = ($result['weekly_assessment_absent'] == "1") ? 'AB' : (int)$result['weekly_assessment'];
                                                            $exam              = ($result['exam_absent'] == "1") ? 'AB' : (int)$result['exam_score'];

                                                            if ($result_type_by_subject[$subject] === 'Midterm') {
                                                                // Numeric values for safe sum
                                                                $scores_midterm = [$test_score, $test_score2, $class_performance, $weekly_assessment];
                                                                $numeric_scores_midterm = array_filter($scores_midterm, 'is_numeric');
                                                                $total_midterm = count($numeric_scores_midterm) ? array_sum($numeric_scores_midterm) : 'AB';
                                                            } else {
                                                                // Endterm
                                                                $scores_endterm = [$test_score, $class_performance, $weekly_assessment, $exam];
                                                                $numeric_scores_endterm = array_filter($scores_endterm, 'is_numeric');
                                                                $total_endterm = count($numeric_scores_endterm) ? array_sum($numeric_scores_endterm) : 'AB';
                                                            }
                                                            ?>
                                                            <tr>
                                                                <td><?= htmlspecialchars($result['studentno']); ?></td>
                                                                <td><?= htmlspecialchars($result['studentName']); ?></td>

                                                                <?php if ($result_type_by_subject[$subject] === 'Midterm'): ?>
                                                                    <td><?= $test_score ?></td>
                                                                    <td><?= $test_score2 ?></td>
                                                                    <td><?= $class_performance ?></td>
                                                                    <td><?= $weekly_assessment ?></td>
                                                                    <td><?= $total_midterm ?></td>
                                                                <?php else: ?>
                                                                    <td><?= $test_score ?></td>
                                                                    <td><?= $class_performance ?></td>
                                                                    <td><?= $weekly_assessment ?></td>
                                                                    <td><?= $exam ?></td>
                                                                    <td><?= $total_endterm ?></td>
                                                                <?php endif; ?>
                                                            </tr>
                                                        <?php endforeach; ?>
                                                        </tbody>

                                                </table>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                            <div class="card-footer text-center">
                                <button type="button" class="btn btn-primary" onclick="PrintFunction()" name="submit" target="_blank"><i class="fas fa-print"></i>
                                    Print
                                </button>
                                <button type="button" class="btn btn-danger approve" onclick="downloadFilteredPDF()" name="submit"><i class="fas fa-file-pdf"></i>
                                    Download PDF
                                </button>
                            </div>
                        </div>

                    </div>
                    <!-- /.container-fluid -->
                </section>
            <?php else: ?>
                <section class="content">
                    <div class="container-fluid">
                        <div class="alert alert-info mt-5">
                            <p class="mb-0">Please select a <strong>Term</strong> and <strong>Session</strong> to view the result.</p>
                        </div>
                    </div>
                </section>
            <?php endif; ?>


        </div>
        <!-- /.content-wrapper -->
        <?php @include("includes/footer.php"); ?>
        <?php @include("includes/foot.php"); ?>
    </div>
    <!-- ./wrapper -->
    <script>
        $(document).ready(function() {
            $('.select2').select2();
            $('#session_id').change(function() {
                var selectedClass = $(this).val();
                if (selectedClass) {
                    $.ajax({
                        url: 'fetch_session.php',
                        type: 'POST',
                        data: {
                            class_name: selectedClass
                        },
                        success: function(response) {
                            $('#term_id').html(response);
                        }
                    });
                } else {
                    $('#term_id').html('<option value="">Select Term</option>');
                }
            });
            $('#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>');
                }
            });
        });
    </script>
    <script>
        $(document).ready(function() {
            $('.example11').DataTable({
                // Options for DataTables (optional)
                "paging": true,
                "searching": true,
                "ordering": true,
                "info": true,
                "responsive": true,
                "autoWidth": false
            });
        });

        function downloadFilteredPDF() {
            var classs = "<?= $class ?>";
            var section = "<?= $section ?>";
            var session = "<?= $session_id ?>";
            var term = "<?= $term_id ?>";
            var tabid = "<?= $tabSessionID ?>";
            var result_type = "<?= $result_type ?>";


            // Check if start and end dates are provided
            if (classs && section) {
                var url = "generate_broadsheet_pdf1.php?class=" + classs + "&section=" + section + "&tab_id=" + tabid + "&session=" + session + "&term=" + term + "&result_type=" + result_type;


                // Redirect to generate PDF
                window.location.href = url;
            } else {
                alert("Class and Arm empty.");
            }
        }

        function PrintFunction() {
            var classs = "<?= $class ?>";
            var section = "<?= $section ?>";
            var tabid = "<?= $tabSessionID ?>";
            var session = "<?= $session_id ?>";
            var term = "<?= $term_id ?>";
            var result_type = "<?= $result_type ?>";

            // Check if start and end dates are provided
            if (classs && section) {
                var url = "print_broadsheet_pdf1.php?class=" + classs + "&section=" + section + "&tab_id=" + tabid + "&session=" + session + "&term=" + term + "&result_type=" + result_type;


                // Redirect to generate PDF
                window.location.href = url;
            } else {
                alert("Class and Arm empty.");
            }
        }
    </script>

</body>

</html>