<?php

date_default_timezone_set('Africa/Lagos'); // Replace with your desired time zone



include('includes/session.php');

error_reporting(0);

// Connect to the database

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'];
// Fetch student ID (e.g., via GET parameter)

$student_id = $_SESSION['student_id'];




// Handle POST selections or fallback to defaults

$session_id = $_POST['session_id'];

$term_id = $_POST['term_id'];

$class = $_POST['class'];



// Get selected names

$selected_session = mysqli_fetch_assoc(mysqli_query($con, "SELECT session_name FROM school_sessions WHERE id = '$session_id'"))['session_name'] ?? '';

$selected_term = mysqli_fetch_assoc(mysqli_query($con, "SELECT term_name FROM school_terms WHERE id = '$term_id'"))['term_name'] ?? '';



// Fetch all sessions, terms, and student's result classes

$sessions = mysqli_query($con, "SELECT * FROM school_sessions ORDER BY id DESC");

$terms = mysqli_query($con, "SELECT * FROM school_terms");

$classes = mysqli_query($con, "SELECT DISTINCT class FROM result2 WHERE student_id = '$student_id'");





// Fetch student info

$student_sql = "SELECT * FROM students WHERE id = $student_id";

$student_result = $con->query($student_sql);

$student = $student_result->fetch_assoc();

$default_class = $student['class'];

$section = $student['section'];

$stream = $student['stream'];

$student_name = htmlspecialchars($student['studentName']);

$studentImage = "studentimages/" . htmlspecialchars($student['studentImage']);





// Get selected session and term

$selected_session_id = $_POST['session_id'];

$selected_term_id = $_POST['term_id'];



// select payment for

$payQuery = "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";





$PaidStmt = $con->prepare($payQuery);

$PaidStmt->bind_param("issss", $student_id, $class, $stream, $selected_session, $selected_term);

$PaidStmt->execute();

$PaidResult = $PaidStmt->get_result();

$PaidRow = $PaidResult->fetch_assoc();

$pay_for = $PaidRow['pay_for'] ?? 'School Fees';



if ($pay_for == 'School Fees') {

    $student_type = "Old";

} elseif ($pay_for == 'School Fees (New Student)') {

    $student_type = "New";

} else {

    $step = "check_payment"; // Or any other default/fallback type

}





// Get default fee

$feeQuery = "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";



$stmt = $con->prepare($feeQuery);

$stmt->bind_param("ssssss", $class, $stream, $pay_for, $student_type, $selected_session, $selected_term);

$stmt->execute();

$feeResult = $stmt->get_result();

$feeRow = $feeResult->fetch_assoc();

$totalFee = $feeRow['amount'] ?? 0;

$currentTermTotalFees = $totalFee;



// Check for JSS 3, SS 1, SS 3 special first term fees

if ($selected_term === 'First Term' && in_array($class, ['JSS 3', 'SS 1', 'SS 3'])) {

$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];

// Try fee_records first (session/term-specific), fall back to fees catalogue
$sFeeAmt = 0.0;
$sFeeQ = $con->prepare("SELECT amount FROM fee_records WHERE class = ? AND stream = ? AND student_type = 'Old' AND name = ? AND session = ? AND term = 'First Term' ORDER BY id DESC LIMIT 1");
$sFeeQ->bind_param("ssss", $class, $stream, $special_fee_name, $selected_session);
$sFeeQ->execute();
$sFeeRes = $sFeeQ->get_result()->fetch_assoc();
$sFeeQ->close();
if ($sFeeRes && (float)$sFeeRes['amount'] > 0) {
    $sFeeAmt = (float)$sFeeRes['amount'];
} else {
    $sFeeQ2 = $con->prepare("SELECT amount FROM fees WHERE class = ? AND stream = ? AND student_type = 'Old' AND name = ? LIMIT 1");
    $sFeeQ2->bind_param("sss", $class, $stream, $special_fee_name);
    $sFeeQ2->execute();
    $sFeeRes2 = $sFeeQ2->get_result()->fetch_assoc();
    $sFeeQ2->close();
    if ($sFeeRes2) $sFeeAmt = (float)$sFeeRes2['amount'];
}
$currentTermTotalFees = $sFeeAmt > 0 ? $sFeeAmt : $totalFee;

}





