<?php
date_default_timezone_set('Asia/Manila');
session_start();

include('../login/check_flogin.php');

if (!isset($_SESSION['student_id'])) {
    header("Location: ../login/student_login.php");
    exit();
}

$con = new mysqli('localhost', 'root', '', 'WSAS');
if ($con->connect_error) {
    die("Connection failed: " . $con->connect_error);
}

$student_id = (int) $_SESSION['student_id'];

// Student info
$stmt = $con->prepare("
    SELECT s.*, c.course_name
    FROM adminstudent s
    LEFT JOIN admincourse c ON s.course_id = c.course_id
    WHERE s.student_id = ?
");
$stmt->bind_param("i", $student_id);
$stmt->execute();
$student = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$student) {
    die("Student not found in database!");
}

$total_units = 0;
$total_lecture = 0;
$total_lab = 0;

$per_unit = 0;
$downpayment_amount = 0;

// Discount
$discount_percent = 0;
$discount_name = '';
$discount_amount = 0;

$stmt = $con->prepare("
    SELECT d.discount_name, d.discount_amount
    FROM student_discount sd
    JOIN admindiscount d ON sd.discount_id = d.discount_id
    WHERE sd.student_id = ?
    LIMIT 1
");

$stmt->bind_param("i", $student_id);
$stmt->execute();
$disc_res = $stmt->get_result();

if ($disc_res && $disc_res->num_rows > 0) {
    $disc = $disc_res->fetch_assoc();
    $discount_percent = (float)$disc['discount_amount'];
    $discount_name = $disc['discount_name'];
}
$stmt->close();

// S.Y.
$sy = $con->query("
    SELECT * FROM school_year 
    WHERE is_active = 1 
    LIMIT 1
")->fetch_assoc();

if (!$sy) {
    die("No active school year found!");
}

// Tuition per unit 
$res = $con->query("
    SELECT fee_amount 
    FROM adminfee 
    WHERE fee_name='Tuition Fee'
    LIMIT 1
");

$per_unit = ($res && $res->num_rows > 0)
    ? (float)$res->fetch_object()->fee_amount
    : 0;

// Fetch enrolled subjects of the student
$subjects = [];
$total_units = 0;
$total_lecture = 0;
$total_lab = 0;

$subject_sql = "
SELECT 
    ss.subject_id,
    a.subject_code,
    a.subject_name,
    a.lecture_unit,
    a.lab_unit,
    (a.lecture_unit + a.lab_unit) AS total_unit,
    COALESCE(f.fee_amount, 0) AS lab_fee
FROM student_subject ss
JOIN adminsubject a ON ss.subject_id = a.subject_id
JOIN adminstudent st ON ss.student_id = st.student_id
JOIN course_subject cs 
    ON ss.subject_id = cs.subject_id 
    AND cs.course_id = st.course_id
LEFT JOIN subject_fee sf ON sf.subject_id = ss.subject_id
LEFT JOIN adminfee f ON f.fee_id = sf.fee_id
WHERE ss.student_id = ?
  AND ss.subject_status = 'enrolled'
ORDER BY cs.year_level ASC, FIELD(cs.semester,'1st','2nd','Summer')
";

$stmt = $con->prepare($subject_sql);
$stmt->bind_param("i", $student_id);
$stmt->execute();
$subject_res = $stmt->get_result();


if (!$subject_res) {
    die("Subjects Query Error: " . mysqli_error($con));
}

while ($row = mysqli_fetch_assoc($subject_res)) {

    $id = $row['subject_id'];

    if (!isset($subjects[$id])) {
        $subjects[$id] = [
            'subject_code' => $row['subject_code'],
            'subject_name' => $row['subject_name'],
            'lecture_unit' => (int)$row['lecture_unit'],
            'lab_unit' => (int)$row['lab_unit'],
            'total_unit' => (int)$row['total_unit'],
            'lab_fee' => 0
        ];
    }

    // get fee from DB 
    $lab_fee = (float)$row['lab_fee'];

    $subjects[$id]['lab_fee'] = $lab_fee;

    $total_lecture += (int)$row['lecture_unit'];
    $total_lab += (int)$row['lab_unit'];
    $total_units += (int)$row['total_unit'];
}

$stmt = $con->prepare("
    SELECT 
        tuition_fee,
        misc_fee,
        special_fee,
        subj_fee,
        total_fee,
        down_payment,
        balance_fee,
        monthly_fee,
        discounted_tuition_fee
    FROM soa
    JOIN enroll_student e ON soa.enroll_id = e.enroll_id
    WHERE e.student_id = ?
    ORDER BY soa.soa_id DESC
    LIMIT 1
");

$stmt->bind_param("i", $student_id);
$stmt->execute();
$fee = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$fee) {
    die("SOA record not found. Please check admin computation.");
}

$check = $con->prepare("
    SELECT 1 FROM student_payment
    WHERE student_id = ?
    AND payment_type = 'Downpayment'
    LIMIT 1
");
$check->bind_param("i", $student_id);
$check->execute();
$exists = $check->get_result()->num_rows > 0;
$check->close();

if (!$exists) {
    $downpayment_amount = (float)$fee['down_payment'];

    $stmt = $con->prepare("
        INSERT INTO student_payment (
            student_id,
            payment_type,
            spay_status,
            spay_amount,
            created_at
        )
        VALUES (?, 'Downpayment', 'Verified', ?, NOW())
    ");

    $stmt->bind_param("id", $student_id, $downpayment_amount);
    $stmt->execute();
    $stmt->close();
}

// Tuition fee
$tuition_fee = $total_units * $per_unit;

// Discount computation
$discount_amount = 0;
$discounted_tuition_fee = $tuition_fee;

if ($discount_percent > 0) {
    $discount_amount = $tuition_fee * ($discount_percent / 100);
    $discounted_tuition_fee = $tuition_fee - $discount_amount;
}

$total_tuition = ($discount_percent > 0)
    ? $discounted_tuition_fee
    : $tuition_fee;

$total_fee = $total_tuition
    + (float)$fee['subj_fee']
    + (float)$fee['special_fee']
    + (float)$fee['misc_fee'];

$totalPaid = 0; 
$remaining_balance = $total_fee - $totalPaid;

$total_tuition = ($discount_percent > 0)
    ? $discounted_tuition_fee
    : $tuition_fee;

// Other fees
$laboratory_fee = (float)$fee['subj_fee'];
$cwts_fee       = (float)$fee['special_fee'];
$misc_fee       = (float)$fee['misc_fee'];

// TOTAL FEES
$total_fee = $total_tuition + $laboratory_fee + $cwts_fee + $misc_fee;

// Get total paid
$stmt = $con->prepare("
    SELECT COALESCE(SUM(spay_amount),0) AS total_paid
    FROM student_payment
    WHERE student_id = ?
    AND spay_status IN ('Verified','Underpaid')
    AND payment_type IN ('Downpayment','Tuition')
");
$stmt->bind_param("i", $student_id);
$stmt->execute();
$totalPaid = (float)$stmt->get_result()->fetch_assoc()['total_paid'];
$stmt->close();

// Balance
$remaining_balance = $total_fee - $totalPaid;

if ($remaining_balance < 0) {
    $remaining_balance = 0;
}

// Downpayment
$downpayment_amount = (float)$fee['down_payment'];

// Enrolment
$enroll_query = mysqli_query($con, "
    SELECT * 
    FROM enroll_student 
    WHERE student_id = '$student_id'
    ORDER BY enroll_id DESC
    LIMIT 1
");

$enroll = mysqli_fetch_assoc($enroll_query);

if (!$enroll || !isset($enroll['date_enrolled'])) {
    die("Enrollment record missing!");
}

$startDate = new DateTime($enroll['date_enrolled'], new DateTimeZone('Asia/Manila'));

// Payments
$payments = [];

$stmt = $con->prepare("
    SELECT 
        spay_amount AS amount,
        spay_method AS payment_method,
        created_at
    FROM student_payment
    WHERE student_id = ?
    AND spay_status IN ('Verified','Underpaid')
    AND payment_type = 'Tuition'
    ORDER BY created_at ASC
");

$stmt->bind_param("i", $student_id);
$stmt->execute();
$res = $stmt->get_result();

while ($row = $res->fetch_assoc()) {
    $payments[] = $row;
}

$stmt->close();

// Monthly payments
$monthly_payments = [];

// Allocate downpayment first
$remaining = $totalPaid;

$dpPaid = min($downpayment_amount, $remaining);
$remaining -= $dpPaid;

// Downpayment
$monthly_payments[] = [
    'month' => 'Downpayment',
    'due' => '-',
    'amount_due' => $fee['down_payment'],
    'amount_paid' => $dpPaid,
    'status' => ($dpPaid >= $fee['down_payment']) ? 'Paid' : (($dpPaid > 0) ? 'Underpaid' : 'Unpaid'),
    'mode' => $dpPaid > 0 ? 'Cash' : '-',  
    'date_paid' => $enroll['date_enrolled']
];

// Convert all tuition payments into monthly schedule
$tuition_payments = $payments; 

$today = new DateTime("now", new DateTimeZone('Asia/Manila'));
$remainingCredit = 0;

for ($i = 1; $i <= 4; $i++) {
    $dueDate = clone $startDate;
    $dueDate->modify("+$i month");
    $amountDue = (float)$fee['monthly_fee'];
    
    $paidAmount = 0;
    $lastMethod = '-';
    $lastDate = '-';

    while (!empty($tuition_payments) && $paidAmount < $amountDue) {

        $p = &$tuition_payments[0];

        $toApply = min($p['amount'], $amountDue - $paidAmount);
        $paidAmount += $toApply;

        if (!empty($p['payment_method'])) {
            $lastMethod = $p['payment_method'];
        }

        // keep real timestamp
        $lastDate = $p['created_at'];

        $p['amount'] -= $toApply;

        if ($p['amount'] <= 0) {
            array_shift($tuition_payments);
        }
    }

    // Determine status
    if ($paidAmount >= $amountDue) {
        $status = 'Paid';
    } elseif ($paidAmount > 0) {
        $status = 'Underpaid';
    } else {
        $status = ($today < $dueDate) ? '-' : 'Unpaid';
    }

    $monthly_payments[] = [
        'month' => $i,
        'due' => $dueDate->format('F d, Y'),
        'amount_due' => $amountDue,
        'amount_paid' => $paidAmount,
        'mode' => ($paidAmount > 0 && $lastMethod !== '-' && $lastMethod !== null)
            ? $lastMethod
            : '-',
        'date_paid' => $paidAmount > 0 ? $lastDate : '-',
        'status' => $status
    ];
}

// Exam permit
$examPeriod = $sy['exam_period'] ?? 'none';

$allowMidterm = isset($monthly_payments[2]) 
    && $monthly_payments[2]['status'] === 'Paid';

$allowFinal = ($remaining_balance <= 0);

$allowExamPermit =
    ($examPeriod === 'midterm' && $allowMidterm) ||
    ($examPeriod === 'final' && $allowFinal);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE-edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> Dashboard - Student </title>

    <link rel="shortcut icon" type="x-icon" href="../images/logo.png">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0" />
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@24,400,0,0" />
    <link rel="stylesheet" href="../Style/snavstyle.css">

<style>
    * {
        box-sizing: border-box;
        margin: 0;
        padding: 0;
    }

    body{
        background: #F3F4F4;
    }

    .dashboard-container {
        display: flex;
        height: 100vh;
    }

    .mainbar {
        margin-left: 270px; 
        flex: 1;
        padding: 10px;
        transition: all 0.4s ease;
        overflow-y: auto;
        display: flex;          
        flex-direction: column; 
    }

    .mainbar-header {
        padding: 6px 12px;
        background-color: #3e7f31;
        border-radius: 10px;
        margin-bottom: 20px;
    }

    .mainbar-header h1 {
        margin: 0;
        color: white;
        font-size: 18px;
    }

    .mainbar-context {
        flex: 1;
        padding: 20px;
        overflow-y: auto;
    }

    .container{
        padding: 10px;
        border-radius: 10px;
        width: 100%;
        max-width: 1000px;
        margin: 40px auto;
        display: flex;
        flex-direction: column;
        margin: 10px auto; 
    }

    table {
        width: 100%;
        border-collapse: collapse; 
        background: rgba(255, 255, 255, 0.95);
        border-radius: 10px;
        overflow: hidden;
        font-family: "Segoe UI", sans-serif;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); 
        text-align: center;
        font-size: 11px;
    }

    table tr {
        cursor: pointer;
    }

    table th {
        background-color: #2b5820; 
        color: white;
        font-weight: 600;
        padding: 5px;
        border: 1px solid #2b5820; 
    }

    table td {
        border: 1px solid #ccc; 
        padding: 3px;
        color: #222;
    }

    table tr:nth-child(even) {
        background-color: #fff;
    }

    table tr:hover {
        background-color: rgba(74, 156, 63, 0.1);
        transition: background-color 0.3s ease;
    }

    .soa-fee-container {
        display: flex;
        flex-direction: column;
        gap: 20px;
    }

    .top-section {
        display: flex;
        gap: 10px;
        align-items: flex-start; 
    }

    .subject-section {
        width: 70%;
    }

    .fees-section th {
        width: 40%;
    }

    .fees-section td {
        width: 30%;
    }

    .monthly-payment-section {
        width: 100%;
    }

    table th, table td {
        padding: 3px;
        border: 1px solid #ccc;
    }

    table th {
        background-color: #2b5820;
        color: white;
    }

    .table-wrapper {
        overflow-x: auto;
        -webkit-overflow-scrolling: touch; 
    }

    .fees-summary-table {
        min-width: 300px; 
    }

/* EXAM PERMIT MODAL */
.modal {
    display: none; 
    justify-content: center;
    align-items: center;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.3);
    z-index: 1000;
    overflow-y: auto;
}

.modal-content {
    background: #fff;
    padding: 25px 35px;
    border-radius: 10px;
    width: 60%;            
    max-width: 500px;
    box-shadow: 0 5px 15px rgba(0,0,0,0.3);
    margin: auto;
    text-align: center;
}

.exampermit-header {
    text-align: center; 
    margin-bottom: 15px;
}

.exampermit-header h3 {
    margin-bottom: 5px;
    font-weight: bold;
    font-size: 14px;
}

.exampermit-header p {
    margin: 0;
    font-size: 11px;
}

.student-details {
    margin-top: 10px;
}

.student-details p {
    margin: 4px 0;
    font-size: 11px;
}

.student-details,
.exampermit-date {
    text-align: left; 
    margin: 0 auto;
    width: 100%;
}

.exampermit-date {
    display: flex;
    margin-top: 10px;
}

.exampermit-date p {
    margin: 0;
    font-size: 11px;
}

.exam-title p {
    margin: 0;
    font-size: 11px;
}

.exam-title {
    text-align: center;
    font-weight: bold;
    margin: 15px 0;
    font-size: 11px;
}

#examPermitModal table {
    box-shadow: none !important;
}

.exampermit-table table {
    table-layout: fixed;
    width: 100%;
}

.exampermit-table td {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.exampermit-table th,
.exampermit-table td {
    border: none;
    padding: 4px 4px;
    font-size: 11px;
    color: #000;
    text-align: left;
}

.exampermit-table th {
    background-color: #fff;
    font-weight: bold;
    text-align: center;
}

.exampermit-table td {
    white-space: nowrap;
    word-break: keep-all;
}

.exampermit-table th:last-child,
.exampermit-table td:last-child {
    text-align: center;
    width: 40%;
}

.exampermit-table tr {
    height: 28px;
}

.exampermit-table tr:hover {
    background: transparent;
}

.signature-cell {
    text-align: center;
}

.profsignature-line {
    display: inline-block;
    width: 80%;
    border-bottom: 1px solid #000;
    margin-top: 10px;
}

.modal-buttons {
    margin-top: 40px;
    text-align: center;
}

.modal-buttons .btn-save,
.modal-buttons .btn-cancel {
    padding: 6px 12px;
    margin: 0 5px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 11px;
    font-weight: bold;
    width: 100px;
}

.modal-buttons .btn-save {
    background-color: #4CAF50;
    color: #fff;
}

.modal-buttons .btn-save:hover {
    background-color: #43a047;
}

.modal-buttons .btn-cancel {
    background-color: #ccc;
    color: #000;
}

.modal-buttons .btn-cancel:hover {
    background-color: #ADADAD;
}

    .exam-btn-container {
        display: flex;
        justify-content: left;
        margin-top: 5px;   
        padding: 0 6px; 
    }

    .exam-btn {
        width: 100%;              
        max-width: 160px;         
        border-radius: 6px;
        font-size: 11px;
        padding: 6px;
        background: #2b5820;
        color: #fff;
        border: none;
        font-weight: bold;
        cursor: pointer;
    }

    .exam-btn:disabled {
        opacity: 0.5;
        cursor: not-allowed;
    }

.table-section {
    margin-bottom: 20px;
}

.table-title {
    font-size: 11px;
    font-weight: 600;
    color: #333; 
    margin-bottom: 2px;
    letter-spacing: 0.5px;   
    text-align: center; 
    font-weight: 600;
}

.fees-section table {
    margin-top: 0;    
}

.divider {
    width: 100%;
    margin: 0; 
    height: 1px;
    background: #bdbdbd; 
    margin-bottom: 10px;
}

.subject-section,
.fees-section,
.monthly-payment-section {
    background: #fff;
    padding: 15px;
    border-radius: 10px;
    box-shadow: 0 2px 6px rgba(0,0,0,0.05);
}

/* Tablet */
@media screen and (max-width: 768px) {
    .mainbar {
        margin-left: 0;
        padding: 8px;
        margin-top: 60px;
    }

    .mainbar-header {
        padding: 5px 10px;
        border-radius: 8px;
    }

    .mainbar-header h1 {
        font-size: 16px;
        text-align: center;
    }

    .table-title {
        font-size: 10px;
        font-weight: 600;
    }

    .subject-section,
    .fees-section, 
    .monthly-payment-section {
        font-size: 10px;
        padding: 2px;
    }

    .top-section {
        flex-direction: column;
        gap: 15px;
    }

    .subject-section,
    .fees-section {
        width: 100%;
    }

    .fees-section {
        width: 100%;
    }

    .fees-summary-table th, 
    .fees-summary-table td {
        font-size: 10px;
        padding: 5px;
    }

    table th, table td {
        font-size: 10px;
        padding: 5px;
    }

    .exam-btn-container {
        display: flex;
        justify-content: center;  
        margin-top: 3px;  
        width: 150px;        
    }

    .exam-btn {
        border-radius: 6px;
        font-size: 10px;
        padding: 3px 6px;
        background: #2b5820;
        color: #fff;
        border: none;
        font-weight: bold;
        cursor: pointer;         
    }
}

/* Mobile phone */
@media screen and (max-width: 576px) {
    .mainbar {
        margin-top: 50px;
        padding: 10px;
    }

    .mainbar-header {
        padding: 5px 10px;
        border-radius: 8px;
    }

    .mainbar-header h1 {
        font-size: 12px;
        text-align: center;
    }

    table th, table td {
        font-size: 8px;
        padding: 5px;
    }

    table {
        font-size: 6px;
        min-width: 400px; 
    }

    .table-wrapper {
        overflow-x: auto;
    }

    .table-title {
        font-size: 8px;
        font-weight: 600;
    }

    .subject-section,
    .fees-section, 
    .monthly-payment-section {
        font-size: 8px;
        padding: 2px;
    }

    .fees-summary-table {
        min-width: 150px; 
    }

    .fees-summary-table th, 
    .fees-summary-table td {
        font-size: 8px;
        padding: 5px;
    }

    .subject-section p {
        font-size: 8px;
    }
    
    .monthly-payment-section {
        width: 95%;          
        margin: 0 auto; 
        font-size: 8px; 
    }

    .payment-table th,
    .payment-table td {
        font-size: 8px;   
        padding: 2px;
    }

    .payment-table tfoot td {
        font-size: 8px;
    }

    .exam-btn-container {
        display: flex;
        justify-content: center;  
        margin-top: 3px;  
        width: 130px;        
    }

    .exam-btn {
        border-radius: 6px;
        font-size: 8px;
        padding: 3px 6px;
        background: #2b5820;
        color: #fff;
        border: none;
        font-weight: bold;
        cursor: pointer;         
    }
}

/* Smaller phone */
@media screen and (max-width: 400px) {
    .mainbar-header h1 {
        font-size: 10px;
    }

    .table-title {
        font-size: 6px;
        font-weight: 600;
    }

    table th, table td {
        font-size: 6px;
        padding: 2px;
    }

    table {
        font-size: 6px;
        min-width: 300px;
    }

    .fees-summary-table {
        min-width: 100px;
    }

    .fees-summary-table th, 
    .fees-summary-table td {
        font-size: 6px;
        padding: 2px;
    }

    .subject-section,
    .fees-section, 
    .monthly-payment-section {
        font-size: 6px;
        padding: 2px;
    }

    .subject-section p {
        font-size: 6px;
        font-weight: 500;  
    }

    .payment-table th,
    .payment-table td {
        font-size: 6px;   
        padding: 2px;
    }

    .payment-table tfoot td {
        font-size: 6px;
    }

    .exam-btn-container {
        display: flex;
        justify-content: center;  
        margin-top: 3px;  
        width: 120px;        
    }

    .exam-btn {
        border-radius: 6px;
        font-size: 6px;
        padding: 3px 6px;
        background: #2b5820;
        color: #fff;
        border: none;
        font-weight: bold;
        cursor: pointer;         
    }
}
</style>
</head>

<body>
    <!-- Side Navigation -->
    <?php include('studentnav.php'); ?>
    <!-- MAIN -->
    <aside class="mainbar">
        <div class="mainbar-header">
            <h1> Statement of Account </h1>
        </div>

        <div class="soa-fee-container">
            <div class="top-section">
                <div class="subject-section">
                    <div class="table-title">SUBJECTS ENROLLED</div>
                    <div class="table-divider"></div>
                    <table class="soa-table">
                        <thead>
                            <tr style="font-weight: 600;">
                                <th> Course Code </th>
                                <th> Description </th>
                                <th> Lecture Unit </th>
                                <th> Lab Unit </th>
                                <th> Total Units </th>
                                <th> Other Fees </th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php
                            // Get tuition per unit
                            $tuition_q = mysqli_query($con, "SELECT fee_amount FROM adminfee WHERE fee_name='Tuition Fee' LIMIT 1");
                            $tuition_row = mysqli_fetch_assoc($tuition_q);
                            $per_unit = $tuition_row['fee_amount'] ?? 0;

                            // Initialize totals
                            $total_lab_fee = 0;
                        ?>

                        <?php foreach($subjects as $id => $sub): ?>

                        <?php
                            $lecture = $sub['lecture_unit'] ?? 0;
                            $lab = $sub['lab_unit'] ?? 0;
                            $total_unit = $sub['total_unit'] ?? ($lecture + $lab);

                            // Lab fee computation
                            $labFee = $sub['lab_fee'] ?? 0;

                            // accumulate total
                            $total_lab_fee += $labFee;
                        ?>

                        <tr>
                            <td><?= htmlspecialchars($sub['subject_code'] ?? '') ?></td>
                            <td><?= htmlspecialchars($sub['subject_name'] ?? '') ?></td>
                            <td><?= $lecture ?></td>
                            <td><?= $lab ?></td>
                            <td><?= $total_unit ?></td>
                            <td><?= number_format($labFee, 2) ?></td>
                        </tr>

                        <?php endforeach; ?>

                        <!-- TOTAL ROW -->
                        <tr style="font-weight:bold">
                            <td colspan="2" style="text-align:center;">Total Units</td>
                            <td><?= $total_lecture ?? 0 ?></td>
                            <td><?= $total_lab ?? 0 ?></td>
                            <td><?= $total_units ?? 0 ?></td>
                        </tr>

                        </tbody>
                    </table>
                    <div style=" 
                        margin-top: 10px;
                        text-align: center; 
                        font-weight: bold; 
                        font-size: 11px;
                        color: #2e7d32;
                    ">
                       <p> Tuition Fee = Total Units (<?= $total_units ?>) × Per Unit (₱ <?= number_format($per_unit,2) ?>) = ₱ <?= number_format($total_units * $per_unit, 2); ?></p>
                    </div>
                </div>

                <div class="fees-section">
                    <div class="table-title">FEES SUMMARY</div>
                    <div class="table-divider"></div>
                    <div class="table-wrapper">
                        <table class="fees-summary-table">
                            <tbody>
                            <tr>
                                <th>Tuition Fee</th>
                                <td>₱ <?= number_format($tuition_fee, 2); ?></td>
                            </tr>
                            <tr>
                                <th>Discount</th>
                                <td>
                                    <?= ($discount_percent > 0 && $discount_amount > 0)
                                    ? "₱ " . number_format($discount_amount, 2)
                                    : "-" ?>
                                </td>
                            </tr>
                            <tr>
                                <th>Discounted Tuition Fee</th>
                                <td>
                                <?= $discount_percent > 0 
                                    ? "₱ " . number_format($discounted_tuition_fee, 2)
                                    : "-" ?>
                                </td>
                            </tr>
                            <tr>
                                <th>Laboratory Fee</th>
                                <td>₱ <?= number_format($fee['subj_fee'], 2) ?></td>
                            </tr>
                            <tr>
                                <th>CWTS</th>
                                <td>₱ <?= number_format($fee['special_fee'], 2) ?></td>
                            </tr>
                            <tr>
                                <th>Miscellaneous Fee</th>
                                <td>₱ <?= number_format($fee['misc_fee'], 2) ?></td>
                            </tr>
                            <tr>
                                <th>Total Fees</th>
                                <td>₱ <?= number_format($total_fee, 2); ?></td>
                            </tr>
                            <tr>
                                <th>Downpayment</th>
                                <td>₱ <?= number_format($fee['down_payment'], 2) ?></td>
                            </tr>
                            <tr>
                                <th>Total Balance</th>
                                <td>₱ <?= number_format($remaining_balance, 2); ?></td>
                            </tr>
                            <tr>
                                <th>Monthly</th>
                                <td>₱ <?= number_format($fee['monthly_fee'], 2); ?></td>
                            </tr>
                        </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <div class="monthly-payment-section">
                <div class="table-title">MONTHLY PAYMENT SCHEDULE</div>
                <div class="table-divider"></div>
                <div class="table-wrapper">
                    <table class="payment-table">
                        <thead>
                            <tr style="font-weight: 600;">
                                <th>Month</th>
                                <th>Due Date</th>
                                <th>Amount Due</th>
                                <th>Amount Paid</th>
                                <th>Mode of Payment</th>
                                <th>Date & Time Paid</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php foreach($monthly_payments as $pay): ?>
                        <tr>
                            <td><?= $pay['month'] ?></td>
                            <td><?= $pay['due'] ?></td>
                            <td>₱ <?= number_format($pay['amount_due'],2) ?></td>
                            <td>₱ <?= number_format($pay['amount_paid'],2) ?></td>
                            <td><?= $pay['mode'] ?></td>                           
                            <td>
                                <?php                               
                                if ($pay['date_paid'] != '-') {

                                    $date = new DateTime($pay['date_paid'], new DateTimeZone('Asia/Manila'));

                                    echo $date->format('F d, Y') . ' | ' . $date->format('g:i A');

                                } else {
                                    echo '-';
                                }
                                ?>
                            </td> 
                                <?php
                                $status = $pay['status'] ?? '-';

                                $color = match($status) {
                                    'Paid' => 'green',
                                    'Unpaid' => 'red',
                                    'Underpaid' => 'orange',
                                    default => '#999'
                                };
                                ?>

                                <td style="font-weight: 500; color: <?= $color ?>">
                                    <?= $status ?>
                                </td>
                        </tr>
                        <?php endforeach; ?>
                        </tbody>
                        <tfoot>
                            <tr style="font-weight:bold;">
                                <td colspan="3" style="text-align:center;">
                                    REMAINING BALANCE:
                                </td>

                                <td style="text-align:center;">
                                    ₱ <?= number_format($remaining_balance, 2); ?>
                                </td>

                                <td colspan="3"></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
        <div class="exam-btn-container">
            <button class="exam-btn" id="examBtn" <?= !$allowExamPermit ? 'disabled' : '' ?>>
                Download Exam Permit
            </button>
        </div>
    </aside>

<!-- Exam Permit Modal -->
<div id="examPermitModal" class="modal">
    <div class="modal-content">
        <div class="exampermit-header">
            <h3> COLEGIO DE LOS BAÑOS </h3>
            <p>
                Lopez Avenue, Brgy. Batong Malake, <br>
                Los Baños, Laguna 4030
            </p>
        </div>
        <div class="student-details">
            <p> Name: <span class="line" style="width:200px">
                <?= htmlspecialchars($student['l_name'] ?? 'N/A') ?>, 
                <?= htmlspecialchars($student['f_name'] ?? 'N/A') ?> 
                <?= htmlspecialchars($student['m_name'] ?? '') ?>
            </span></p>
            <p> Course: <?= htmlspecialchars($student['course_name'] ?? 'N/A'); ?></p>
            <p> Semester: <?= htmlspecialchars($sy['semester'] ?? 'N/A'); ?></p>
        </div>
        <div class="exampermit-date">
            <p> Date: <span id="examPermitDate"></span></p>
        </div>
        
        <div class="exam-title">
            EXAM PERMIT <span id="examTypeLabel"></span>
        </div>
        <div class="exampermit-table">
            <table>
                <tr>
                    <th> Subjects </th>
                    <th> Teacher's Signature </th>
                </tr>
                <?php if(!empty($subjects)): ?>
                    <?php foreach($subjects as $sub): ?>
                        <tr>
                            <td>
                                <?= htmlspecialchars($sub['subject_code']) ?> - 
                                <?= htmlspecialchars($sub['subject_name']) ?>
                            </td>
                            <td class="signature-cell">
                                <span class="profsignature-line"></span>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="2">No subjects found.</td>
                    </tr>
                <?php endif; ?>
            </table>
        </div> 
        
        <div class="modal-buttons">
            <button class="btn-save" onclick="downloadExamPermit()"> Download </button>
            <button class="btn-cancel" onclick="closeExamPermitModal()"> Cancel </button>
        </div>
    </div>
</div>

<script>
// Export PHP permission to JS
const allowMidterm = <?= $allowMidterm ? 'true' : 'false'; ?>;
const allowFinal   = <?= $allowFinal ? 'true' : 'false'; ?>;

// Open modal
function openExamPermit() {
    let examType = "";

    if (allowFinal) {
        examType = "FINALS";
    } 
    else if (allowMidterm) {
        examType = "MIDTERM";
    } 
    else {
        alert("Exam permit is not available yet.");
        return;
    }

    const modal = document.getElementById("examPermitModal");
    const dateLabel = document.getElementById("examPermitDate");
    const examLabel = document.getElementById("examTypeLabel");

    dateLabel.innerText = new Date().toLocaleDateString('en-US', {
        year: 'numeric',
        month: 'long',
        day: 'numeric'
    });

    examLabel.innerText = examType;

    modal.style.display = "flex";
}

// Close modal
function closeExamPermitModal() {
    document.getElementById("examPermitModal").style.display = "none";
}

// Download PDF
function downloadExamPermit() {
    const element = document.querySelector("#examPermitModal .modal-content");

    // Clean table formatting for PDF
    element.querySelectorAll("td").forEach(td => {
        td.style.whiteSpace = "nowrap";
        td.style.fontSize = "10px";
    });

    const buttons = element.querySelector(".modal-buttons");
    buttons.style.display = "none";

    const opt = {
        margin: 10,
        filename: 'exam_permit.pdf',
        image: { type: 'jpeg', quality: 1 },
        html2canvas: {
            scale: 3,
            useCORS: true,
            scrollY: 0
        },
        jsPDF: {
            unit: 'mm',
            format: 'a4',
            orientation: 'portrait'
        }
    };

    html2pdf().set(opt).from(element).save().then(() => {
        buttons.style.display = "block";
        closeExamPermitModal();
    });
}

// Close the modal when click outside
window.onclick = function(event) {
    const modal = document.getElementById("examPermitModal");
    if (event.target === modal) {
        modal.style.display = "none";
    }
};
</script>

<script>
document.addEventListener("DOMContentLoaded", function () {
    const btn = document.getElementById("examBtn");

    if (!btn) return;

    btn.addEventListener("click", function () {
        if (this.disabled) return;
        openExamPermit();
    });
});
</script>

    <!-- to download exam permit modal as a PDF file -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js" integrity="sha512-GsLlZN/3F2ErC5ifS5QtgpiJtWd43JWSuIgh7mbzZ8zBps+dvLusV+eNQATqgA/HdeKFVgA5v3S/cIrLF7QnIg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    
    <!-- script -->
    <script type="module" src="https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.esm.js"></script>
    <script nomodule src="https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.js"></script>
</body>
</html>