<?php
include("../database/auth_check.php");
$con = mysqli_connect("localhost","root","","WSAS");
if (!$con) die("Database connection failed");

// Get student
if (!isset($_GET['student_id'])) die("No student selected");
$student_id = (int) $_GET['student_id'];

$student_sql = "
  SELECT s.*, c.course_name
  FROM adminstudent s
  LEFT JOIN admincourse c ON s.course_id = c.course_id
  WHERE s.student_id = $student_id";
$student_res = mysqli_query($con, $student_sql);
$student = mysqli_fetch_assoc($student_res);

$is_alumni = false;
 
$alumni_check = mysqli_query($con, "
    SELECT 1 FROM alumni 
    WHERE student_id = $student_id 
    LIMIT 1
");

if($alumni_check && mysqli_num_rows($alumni_check) > 0){
    $is_alumni = true;
}
// Get active school year
$sy_q = mysqli_query($con, "SELECT * FROM school_year WHERE is_active = 1 LIMIT 1");
$sy = mysqli_fetch_assoc($sy_q);
$semester = (strpos(strtolower($sy['semester'] ?? ''), '1') !== false) ? 1 : 2;

// Get SOA fees
$fee_sql = "
    SELECT s.tuition_fee, s.misc_fee, s.special_fee, s.subj_fee, s.total_fee, 
           s.down_payment, s.balance_fee, s.monthly_fee
    FROM soa s
    JOIN enroll_student e ON s.enroll_id = e.enroll_id
    WHERE e.student_id = $student_id
    LIMIT 1";
$fee_res = mysqli_query($con, $fee_sql);
$fee = mysqli_fetch_assoc($fee_res) ?? [
    'tuition_fee'=>0,'misc_fee'=>0,'special_fee'=>0,'subj_fee'=>0,'total_fee'=>0,
    'down_payment'=>0,'balance_fee'=>0,'monthly_fee'=>0
];

// Get subjects with student status and fees
$subjects_sql = "
SELECT 
    cs.year_level,
    a.subject_id, a.subject_code, a.subject_name, a.total_unit,
    f.fee_name, f.fee_amount, f.subject_fee, 
    sc.sc_status, cs.semester,

    pre.subject_name AS prereq_name,
    sc_pre.sc_status AS prereq_status

FROM course_subject cs
JOIN adminsubject a ON cs.subject_id = a.subject_id

LEFT JOIN student_curriculum sc 
    ON a.subject_id = sc.subject_id 
    AND sc.student_id = $student_id

LEFT JOIN subject_prerequisite sp 
    ON a.subject_id = sp.subject_id

LEFT JOIN adminsubject pre 
    ON sp.prerequisite_id = pre.subject_id

LEFT JOIN student_curriculum sc_pre 
    ON sp.prerequisite_id = sc_pre.subject_id 
    AND sc_pre.student_id = $student_id

LEFT JOIN subject_fee sf ON a.subject_id = sf.subject_id
LEFT JOIN adminfee f ON sf.fee_id = f.fee_id

WHERE cs.course_id = {$student['course_id']}
ORDER BY cs.year_level, cs.semester
";

$subjects_res = mysqli_query($con, $subjects_sql);

if(mysqli_num_rows($subjects_res) === 0){
    echo "<p>No subjects found for this course.</p>";
}
$curriculum = [];
$subjects = []; 

while($row = mysqli_fetch_assoc($subjects_res)){
    $id = $row['subject_id'];

    // Ensure year_level and semester are integers and not null
    $year = isset($row['year_level']) ? (int)$row['year_level'] : 1;
    $sem = isset($row['semester']) ? (int)$row['semester'] : 1;

    // Initialize arrays to avoid undefined indexes
    if(!isset($curriculum[$year])) $curriculum[$year] = [];
    if(!isset($curriculum[$year][$sem])) $curriculum[$year][$sem] = [];

    $curriculum[$year][$sem][] = $row;

    if(!isset($subjects[$id])){
        $subjects[$id] = [
            'code'=>$row['subject_code'],
            'name'=>$row['subject_name'],
            'units'=>$row['total_unit'],
            'fees'=>[],
            'prereqs'=>[],
            'prereq_ok'=>true
        ];
    }

    if(!empty($row['fee_name'])){
        $subjects[$id]['fees'][] = [
            'name'=>$row['fee_name'],
            'amount'=>$row['fee_amount'],
            'type'=>$row['subject_fee']
        ];
    }

    // prerequisites
    if(!empty($row['prereq_name'])){
        $subjects[$id]['prereqs'][] = [
            'name'=>$row['prereq_name'],
            'status'=>$row['prereq_status']
        ];

        if($row['prereq_status'] !== 'completed'){
            $subjects[$id]['prereq_ok'] = false;
        }
    }
}
// Get Tuition Fee and Misc Fee amounts from adminfee
$fee_query = mysqli_query($con, "SELECT fee_name, fee_amount FROM adminfee");
$adminFees = [];
while($row = mysqli_fetch_assoc($fee_query)){
    $adminFees[$row['fee_name']] = $row['fee_amount'];
}
// Fetch available discounts for non-alumni
$discounts = [];
if(!$is_alumni){
    $disc_q = mysqli_query($con, "SELECT * FROM admindiscount");
    while($row = mysqli_fetch_assoc($disc_q)){
        $discounts[] = $row; // id, name, amount (percentage)
    }
}
$minDownPayment = floatval($adminFees['MINIMUM DOWN PAYMENT'] ?? 0);

$alumni_tf = 0;

if($is_alumni){
    $alumni_q = mysqli_query($con, "
        SELECT alumni_tf 
        FROM alumni 
        WHERE student_id = $student_id
        LIMIT 1
    ");
    $alumni_data = mysqli_fetch_assoc($alumni_q);
    $alumni_tf = $alumni_data['alumni_tf'] ?? 0;
}
?>
<?php
if (!$student) {
    die("Error: Student not found. ID = $student_id");
}
?>

<!DOCTYPE html>
<html>
<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>Enroll Student - Admin</title>
    <link rel="shortcut icon" type="x-icon" href="../images/logo.png">
    <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/navstyle.css">
<style>
/* reuse your styles */
.disabled {
    pointer-events: none;
}
.done {
    background: #d4edda;
}
.completed {
    background: #d4edda;
}

.enrolled {
    background: #fff3cd;
}
</style>
<style>
    .dashboard-container {
    display: flex;
    height: 100vh;
    font-family: "Segoe UI", sans-serif;
    background-color: #f4f6f8;
    }

    .mainbar {
    margin-left: 280px;
    width: calc(100% - 280px);
    flex: 1;
    display: flex;
    flex-direction: column;
}

    .open-btn {
    background-color: #4a9c3f;
    color: #fff;
    padding: 10px 18px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-weight: 500;
    transition: background-color 0.3s;
    }

    .open-btn:hover {
    background-color: #3e8c36;
    }

    /* Main content */
    .mainbar-context {
    flex: 1;
    padding: 20px 25px;
    overflow-y: auto;
    }

    /* Inner containers */
    .container, .container1 {
    display: flex;
    gap: 20px;
    flex-wrap: wrap;
    margin-bottom: 20px;
    }

    .courses {
    background-color: #4a9c3f;
    color: #fff;
    padding: 20px;
    flex: 1 1 300px;
    border-radius: 10px;
    text-align: center;
    box-shadow: 0 4px 12px rgba(0,0,0,0.05);
    }

    /* Table Styling */
    table {
    width: 100%;
    border-collapse: collapse;
    border-radius: 10px;
    overflow: hidden;
    box-shadow: 0 4px 10px rgba(0,0,0,0.05);
    text-align: center;
    background: #fff;
    }

    table th, table td {
    padding: 12px 15px;
    border-bottom: 1px solid #e0e0e0;
    font-size: 14px;
    color: #333;
    }

    table th {
    background-color: #4a9c3f;
    color: #fff;
    font-weight: 600;
    }

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

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

    .upd_btn, .del_btn {
    text-decoration: none;
    font-weight: 500;
    padding: 6px 12px;
    border-radius: 6px;
    transition: 0.3s;
    }

    .upd_btn {
    background: #1261A0;
    color: #fff;
    }

    .upd_btn:hover {
    background: #0f4d80;
    }

    .del_btn {
    background: #EE7A02;
    color: #fff;
    }

    .del_btn:hover {
    background: #c36100;
    }

    /* Search Box */
    .search-container {
    margin-bottom: 15px;
    text-align: right;
    }

    .search-input {
    padding: 8px 12px;
    width: 220px;
    border: 1px solid #ccc;
    border-radius: 6px;
    font-size: 14px;
    }

    .search-input:focus {
    outline: none;
    border-color: #4a9c3f;
    box-shadow: 0 0 3px rgba(74,156,63,0.5);
    }

    </style>
    <style>
    /* Modal Overlay */
    .modal {
    display: none;
    position: fixed;
    z-index: 1000;
    inset: 0; 
    background: rgba(0,0,0,0.5);
    overflow-y: auto;
    padding: 20px;
    transition: opacity 0.3s ease;
    }

    /* Modal Content */
    .modal-content {
    background: #fff;
    max-width: 480px;
    width: 100%;
    margin: 80px auto;
    padding: 30px 25px;
    border-radius: 12px;
    box-shadow: 0 8px 24px rgba(0,0,0,0.2);
    animation: pop 0.3s ease;
    position: relative;
    box-sizing: border-box;
    }

    /* Pop Animation */
    @keyframes pop {
    from { transform: scale(0.85); opacity: 0; }
    to { transform: scale(1); opacity: 1; }
    }

    /* Close Button */
    .close-btn {
    position: absolute;
    top: 15px;
    right: 20px;
    font-size: 26px;
    font-weight: bold;
    cursor: pointer;
    color: #444;
    transition: color 0.3s;
    }
    .close-btn:hover {
    color: #4a9c3f;
    }

    /* Modal Title */
    .discount-title {
    text-align: center;
    font-size: 24px;
    font-weight: 600;
    margin-bottom: 25px;
    color: #333;
    }

    /* Form Styles */
    .discount-form {
    display: flex;
    flex-direction: column;
    gap: 18px;
    }

    .form-group {
    display: flex;
    flex-direction: column;
    }

    .form-label {
    font-weight: 500;
    margin-bottom: 6px;
    color: #555;
    font-size: 14px;
    }

    .form-input {
    padding: 12px 14px;
    font-size: 15px;
    border-radius: 8px;
    border: 1px solid #ccc;
    outline: none;
    transition: border-color 0.3s, box-shadow 0.3s;
    }

    .form-input:focus {
    border-color: #4a9c3f;
    box-shadow: 0 0 0 2px rgba(74,156,63,0.2);
    }

    /* Submit Button */
    .submit-btn {
    padding: 14px 0;
    background-color: #4a9c3f;
    color: #fff;
    font-weight: 600;
    font-size: 15px;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    transition: background-color 0.3s;
    }

    .submit-btn:hover {
    background-color: #3e8c36;
    }

    /* Responsive for Mobile */
    @media (max-width: 500px) {
    .modal-content {
        margin: 60px 15px;
        padding: 25px 20px;
    }

    .form-input {
        font-size: 14px;
        padding: 10px 12px;
    }

    .submit-btn {
        font-size: 14px;
    }
    }

    .readonly-style {
        background-color: #e9ecef;
        color: #6c757d;
        cursor: not-allowed;
        border: 1px solid #ccc;
    }

    .sticky-enroll-bar {
        position: sticky;
        top: 0;
        z-index: 999;
        background: #f4f6f8;
        padding: 10px 0;
        border-bottom: 1px solid #ddd;
        display: flex;
        justify-content: flex-end;
    }
    </style>
</head>

<body>
<div class="dashboard-container">
<?php include('../adminpanel/adminnav.php'); ?>

<aside class="mainbar">

<div class="mainbar-context">
    <div class="sticky-enroll-bar">
    <button type="button" onclick="previewEnroll()" class="open-btn">
        Enroll Selected
    </button>
</div>

<form method="POST" action="../database/enroll_student.php" id="enrollForm">
    <input type="hidden" name="student_id" value="<?= $student_id ?>">
    <input type="hidden" name="course_id" value="<?= $student['course_id'] ?>">
    <input type="hidden" name="sy_id" value="<?= $sy['sy_id'] ?>">
    <input type="hidden" name="semester" value="<?= $semester ?>">
    <input type="hidden" name="year_level" value="<?= $student['year_level'] ?? '' ?>">
    <input type="hidden" name="student_status" value="Enrolled">
    <input type="hidden" name="down_payment" id="downPaymentInput" value="<?= $fee['down_payment'] ?? 0 ?>">
    <p id="dpError" style="color:red; display:none;"></p>

<?php foreach($curriculum as $year => $semesters): ?>
    <h4><?= $year ?> Year</h4>

    <?php foreach([1,2] as $sem): ?>
        <h4>
            <?= $sem==1 ? '1st Semester' : '2nd Semester' ?>
        </h4>
        <h4><input type="checkbox" class="select-semester" data-year="<?= $year ?>" data-sem="<?= $sem ?>"> Select All</h4>

        <?php 
        $rows = $curriculum[$year][$sem] ?? []; 
        if(empty($rows)){
            echo "<p>No subjects available</p>";
            continue;
        }
        ?>

        <table>
        <tr>
            <th>Select</th>
            <th>Code</th>
            <th>Subject</th>
            <th>Prerequisites</th>
            <th>Status</th>
        </tr>

        <?php foreach($rows as $row): 
            $status = $row['sc_status'] ?? 'not_taken';
            $row_sem = (int) $row['semester'];
            $sub = $subjects[$row['subject_id']];

            $disabled = (
                $status==='completed' || 
                $status==='enrolled' || 
                !$sub['prereq_ok'] ||
                ($row_sem != $semester) // optional, keep this to disable other semester
            );
        ?>
        <tr class="<?= $status==='completed'?'completed':($status==='enrolled'?'enrolled':'') ?>">
            <td>
                <input type="checkbox" 
                    name="subjects[]" 
                    value="<?= $row['subject_id'] ?>" 
                    class="subject-checkbox"
                    data-year="<?= $year ?>" 
                    data-sem="<?= $sem ?>"
                    <?= $disabled?'disabled':'' ?>>
            </td>

            <td><?= $row['subject_code'] ?></td>
            <td><?= $row['subject_name'] ?></td>

            <td>
            <?php
            if(empty($sub['prereqs'])){
                echo "None";
            } else {
                foreach($sub['prereqs'] as $p){
                    echo ($p['status']==='completed' ? "✅" : "❌") . " {$p['name']}<br>";
                }
            }
            ?>
            </td>

            <td>
            <?php
            if($status==='completed') echo "✅ Completed";
            elseif($status==='enrolled') echo "🟡 Currently Enrolled";
            elseif(!$sub['prereq_ok']) echo "🔒 Prerequisite Required";
            elseif($row_sem != $semester) echo "⛔ Not Available";
            else echo "🟢 Available";
            ?>
            </td>
        </tr>
        <?php endforeach; ?>
        </table><br>

    <?php endforeach; ?>
<?php endforeach; ?>

<div id="confirmModal" class="modal">
<div class="modal-content">
<span onclick="closeModal()" class="close-btn">&times;</span>
<h2>Enrollment Summary</h2>
<div id="summary"></div>
<?php if(!$is_alumni && !empty($discounts)): ?>
    <div class="form-group">
    <label class="form-label">Select Discount</label>
    <select name="discount_id" id="discountSelect" class="form-input" onchange="updateBalance()" <?= $is_alumni ? 'disabled' : '' ?>>
        <option value="">No Discount</option>
        <?php foreach($discounts as $d): ?>
            <option value="<?= $d['discount_id'] ?>" 
                    data-amount="<?= $d['discount_amount'] ?>"
                    data-type="<?= strtolower($d['discount_name']) ?>">
                <?= $d['discount_name'] ?> (<?= $d['discount_amount'] ?>%)
            </option>
        <?php endforeach; ?>
    </select>
</div>
<?php endif; ?>
<button type="button" id="confirmBtn" onclick="submitEnroll()" class="open-btn">
    Confirm Enroll
</button>
</div>
</div>

<br>
</form>
</div>
</aside>
</div>

<div id="finalConfirmModal" class="modal">
  <div class="modal-content">
    <h3>Confirm Enrollment</h3>
    <p>Are you sure you want to enroll the selected subjects?</p>
    <br>

    <button id="finalYesBtn" class="open-btn">Yes, Enroll</button>
    <button id="finalNoBtn" class="close-btn">Cancel</button>
  </div>
</div>

<script>
document.querySelectorAll('.select-semester').forEach(semCheckbox => {
    semCheckbox.addEventListener('change', function(){
        let year = this.dataset.year;
        let sem = this.dataset.sem;
        let checked = this.checked;

        document.querySelectorAll(`.subject-checkbox[data-year="${year}"][data-sem="${sem}"]`).forEach(subCheckbox => {
            if(!subCheckbox.disabled){
                subCheckbox.checked = checked;
            }
        });
    });
});

let subjects = <?= json_encode($subjects); ?>;
let feeData = <?= json_encode($fee); ?>;
let adminFees = <?= json_encode($adminFees); ?>;
let isAlumni = <?= json_encode($is_alumni); ?>;
let alumniTF = <?= json_encode($alumni_tf); ?>;
let downPaymentMin = <?= $minDownPayment ?>;
let downPayment = downPaymentMin;

function previewEnroll() {
    let checkboxes = document.querySelectorAll('input[name="subjects[]"]:checked');
    if (checkboxes.length === 0) {
        alert("Select at least one subject");
        return;
    }

    // Identify lab subjects
    let comlabSubjects = [];
    checkboxes.forEach(cb => {
        let sub = subjects[cb.value];
        if (!sub) return;
        if (sub.fees.some(f => f.name.includes('Computer Laboratory Fee'))) {
            comlabSubjects.push({ id: cb.value, code: sub.code });
        }
    });

    // Pick the "full lab" subject
    let fullLabSubject = null;
    fullLabSubject = comlabSubjects.find(s => s.code.includes('CSPC'))?.id;
    if (!fullLabSubject && comlabSubjects.length > 0) {
        let highestCSCC = 0;
        comlabSubjects.forEach(s => {
            let m = s.code.match(/CSCC(\d+)/i);
            if (m && parseInt(m[1]) > highestCSCC) {
                highestCSCC = parseInt(m[1]);
                fullLabSubject = s.id;
            }
        });
    }

    let tableHTML = `<table style="width:100%;border-collapse:collapse;margin-bottom:15px;">
        <tr><th>Code</th><th>Subject</th><th>Units</th><th>Fees</th></tr>`;

    let totalUnits = 0;
    let tuitionUnits = 0;
    let subjFeeTotal = 0;

    checkboxes.forEach(cb => {
        let sub = subjects[cb.value];
        let feesHTML = "";

        let isSpecial = sub.fees.some(f => f.type === 'Special');

        if (!isSpecial) tuitionUnits += parseFloat(sub.units);

        sub.fees.forEach(f => {
            let feeAmount = parseFloat(f.amount);

            // Use dynamic downPaymentMin for lab subjects if needed
            if (f.name.includes('Computer Laboratory Fee')) {
                feeAmount = cb.value === fullLabSubject
                    ? parseFloat(feeData.comlab_fee || f.amount)
                    : parseFloat(feeData.other_comlab_fee || downPaymentMin);
            }

            feesHTML += `${f.name}: ₱${feeAmount.toLocaleString()}<br>`;
            subjFeeTotal += feeAmount;
        });

        totalUnits += parseFloat(sub.units);

        tableHTML += `<tr>
            <td>${sub.code}</td>
            <td>${sub.name}</td>
            <td>${sub.units}</td>
            <td>${feesHTML}</td>
        </tr>`;
    });

    tableHTML += `</table>`;

    let tuitionPerUnit = parseFloat(adminFees['Tuition Fee'] || 0);
    let tuition = isAlumni
    ? parseFloat(alumniTF)
    : tuitionPerUnit * tuitionUnits;

    let misc = parseFloat(adminFees['Miscellaneous Fee'] || 0);

    let total = tuition + misc + subjFeeTotal;
    let balance = total - downPayment;
    let monthly = balance / 4;

    document.getElementById("summary").innerHTML = `
        ${tableHTML}
        <p><strong>Total Units:</strong> ${totalUnits}</p>
        <p>
        ${isAlumni 
            ? `Tuition Fee: ₱${tuition.toLocaleString()}`
            : `Tuition Fee (₱${tuitionPerUnit}/unit × ${tuitionUnits} units): ₱${tuition.toLocaleString()}`
        }
        </p>
        <p>Misc Fee: ₱${misc.toLocaleString()}</p>
        <p>Other Subject Fees Total: ₱${subjFeeTotal.toLocaleString()}</p>
        <hr>
        <p><strong>Total Fee:</strong> ₱<span id="totalFee">${total.toLocaleString()}</span></p>
        <p>Down Payment (min ₱${downPaymentMin}):
        <input type="number" id="dpInput" value="${downPaymentMin}" min="${downPaymentMin}" oninput="updateBalance()">
        <p>Balance Fee: ₱<span id="balanceFee">${balance.toLocaleString()}</span></p>
        <p>Monthly Payment: ₱<span id="monthlyFee">${monthly.toLocaleString()}</span></p>
           `;

    document.getElementById("confirmModal").style.display = "block";

    setTimeout(updateBalance, 0);
}

function updateBalance() {
    let discountEl = document.getElementById("discountSelect");
    let discountPercent = 0;
    let fullPaymentSelected = false;

    if(discountEl){
    let selectedOption = discountEl.options[discountEl.selectedIndex];

    discountPercent = parseFloat(selectedOption.dataset.amount || 0);

    let discountType = selectedOption.dataset.type || "";
    fullPaymentSelected = discountType.includes("full payment");
}

    let checkboxes = document.querySelectorAll('input[name="subjects[]"]:checked');
    if (checkboxes.length === 0) return;

    let totalUnits = 0;
    let tuitionUnits = 0;
    let subjFeeTotal = 0;

    let comlabSubjects = [];
    checkboxes.forEach(cb => {
        let sub = subjects[cb.value];
        if (sub.fees.some(f => f.name.includes('Computer Laboratory Fee'))) {
            comlabSubjects.push({ id: cb.value, code: sub.code });
        }
    });

    let fullLabSubject = comlabSubjects.find(s => s.code.includes('CSPC'))?.id;
    if (!fullLabSubject && comlabSubjects.length > 0) {
        let highestCSCC = 0;
        comlabSubjects.forEach(s => {
            let m = s.code.match(/CSCC(\d+)/i);
            if (m && parseInt(m[1]) > highestCSCC) {
                highestCSCC = parseInt(m[1]);
                fullLabSubject = s.id;
            }
        });
    }

    checkboxes.forEach(cb => {
        let sub = subjects[cb.value];
        let isSpecial = sub.fees.some(f => f.type === 'Special');
        if (!isSpecial) tuitionUnits += parseFloat(sub.units);

        sub.fees.forEach(f => {
            let feeAmount = parseFloat(f.amount);
            if (f.name.includes('Computer Laboratory Fee')) {
                feeAmount = cb.value === fullLabSubject
                    ? parseFloat(feeData.comlab_fee || f.amount)
                    : parseFloat(feeData.other_comlab_fee || downPaymentMin);
            }
            subjFeeTotal += feeAmount;
        });

        totalUnits += parseFloat(sub.units);
    });

    let tuitionPerUnit = parseFloat(adminFees['Tuition Fee'] || 0);
    let tuition;

        if(isAlumni){
            tuition = parseFloat(alumniTF);
        }else {
        // Non-alumni pay per-unit tuition
        let tuitionPerUnit = parseFloat(adminFees['Tuition Fee'] || 0);
        tuition = tuitionPerUnit * tuitionUnits;

        // Apply discount if applicable
        if(discountPercent > 0){
            if(fullPaymentSelected){
                // Full payment discount
                tuition = tuition - (tuition * (discountPercent / 100));
            } else {
                // Regular discount (if you still want it)
                tuition = tuition - (tuition * (discountPercent / 100));
            }
        }
    }

    let misc = parseFloat(adminFees['Miscellaneous Fee'] || 0);
    let total = tuition + misc + subjFeeTotal;

    let dpInputEl = document.getElementById("dpInput");


        let currentDP = parseFloat(dpInputEl.value);
        let errorEl = document.getElementById("dpError");
        let confirmBtn = document.getElementById("confirmBtn");

        if(isNaN(currentDP) || currentDP < downPaymentMin){
            errorEl.style.display = "block";
            errorEl.innerText = "Minimum down payment is ₱" + downPaymentMin;

            confirmBtn.disabled = true;
            confirmBtn.style.opacity = "0.6";
            confirmBtn.style.cursor = "not-allowed";
        } else {
            errorEl.style.display = "none";

            confirmBtn.disabled = false;
            confirmBtn.style.opacity = "1";
            confirmBtn.style.cursor = "pointer";
        }

    if (currentDP < downPaymentMin) {
        errorEl.style.display = "block";
        errorEl.innerText = "Minimum down payment is ₱" + downPaymentMin;
    } else {
        errorEl.style.display = "none";
    }

    let balance = total - currentDP;
    let monthly = fullPaymentSelected ? 0 : balance / 4;

    document.getElementById("totalFee").innerText = total.toLocaleString();
    document.getElementById("downPaymentInput").value = currentDP;
    document.getElementById("balanceFee").innerText = balance.toLocaleString();
    document.getElementById("monthlyFee").innerText = monthly.toLocaleString();


    if(currentDP < downPaymentMin || isNaN(currentDP)){
        confirmBtn.disabled = true;
        confirmBtn.style.opacity = "0.6";
        confirmBtn.style.cursor = "not-allowed";
    } else {
        confirmBtn.disabled = false;
        confirmBtn.style.opacity = "1";
        confirmBtn.style.cursor = "pointer";
    }
}

const finalModal = document.getElementById("finalConfirmModal");
const finalYesBtn = document.getElementById("finalYesBtn");
const finalNoBtn = document.getElementById("finalNoBtn");
const enrollForm = document.getElementById("enrollForm");

// Confirm enrollment
finalYesBtn.addEventListener("click", () => {
    enrollForm.submit();
});

// Cancel
finalNoBtn.addEventListener("click", () => {
    finalModal.style.display = "none";
});

// Click outside modal
window.addEventListener("click", (e) => {
    if (e.target === finalModal) {
        finalModal.style.display = "none";
    }
});

function submitEnroll(){
    document.getElementById("finalConfirmModal").style.display = "block";
    
}
function closeModal(){ document.getElementById("confirmModal").style.display="none"; }
</script>

</body>
</html>