// Fetch total amount paid by the student for the current term

$totalPaidQuery = "SELECT SUM(amount) as total_paid FROM payment 

WHERE student_id = ? 

AND class = ? 

AND pay_for =? 

AND school_type = ?

AND session = ?

AND Term = ?";



$totalPaidStmt = $con->prepare($totalPaidQuery);

$totalPaidStmt->bind_param("isssss", $student_id, $class, $pay_for, $stream, $selected_session, $selected_term);

$totalPaidStmt->execute();

$totalPaidResult = $totalPaidStmt->get_result();

$totalPaidRow = $totalPaidResult->fetch_assoc();

$totalPaidAmount = $totalPaidRow['total_paid'] ?? 0;





$sql = "SELECT DATE(publish_datetime) AS publish_date 

FROM result_publish_schedule 

WHERE session_id = ? AND term_id = ? AND result_type = 'Midterm'";



$stmt = $con->prepare($sql);

$stmt->bind_param("ii", $session_id, $term_id);

$stmt->execute();

$result = $stmt->get_result();

$publish_date = 'N/A'; // Default value if no publish date is found

if ($row = $result->fetch_assoc()) {

    $publish_date = $row['publish_date'];

}



// Fetch all terms for the session, ordered correctly

$terms_sql = "SELECT id AS term_id, term_name FROM school_terms WHERE session_id = '$selected_session_id' ORDER BY id ASC";

$terms_result = $con->query($terms_sql);



$terms = [];

$term_order = [];

$term_names = [];





if ($terms_result && $terms_result->num_rows > 0) {

    while ($row = $terms_result->fetch_assoc()) {

        $terms[] = $row;

        $term_order[] = $row['term_id'];

        $term_names[$row['term_id']] = $row['term_name'];

    }

}



$current_term_index = array_search($selected_term_id, $term_order);



$previous_term_ids = [];



if ($current_term_index !== false) {

    for ($i = 0; $i < $current_term_index; $i++) {

        $previous_term_ids[] = $term_order[$i];

    }

}



$all_terms_to_fetch = array_merge($previous_term_ids, [$selected_term_id]);

$term_ids_in = implode(",", $all_terms_to_fetch);





$results = [];  // Initialize it as an empty array to avoid "undefined" error

$total_score = 0;

$total_subjects = 0;

$mark_obtainable = 0;

$percentage = 0;

$average_score = 0;

$error_message = '';



if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['view_result'])) {



    // Check publish date first

    if ($publish_date === 'N/A') {

        $error_message = "Kindly note that the official date for the release of results has not been announced by the school. You are advised to check back at a later time or contact the school administration for further clarification.";

    } elseif (strtotime(date('Y-m-d')) < strtotime($publish_date)) {

        $error_message = "Mid Term Results for ".$selected_term." ". $selected_session." session has not been published yet. Wait till " . date("l, jS F Y g:i A", strtotime($publish_date)) . "."; 

        $error_message = "Sorry, Unable to view results! <br>You have not paid at least 70% of the required school fee. Please complete your payment.";

        $show_payment_button = true;  //flag to show payment button 

       } else {

        // ✅ Fetch academic results only if date is reached and fees are okay

        $results_sql = "SELECT term_id, subject, test_score, test_score2, class_performance, weekly_assessment, remarks_test,

                        (test_score + test_score2 + class_performance + weekly_assessment) AS total_score, 

                        remarks_test, test_absent, test2_absent, class_performance_absent, weekly_assessment_absent

                    FROM result2 

                    WHERE student_id = '$student_id' 

                    AND session_id = '$selected_session_id' 

                    AND term_id = '$selected_term_id'

                    AND class = '$class'";

        $results_result = $con->query($results_sql);



        $subjects_results = [];

        $total_score = 0;

        $total_subjects = 0;

        $mark_obtainable = 0;

        $percentage = 0;



        if ($results_result && $results_result->num_rows > 0) {

            while ($row = $results_result->fetch_assoc()) {

                $subjects_results[] = $row;

            }



            $total_subjects = count($subjects_results);

            $mark_obtainable = $total_subjects * 30;



            foreach ($subjects_results as $result) {

                $total_score += $result['total_score'] ?? 0;

            }



            $percentage = $total_subjects ? round(($total_score / $mark_obtainable) * 100, 2) : 0;

            $average_score = $total_subjects ? round($total_score / $total_subjects, 2) : 0;

        } else {

            $error_message = "No results found for this student.";

        }

    }

}



