<?php
include('includes/session1.php');
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 (!isset($_SESSION['sid'])) {
    header('location:logoutteacher.php');
    exit();
}

$teacher_id = $_SESSION['sid']; // Assuming teacher id is stored in session

// Fetch assigned subjects where the teacher is a subject teacher
$subject_stmt = $con->prepare("
    SELECT c.class, c.section, s.Subject_name 
    FROM teacher_assignments ta
    JOIN subjectcombination s ON ta.subject_id = s.id
    JOIN class_section c ON c.class = s.Class AND c.section = s.section
    WHERE ta.teacher_id = ? AND ta.subject_id IS NOT NULL
");
$subject_stmt->bind_param("i", $teacher_id);
$subject_stmt->execute();
$subject_result = $subject_stmt->get_result();
$subject_teacher_classes = $subject_result->fetch_all(MYSQLI_ASSOC);



// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $full_value = $_POST['class']; // since the <select name="class">

    list($subject, $class, $section) = explode('|', $full_value);
    $session_id = $_POST['session_id'];  // Selected session
    $term_id = $_POST['term_id'];  // Selected term
    $result_type = $_POST['result_type'];


    if ( $result_type === 'Endterm'){
    // Fetch results for this subject, class, section, session, and term
    $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 = ?
        ");
    $stmt->bind_param("sssss", $class, $section, $subject, $term_id, $session_id);
    $stmt->execute();
    $result_data = $stmt->get_result();
}
else{
        // Fetch results for this subject, class, section, session, and term
    $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 = ?
        ");
    $stmt->bind_param("sssss", $class, $section, $subject, $term_id, $session_id);
    $stmt->execute();
    $result_data = $stmt->get_result();
}
}
?>

<!-- HTML to display the results -->

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

