<?php
include('includes/session1.php');
error_reporting(0);
include('includes/dbconnection.php');
include('includes/session_term_helper.php');

if (!isset($_SESSION['sid'])) {
    header('location:logoutteacher.php');
    exit();
}
// Assuming the subject teacher is viewing results for a specific subject
$subject = $_GET['subject'];  // Get the subject from URL parameter
$class = $_GET['class'];  // Get the class from URL parameter
$section = $_GET['section'];  // Get the section from URL parameter

// Fetch current session and term
// Fetch active session ordered by earliest start_date

// Resolve current session and term (with fallback support)
$sessionTerm = resolveCurrentSessionTerm($con);
$currentSessionId   = $sessionTerm['session_id']   ?: null;
$currentSessionName = $sessionTerm['session_name'];
$currentTermId      = $sessionTerm['term_id']       ?: null;
$currentTermName    = $sessionTerm['term_name'];



// First, try to fetch End-of-Term results
$queryEndTerm = "
    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 = $con->prepare($queryEndTerm);
$stmt->bind_param("sssii", $class, $section, $subject, $currentTermId, $currentSessionId);
$stmt->execute();
$result_data = $stmt->get_result();

$result_type = 'Endterm';



?>

<!-- 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 border-primary">
                        <div class="card-header bg-primary text-white">
                            <h5 class="mb-0"><i class="fas fa-chalkboard"></i> <?= $class ?> - <?= ($section) ?> End of Term <?= htmlspecialchars($subject); ?> Scoresheet </h5>
                        </div>
                        <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); ?> - End of Term</h6>
                            </div>
                            <div class="card-body">
                                <table class="table table-bordered table-hover example11">
                                    <thead>
                                        <tr>
                                            <th>Admission No.</th>
                                            <th>Student Name</th>
                                            <th>C.A. Test(10)</th>
                                            <th>Ex. & Projects (15)</th>
                                            <th>Assignment (5)</th>
                                            <th>Exam (70)</th>
                                            <th>Total (100)</th>
                                        </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'];
    $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 = [$test_score, $class_performance, $weekly_assessment, $exam];
    $numeric_scores = array_filter($scores, 'is_numeric');

    // Calculate total or show AB if all absent
    $total = count($numeric_scores) ? array_sum($numeric_scores) : '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
                                            $showScores = ($total_paid >= $expected_fee);
                                            ?>
                                                        <tr>
                                                            <td><?= $studentNo ?></td>
                                                            <td><?= $studentName ?></td>
                                                            <td><?= $showScores ? $test_score : '***' ?></td>
                                                            <td><?= $showScores ? $class_performance : '***' ?></td>
                                                            <td><?= $showScores ? $weekly_assessment : '***' ?></td>
                                                            <td><?= $showScores ? $exam : '***' ?></td>
                                                            <td><?= $showScores ? $total : '***' ?></td>
                                                        </tr>
                                        <?php endwhile; ?>
                                    </tbody>

                                </table>
                            </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>

        </div>
        <!-- /.content-wrapper -->
        <?php @include("includes/footer.php"); ?>
        <?php @include("includes/foot.php"); ?>
    </div>
    <!-- ./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 tabid = "<?= $tabSessionID ?>";


            // Check if start and end dates are provided
            if (classs && section) {
                var url = "generate_scoresheet_pdf.php?class=" + classs + "&section=" + section + "&subject=" + subject + "&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 tabid = "<?= $tabSessionID ?>";



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


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

</body>

</html>