// Remark generator

function generateRemark($percentage)

{

    if ($percentage >= 75) {

        return 'Outstanding Performance!';

    } elseif ($percentage >= 60) {

        return 'Commendable performance!';

    } elseif ($percentage >= 50) {

        return 'Satisfactory Performance!';

    } elseif ($percentage >= 40) {

        return 'Marginal Performance!';

    } else {

        return 'Unsatisfactory Performance!';

    }

}

$principal_remarks = generateRemark($percentage);



use Dotenv\Dotenv;



// Load Composer dependencies

require_once 'vendor/autoload.php';

// Load environment variables



$dotenv = Dotenv::createImmutable(__DIR__);

$dotenv->load();



$school_name = $_ENV['SCHOOL_NAME_1'];

$logo = $_ENV['WEBSITE_LOGO'];

$address = $_ENV['id_address'];

$school_email = $_ENV['SCHOOL_EMAIL'];

$signature = $_ENV['PRINCIPAL_SIGNATURE'];

$website = $_ENV['SCHOOL_WEBSITE'];







?>

<!DOCTYPE html>

<html lang="en">

<?php include('includes/head.php'); ?>

<style>

    .header {

        padding-top: 20px;

        text-align: center;

        font-family: 'Times New Roman', Times, serif;

        /* Good size for print readability */

        font-weight: bold;

        /* Optional: makes it more prominent */

    }



    .logo {

        float: left;

        margin-right: 20px;

    }







    .report-title {

        font-size: 14px;

        font-weight: bold;

        background-color: #ff0000;

        color: white;

        padding: 5px;

        text-align: center;

        width: fit-content;

        margin: 10px auto;

    }



    table {

        width: 100%;

        border-collapse: collapse;

        margin-top: 20px;

    }



    th,

    td {

        border: 1px solid #000;

        padding: 8px;

        text-align: left;

    }



    th {

        background-color: #f2f2f2;

    }



    .comment-section,

    .signature-section {

        margin-top: 20px;

    }



    .line {

        border-bottom: 1px solid #000;

        margin: 5px 0;

    }



    .print-btn {

        margin: 20px 0;

    }

</style>