<body class="hold-transition sidebar-mini layout-fixed">
    <div class="wrapper">
        <?php @include("includes/headert.php"); ?>
        <?php @include("includes/sidebart.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">Scoresheet - <?= $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="teacher_dashboard.php" class="text-primary">Home</a></li>
                            <li class="breadcrumb-item active" aria-current="page">Scoresheet</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 Result
                            </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 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 for="class">Subject</label>
                                        <select name="class" id="class" class="form-control select2" required>
                                            <option value="">-- Select Subject --</option>
                                            <?php
                                            // Dynamically populate subjects based on teacher assignments
                                            foreach ($subject_teacher_classes as $row) {
                                                $value = htmlspecialchars($row['Subject_name'] . "|" . $row['class'] . "|" . $row['section']);
                                                $text = htmlspecialchars($row['Subject_name']) . " - " . htmlspecialchars($row['class']) . " " . htmlspecialchars($row['section']);
                                                echo "<option value='$value'>$text</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) ?> Scoresheet </h5>
                            </div>
                            <div class="card mt-3">
                                <div class="card-body">
                                    <!-- Display the Results Table -->
                                    <div class="card-body">
                                        <table class="table table-bordered table-hover example11">
                                            <thead>
                                                <tr>
                                                <tr>
                                                    <th>Admission No.</th>
                                                    <th>Student Name</th>
                                                    <?php if ($result_type === 'Endterm'):?>                                                    
                                                    <th>C.A. Test 1 (10)</th>
                                                    <th>C.A. Test 2 (10)</th>
                                                    <?php else:?>        
                                                    <th>1st C.A. Test (10)</th>
                                                    <th>2nd C.A. Test (10)</th>
                                                    <?php endif;?>                                                    
                                                    <th>Ex. & Projects (5)</th>
                                                    <th>Assignment (5)</th>
                                                    <?php if ($result_type === 'Endterm'):?>
                                                    <th>Exam (70)</th>
                                                    <th>Total (100)</th>
                                                    <?php else:?>
                                                    <th>Total (30)</th>
                                                    <?php endif;?>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($row = $result_data->fetch_assoc()): ?>
                                              <?php
    // Determine each score display
    $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'];
    // Collect scores for numeric sum
    $scores_exam = [$test_score, $test_score2, $class_performance, $weekly_assessment, $exam];
    $numeric_scores_exam = array_filter($scores_exam, 'is_numeric');

    // Calculate total or show AB if all absent
    $total_exam = count($numeric_scores_exam) ? array_sum($numeric_scores_exam) : 'AB';

    //for test
        // Collect scores for numeric sum
    $scores_test = [$test_score, $test_score2, $class_performance, $weekly_assessment];
    $numeric_scores_test = array_filter($scores_test, 'is_numeric');

    // Calculate total or show AB if all absent
    $total_test = count($numeric_scores_test) ? array_sum($numeric_scores_test) : 'AB';

    ?>                                                                                    <?php
                                            $studentNo = $row['studentno'];
                                            $studentName = $row['studentName'];

                                            // Fetch student details
                                            $studentDataQuery = $con->prepare("SELECT id, stream, class, demote_status FROM students WHERE studentno = ?");
                                            $studentDataQuery->bind_param("s", $studentNo);
                                            $studentDataQuery->execute();
                                            $studentDataResult = $studentDataQuery->get_result();
                                            $studentData = $studentDataResult->fetch_assoc();

                                            $student_id = $studentData['id'];
                                            $stream = $studentData['stream'];
                                            $student_class = $studentData['class'];
                                            $repeat = $studentData['demote_status'];

                                            // Check if student paid - Determine student type
                                            $payQuery = $con->prepare("SELECT pay_for FROM payment 
                                                WHERE student_id = ? AND class = ? AND school_type = ? 
                                                AND session = ? AND term = ? AND pay_for LIKE 'School Fees%' 
                                                LIMIT 1");
                                            $payQuery->bind_param("issss", $student_id, $student_class, $stream, $currentSessionName, $currentTermName);
                                            $payQuery->execute();
                                            $payResult = $payQuery->get_result()->fetch_assoc();
                                            $pay_for = $payResult['pay_for'] ?? 'School Fees';
                                            $student_type = ($pay_for === 'School Fees (New Student)') ? 'New' : 'Old';

                                            // Fetch expected fee
                                            $feeQuery = $con->prepare("SELECT amount FROM fee_records 
                                                WHERE class = ? AND stream = ? AND name = ? AND student_type = ? 
                                                AND session = ? AND term = ? 
                                                ORDER BY created_at DESC LIMIT 1");
                                            $feeQuery->bind_param("ssssss", $student_class, $stream, $pay_for, $student_type, $currentSessionName, $currentTermName);
                                            $feeQuery->execute();
                                            $feeResult = $feeQuery->get_result()->fetch_assoc();
                                            $expected_fee = $feeResult['amount'] ?? 0;

                                            if (trim($student_class) === 'SS 1' && $repeat === 1 && $currentTermName === 'First Term') {

                                                // Fetch expected fee
                                                $feeQuery = $con->prepare("SELECT amount FROM fees 
                                                            WHERE name = 'School Fees' 
                                                            AND class = ? AND stream = ? AND student_type = 'Old' 
                                                            LIMIT 1");
                                                $feeQuery->bind_param("ss", $student_class, $stream);
                                                $feeQuery->execute();
                                                $feeResult = $feeQuery->get_result()->fetch_assoc();
                                                $expected_fee1 = $feeResult['amount'] ?? $expected_fee;
                                                $expected_fee = $expected_fee1;
                                            }
                                            // Check for JSS 3, SS 1, SS 3 special first term fees
                                            if ($currentTermName === 'First Term' && in_array($student_class, ['JSS 3', 'SS 1', 'SS 3'])) {
                                                // Match specific fee names
                                                $special_fee_names = [
                                                    'JSS 3' => 'First Term JSS 3 School Fees',
                                                    'SS 1'  => 'First Term SS 1 School Fees',
                                                    'SS 3'  => 'First Term SS 3 School Fees'
                                                ];

                                                $special_fee_name = $special_fee_names[$class];

                                                $feeQuery = "SELECT amount FROM fees 
                                                    WHERE class = ? 
                                                    AND stream = ? 
                                                    AND student_type = 'Old' 
                                                    AND name = ? 
                                                    LIMIT 1";

                                                $stmt = $con->prepare($feeQuery);
                                                $stmt->bind_param("sss", $student_class, $stream, $special_fee_name);
                                                $stmt->execute();
                                                $feeResult = $stmt->get_result();
                                                $feeRow = $feeResult->fetch_assoc();
                                                $expected_fee1 = $feeRow['amount'] ?? $expected_fee; // Fallback to default fee if special fee not found
                                                $expected_fee = $expected_fee1; // Use the special fee if applicable
                                            }


                                            // Total paid
                                            $paidQuery = $con->prepare("SELECT SUM(amount) AS total_paid FROM payment 
                                                WHERE student_id = ? AND class = ? AND pay_for = ? 
                                                AND school_type = ? AND session = ? AND term = ?");
                                            $paidQuery->bind_param("isssss", $student_id, $student_class, $pay_for, $stream, $currentSessionName, $currentTermName);
                                            $paidQuery->execute();
                                            $paidResult = $paidQuery->get_result()->fetch_assoc();
                                            $total_paid = $paidResult['total_paid'] ?? 0;

                                            // Check if fully paid
                                            if ($result_type === 'Endtime'){
                                            $showScores = ($total_paid >= $expected_fee);
                                            }else{
                                            $showScores = ($total_paid >= ($expected_fee /100 * 70));

                                            }
                                            ?>       
                                                    <tr>
                                                        <td><?= htmlspecialchars($row['studentno']); ?></td>
                                                        <td><?= htmlspecialchars($row['studentName']); ?></td>
                                                            <td><?= $showScores ? $test_score : '***' ?></td>
                                                            <td><?= $showScores ? $test_score2 : '***' ?></td>
                                                            <td><?= $showScores ? $class_performance : '***' ?></td>
                                                            <td><?= $showScores ? $weekly_assessment : '***' ?></td>
                                                        <?php if ($result_type === 'Endterm'):?>
                                                            <td><?= $showScores ? $exam : '***' ?></td>
                                                            <td><?= $showScores ? $total_exam : '***' ?></td>
                                                        <?php else:?>
                                                            <td><?= $showScores ? $total_test : '***' ?></td>
                                                        <?php endif;?>
                                                    </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>

                                </div>
                            </div>
                            <!-- <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>, <strong>Session</strong> and <strong>Subject</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>
    <script src="dist/js/select2.min.js"></script>
    <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>');
                }
            });
        });
    </script>
    <!-- ./wrapper -->
    <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 subject = "<?= $subject ?>";
            var session = "<?= $session_id ?>";
            var term = "<?= $term_id ?>";
            var tabid = "<?= $tabSessionID ?>";


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


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

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



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


                // Redirect to generate PDF
                window.location.href = url;
            } else {
                alert("Class, Section, Session, and Term must not be empty.");
            }
        }
    </script>

</body>

</html>