<body class="hold-transition sidebar-mini layout-fixed">

    <div class="wrapper">

        <?php include('includes/headerstd.php'); ?>

        <?php include('includes/sidebaroldstdboard.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-clipbaord-list"></i>

                        </div>

                        <div>

                            <h1 class="premium-title text-primary">

                                Result Management

                                <span class="premium-subtitle text-secondary">Mid Term 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="oldstdboard.php" class="text-primary">Home</a></li>

                            <li class="breadcrumb-item active" aria-current="page">View Result</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 Result

                            </h5>



                        </div>

                        <div class="card-body">



                            <!-- Result Filter Form -->

                            <form method="POST" class="mb-4">

                                <div class="row">

                                    <div class="form-group col-md-4">

                                        <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

                                            $sessionResult = $con->query("SELECT DISTINCT id, session_name FROM school_sessions ORDER BY session_name DESC");

                                            while ($row = $sessionResult->fetch_assoc()) {

                                                echo "<option value='{$row['id']}'>{$row['session_name']}</option>";

                                            }

                                            ?>

                                        </select>

                                    </div>



                                    <div class="form-group col-md-4">

                                        <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-4">

                                        <label for="class">Class</label>

                                        <select name="class" id="class" class="form-control select2" required>

                                            <option value="">-- Select Class --</option>

                                            <?php

                                            $classResult = $con->query("SELECT DISTINCT class FROM class_section ORDER BY class");

                                            while ($row = $classResult->fetch_assoc()) {

                                                echo "<option value='{$row['class']}'>{$row['class']}</option>";

                                            }

                                            ?>

                                        </select>

                                    </div>

                                </div>

                                <div class="form-group col-md-12  text-center">

                                    <button type="submit" name="view_result" class="btn btn-primary mt-3"><i class="fas fa-eye"></i> View Result</button>

                                </div>

                            </form>

                            <!-- End of Result Filter Form -->

                        </div>

                    </div>

                </div>

            </section>

            <!-- // Check if the student has paid the full amount -->

                <?php if (!empty($error_message)) : ?>

                <section class="content">

                    <div class="container-fluid">

                        <div class="alert alert-danger text-center mt-4">

                            <p><?php echo $error_message; ?></p>

                                <?php if (!empty($show_payment_button)) : ?>

                                    <a href="payschoolfeesb.php" class="btn btn-primary mt-2">

                                        <i class="fas fa-sign-in-alt"></i> Go to School Fees Payment Page

                                    </a>

                                <?php endif; ?>                       

                         </div>

                    </div>

                </section>

                





            <?php elseif (empty($selected_term) || empty($selected_session)): ?>

                <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 elseif (empty($error_message) && $total_subjects > 0): ?>

                <!-- JSS 1 REPORT CARD -->

                <section class="content">

                    <div class="container-fluid">

                        <div class="card border-5" style="position: relative;">

                            <!-- Watermark image -->

                            <img src="<?php echo $logo; ?>" alt="Watermark"

                                style="position: absolute;

                                                top: 50%;

                                                left: 50%;

                                                transform: translate(-50%, -50%);

                                                opacity: 0.10;

                                                width: 50%;

                                                max-width: 200px;

                                                z-index: 0;

                                                pointer-events: none;">

                            <!-- Main content goes here -->

                            <div style="position: relative; z-index: 1;">

                                <!-- Your result content here -->



                                <div class="header">

                                    <img src="<?php echo $logo; ?>" style="width: 70px; height: 70px;" alt="logo" class="logo">

                                    <div class="school-name">

                                            <h1 class="mb-0 fw-bold" style="font-weight:bold; font-size: 65px;"><?php echo strtoupper($school_name) ?></h1>

                                        <?php echo $address; ?><br>

                                        <b>Website:</b> <span><?php echo $website; ?></span> <b>| E-mail:</b> <span> <?php echo $school_email; ?></span>

                                    </div>

                                    <hr>

                                    <div class="report-title" style = "font-size: 26px;">MID-TERM REPORT</div>

                                    <hr>

                                </div>

                                <div class="card-body">

                                    <!-- Student Bio -->

                                    <table style="border-collapse: collapse; border: none; width: 100%; font-size: 14px; text-align: left;">

                                            <tr>

                                                <td style="border: none; max-width: 100px;"><strong>NAME:</strong> <?php echo htmlspecialchars($student_name); ?></td>

                                                <td style="border: none; max-width: 100px;"><strong>CLASS:</strong> <?php echo htmlspecialchars($class); ?> - <?php echo htmlspecialchars($section); ?></td>

                                                <td style="border: none; max-width: 100px;"><strong>TERM:</strong> <?php echo htmlspecialchars($selected_term); ?></td>            

                                                <td style="border: none; max-width: 100px;"><strong>SESSION:</strong> <?php echo htmlspecialchars($selected_session); ?></td>

                                            </tr>

                                    </table>







<table style="font-size:12px; text-align:center; width:100%; border-collapse:collapse; table-layout:fixed;">

    <thead>

        <tr>

            <th style="font-style: italic; width:25%;">Subject</th>

            <th style="font-style: italic; text-align: center; width:15%;">1st C.A. Test</th>

            <th style="font-style: italic; text-align: center; width:15%;">2nd C.A. Test</th>

            <th style="font-style: italic; text-align: center; width:15%;">Ass/Exe</th>

            <th style="font-style: italic; text-align: center; width:15%;">Total</th>

            <th style="font-style: italic; text-align: center; width:15%;">Grade</th>

        </tr>

    </thead>

    <tbody>

                                            <?php if (!empty($subjects_results)) : ?>

<?php foreach ($subjects_results as $result): ?>

    <?php

    // Determine each score display

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





    // Calculate Ass/Exe

if ($class_performance === 'AB' && $weekly_assessment === 'AB') {

    $ass_exe = 'AB'; // both absent

} elseif ($class_performance === 'AB') {

    $ass_exe = $weekly_assessment; // only class performance absent

} elseif ($weekly_assessment === 'AB') {

    $ass_exe = $class_performance; // only weekly assessment absent

} else {

    $ass_exe = $class_performance + $weekly_assessment; // both present

}



    // Collect scores for numeric sum

    $scores = [$test_score, $test_score2, $class_performance, $weekly_assessment];

    $numeric_scores = array_filter($scores, 'is_numeric');



    // Calculate total or show AB if all absent

$total = 0;

foreach ([$test_score, $test_score2, $ass_exe] as $score) {

    if (is_numeric($score)) $total += $score;

}



    // Grade logic (only if numeric)

    $grade = '';

    if (is_numeric($total)) {

        if ($total >= 25) $grade = 'Excellent';

        elseif ($total >= 20) $grade = 'Very Good';

        elseif ($total >= 15) $grade = 'Good';

        elseif ($total >= 10) $grade = 'Pass';

        else $grade = 'Fair';

    } else {

        $grade = '-'; // or leave blank for AB

    }

    ?>

    

    <tr>

        <td><?= htmlspecialchars($result['subject']) ?></td>

        <td><?= $test_score ?></td>

        <td><?= $test_score2 ?></td>

        <td><?= $ass_exe ?></td>

        <td><?= $total ?></td>

        <td><?= $grade ?></td>

    </tr>

<?php endforeach; ?>

                                            <?php else : ?>

                                                <tr>

                                                    <td colspan="6" style="text-align: center;">No results found.</td>

                                                </tr>

                                            <?php endif; ?>

                                        </tbody>

                                    </table>



                                    <table style="width: 100%; margin-top: 20px; border-collapse: collapse; border: none;">

                                        <tr>

                                            <td style="padding: 10px; border: none; width: 100%;">

                                                <label for="class-teacher-comment"><strong>Class Teacher's Comment:</strong></label>

                                                <span><?= htmlspecialchars($result['remarks_test']) ?></span>

                                            </td>

                                        </tr>

                                        <tr>

                                            <td style="padding: 10px; border: none; width: 100%;">

                                                <label for="class-teacher-comment"><strong>Principal's Comment:</strong></label>

                                                <span><?= htmlspecialchars($principal_remarks) ?></span>

                                            </td>

                                        </tr>

                                    </table>









                                </div>

                            </div>

                        </div>

                        <div class="text-center mb-3">

                            <button type="button" class="btn btn-primary" onclick="PrintFunction()" name="submit" target="_blank"><i class="fas fa-print"></i>

                                Print

                            </button>

                            <a href="download_result_test.php?session_id=<?= $session_id ?>&term_id=<?= $term_id ?>&class=<?= urlencode($class) ?>" class="btn btn-success approve" target="_blank">

                                <i class="fas fa-file-pdf"></i> Download as PDF

                            </a>

                        </div>

                    </div>

                </section>



            <?php else: ?>

                <section class="content">

                    <div class="container-fluid">

                        <div class="alert alert-warning mt-5">

                            <p class="mb-0">Result for <strong><?= $selected_term ?> </strong> <strong><?= $selected_session ?> session</strong> has not been published yet.</p>

                        </div>

                    </div>

                </section>

            <?php endif; ?>

        </div>

        <!-- Footer -->

        <?php @include("includes/footer.php"); ?>

        <?php @include("includes/foot.php"); ?>

    </div>



    <!-- jQuery and Bootstrap JS -->

    <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 Section</option>');

                }

            });

        });

    </script>

    <script>

        function PrintFunction() {

            var session = "<?= $session_id ?>";

            var term = "<?= $term_id ?>";

            var classs = "<?= $class ?>";

            var tabid = "<?= $tabSessionID ?>";







            // Check if start and end dates are provided

            if (session && term && classs) {

                var url = "print_result_test.php?session_id=" + session + "&term_id=" + term + "&class=" + classs + "&tab_id=" + tabid;

                // Redirect to generate PDF

                window.location.href = url;

            } else {

                alert("Class and Section empty.");

            }

        }

    </script>



</body>



</html>