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

// Set student details
$id = $_SESSION['student_id'];
$cls = $_SESSION['class'];
$st = $_SESSION['stream'];

// Fetch the current session
$currentSessionQuery = "SELECT id, session_name 
                        FROM school_sessions 
                        WHERE start_date <= CURDATE() 
                          AND end_date >= CURDATE() 
                        ORDER BY start_date ASC 
                        LIMIT 1";
$currentSessionResult = $con->query($currentSessionQuery);

if ($currentSessionResult && $currentSessionResult->num_rows > 0) {
  $currentSession = $currentSessionResult->fetch_assoc();
  $currentSessionId = $currentSession['id'];
  $currentSessionName = $currentSession['session_name'];
} else {
  $currentSessionId = null;
  $currentSessionName = null;
}

// Fetch the current term
$termQuery = "SELECT id, term_name 
              FROM school_terms 
              WHERE session_id = '$currentSessionId'
                AND start_date <= CURDATE() 
                AND end_date >= CURDATE() 
              ORDER BY start_date ASC 
              LIMIT 1";
$termResult = mysqli_query($con, $termQuery);
$termRow = mysqli_fetch_assoc($termResult);
$currentTermId = $termRow['id'];
$currentTermName = $termRow['term_name'];

// Fetch the last term (even from the previous session if needed)
$lastTermQuery = "SELECT t.id, t.term_name, s.session_name 
                  FROM school_terms t
                  JOIN school_sessions s ON t.session_id = s.id
                  WHERE t.id < '$currentTermId' 
                  ORDER BY t.id DESC 
                  LIMIT 1";
$lastTermResult = mysqli_query($con, $lastTermQuery);
$lastTermRow = mysqli_fetch_assoc($lastTermResult);

if ($lastTermRow) {
  $lastTermId = $lastTermRow['id'];
  $lastTermName = $lastTermRow['term_name'];
  $lastSessionName = $lastTermRow['session_name'];
} else {
  $lastTermId = null;
  $lastTermName = null;
  $lastSessionName = null;
}

$pay_forQuery = "SELECT SUM(amount) AS totalpaid, pay_for FROM payment
WHERE student_id = '$id'
AND class = '$cls'
AND school_type = '$st'
AND session = '$currentSessionName'
AND Term = '$currentTermName'
AND pay_for = 'School Fees (Scholarship Student)'
ORDER BY id DESC LIMIT 1";
$pay_forQueryResult = mysqli_query($con, $pay_forQuery);
$pay_forQueryRow = mysqli_fetch_assoc($pay_forQueryResult);
$pay_for = $pay_forQueryRow['pay_for'];
$paid_for = $pay_forQueryRow['totalpaid'];

// Fetch student's admission term and session
$admissionQuery = "SELECT admission_term, academic_session 
                   FROM students 
                   WHERE id = '$id'";
$admissionResult = mysqli_query($con, $admissionQuery);
$admissionRow = mysqli_fetch_assoc($admissionResult);
$admissionTerm = $admissionRow['admission_term'] ?? '';
$admissionSession = $admissionRow['academic_session'] ?? '';

// Determine if the student is New or Old
if ($admissionSession === $currentSessionName) {
  if ($admissionTerm === $currentTermName) {
    $std = 'New'; // Still in the first term after admission
  } elseif ($pay_for === 'School Fees (Scholarship Student)') {
    $std = 'New'; // New student but moved to next term
  } else {
    $std = 'Old'; // Old student
  }
} else {
  $std = 'Old'; // Not a newly admitted student this session
}

// Determine fee name based on student type
if ($std === 'New') {
  $feename = 'School Fees (Scholarship Student)'; // Set to New Student for fee records
} else {
  $feename = 'School Fees (Scholarship Student)'; // Set to Old Student for fee records
}

// Check if fee record for the current term/session is already stored
// Fetch current term fee amount
$stmt = $con->prepare("SELECT amount FROM fees 
                       WHERE class = ? AND stream = ? AND student_type = 'old' 
                      AND name = 'School Fees (Scholarship Student)' 
                       LIMIT 1");
$stmt->bind_param("ss", $cls, $st);
$stmt->execute();
$stmt->bind_result($currentTermTotalFees);
$stmt->fetch();
$stmt->close();

$currentTermTotalFees = $currentTermTotalFees ?? 0;

// Check if fee record already exists
$stmt = $con->prepare("SELECT id FROM fee_records 
                       WHERE class = ? AND stream = ? AND student_type = ? 
                       AND session = ? AND term = ? 
                      AND name = 'School Fees (Scholarship Student)' 
                       LIMIT 1");
$stmt->bind_param("sssss", $cls, $st, $std, $currentSessionName, $currentTermName);
$stmt->execute();
$stmt->store_result();

if ($stmt->num_rows == 0) {
  // Insert new fee record
  $stmt->close();
  $feee = "School Fees (Scholarship Student)";
  $stmt = $con->prepare("INSERT INTO fee_records (name, class, stream, student_type, session, term, amount) 
                           VALUES (?, ?, ?, ?, ?, ?, ?)");
  $stmt->bind_param("ssssssd", $feee, $cls, $st, $std, $currentSessionName, $currentTermName, $currentTermTotalFees);
  $stmt->execute();
} else {
  // Update existing fee record
  $stmt->bind_result($feeRecordId);
  $stmt->fetch();
  $stmt->close();
  $stmt = $con->prepare("UPDATE fee_records SET amount = ? WHERE id = ?");
  $stmt->bind_param("di", $currentTermTotalFees, $feeRecordId);
  $stmt->execute();
}
$stmt->close();
// Get last term's total fees from `fee_records` to ensure historical accuracy
$lastTermFeesQuery = "SELECT amount FROM fee_records
                      WHERE class = '$cls'
                      AND stream = '$st'
                      AND student_type = '$std'
                      AND session = '$lastSessionName'
                      AND term = '$lastTermName'
                      AND name = '$feename' 
                      ORDER BY id DESC LIMIT 1";
$lastTermFeesResult = mysqli_query($con, $lastTermFeesQuery);
$lastTermFeesRow = mysqli_fetch_assoc($lastTermFeesResult);
$lastTermTotalFees = $lastTermFeesRow['amount'] ?? 0;

// Get total payments for the last term
$lastTermPaidQuery = "SELECT SUM(amount) AS total_paid
                      FROM payment
                      WHERE student_id = '$id'
                      AND class = '$cls'
                      AND school_type = '$st'
                      AND session = '$lastSessionName'
                      AND Term = '$lastTermName'
                      AND pay_for = 'School Fees (Scholarship Student)'";
$lastTermPaidResult = mysqli_query($con, $lastTermPaidQuery);
$lastTermPaidRow = mysqli_fetch_assoc($lastTermPaidResult);
$lastTermTotalPaid = $lastTermPaidRow['total_paid'] ?? 0;

// Calculate outstanding balance from the last term
if ($lastTermTotalFees > 0) {
  $outstandingBalance = $lastTermTotalFees - $lastTermTotalPaid;
} else {
  $outstandingBalance = 0; // If no fees were set for last term, there's no outstanding balance
}

// Ensure outstanding balance is not negative
$outstandingBalance = max(0, $outstandingBalance);


// Get total fees for the current term
$totalFeesQuery = "SELECT SUM(amount) AS total_fees 
                   FROM fees 
                   WHERE class ='$cls' 
                   AND stream ='$st' 
                   AND student_type = '$std' 
                      AND name = 'School Fees (Scholarship Student)'";
$totalFeesResult = mysqli_query($con, $totalFeesQuery);
$totalFeesRow = mysqli_fetch_assoc($totalFeesResult);
$totalFees = $totalFeesRow['total_fees'] ?? 0;

// Query to get the fee ID for the current term
$query = "SELECT id
          FROM fees
          WHERE class = '$cls' 
          AND stream = '$st' 
          AND student_type = 'Old'
                      AND name = 'School Fees (Scholarship Student)' 
          LIMIT 1";
$result = mysqli_query($con, $query);

if ($result && mysqli_num_rows($result) > 0) {
  $row = mysqli_fetch_assoc($result);

  $feeId = $row['id'];          // Unique fee ID  
} else {
  $feeId = null; // Set to null if no result is found
}

// Get amount paid for the current session and term
// Fetch total amount already paid by the student in session
$amountPaidQuery = "SELECT SUM(amount) AS total_paid 
                    FROM payment 
                    WHERE student_id = '$id'
                      AND class = '$cls'
                      AND school_type = '$st'
                      AND session = '$currentSessionName'
                      AND pay_for ='School Fees (Scholarship Student)'";
$amountPaidResult = mysqli_query($con, $amountPaidQuery);
$amountPaidRow = mysqli_fetch_assoc($amountPaidResult);
$totalPaid = $amountPaidRow['total_paid'] ?? 0;


//total paid for the current term
$amountPaidQueryy = "SELECT SUM(amount) AS total_paid 
                    FROM payment 
                    WHERE student_id = '$id'
                      AND class = '$cls'
                      AND school_type = '$st'
                      AND session = '$currentSessionName'
                      AND term = '$currentTermName'
                      AND pay_for = 'School Fees (Scholarship Student)'";
$amountPaidResulty = mysqli_query($con, $amountPaidQueryy);
$amountPaidRowy = mysqli_fetch_assoc($amountPaidResulty);
$termtotalPaid = $amountPaidRowy['total_paid'] ?? 0;

if ($std === 'New') {
  // New student, first term has special fee, remaining terms normal fee
  $firstTimeFee = $paid_for; // first time fee (example: ₦150,000)

  // Fetch the normal fee for old students
  $oldStudentFeeQuery = "SELECT amount FROM fees 
                       WHERE class = '$cls' 
                       AND stream = '$st' 
                       AND student_type = 'Old' 
                       AND name = 'School Fees (Scholarship Student)'
                       LIMIT 1";
  $oldStudentFeeResult = mysqli_query($con, $oldStudentFeeQuery);
  $oldStudentFeeRow = mysqli_fetch_assoc($oldStudentFeeResult);
  $oldStudentFee = $oldStudentFeeRow['amount'] ?? 0;

  // Calculate based on how many terms remaining
  switch ($admissionTerm) {
    case 'First Term':
      $remainingTerms = 2; // Second and Third term left
      break;
    case 'Second Term':
      $remainingTerms = 1; // Only Third term left
      break;
    case 'Third Term':
      $remainingTerms = 0; // No more terms this session
      break;
    default:
      $remainingTerms = 2;
      break;
  }

  $totalSessionFee = $firstTimeFee + ($oldStudentFee * $remainingTerms);
} else {
  // All other students
    // --- DYNAMIC SESSION FEE CALCULATION ---

    // 1. Initialize all terms to the CURRENT term fee.
    // This acts as a fallback: if we are in 1st term, it assumes T2 and T3 are the same.
    // If we are in 2nd term, it assumes T3 is the same as T2.
    $t1_amount = $currentTermTotalFees;
    $t2_amount = $currentTermTotalFees;
    $t3_amount = $currentTermTotalFees;

    // 2. Fetch historical fee records for this session
    // This checks if we have stored a specific different price for previous terms
    $historyStmt = $con->prepare("SELECT term, amount FROM fee_records 
                                  WHERE session = ? 
                                  AND class = ? 
                                  AND stream = ? 
                                  AND student_type = ? 
                                  AND name = ?");
    
    $historyStmt->bind_param("sssss", $currentSessionName, $cls, $st, $std, $feename);
    $historyStmt->execute();
    $historyResult = $historyStmt->get_result();

    // 3. Update the amounts based on what is found in the database
    while ($row = $historyResult->fetch_assoc()) {
        if ($row['term'] === 'First Term') {
            $t1_amount = $row['amount']; // Overwrite with actual T1 cost (e.g., 95k)
        }
        elseif ($row['term'] === 'Second Term') {
            $t2_amount = $row['amount']; // Overwrite with actual T2 cost
        }
        elseif ($row['term'] === 'Third Term') {
            $t3_amount = $row['amount']; // Overwrite with actual T3 cost
        }
    }
    $historyStmt->close();

    // 4. Handle "Current Term" Priority
    // If the database has an old value for the current term, we force the *current* fee
    // to ensure the calculation uses the latest price set by the school admin for right now.
    if ($currentTermName === 'First Term') {
        $t1_amount = $currentTermTotalFees;
        $t2_amount = $currentTermTotalFees; // Projection
        $t3_amount = $currentTermTotalFees; // Projection
    } 
    elseif ($currentTermName === 'Second Term') {
        $t2_amount = $currentTermTotalFees; // Force Current Price
        $t3_amount = $currentTermTotalFees; // Projection for T3
    } 
    elseif ($currentTermName === 'Third Term') {
        $t3_amount = $currentTermTotalFees; // Force Current Price
    }

    // 5. Final Summation
    $totalSessionFee = $t1_amount + $t2_amount + $t3_amount;
}
if ($std === 'New') {
  // calculate final balance
  $totalFeesDue = $totalFees + $outstandingBalance;
} else {
  // Calculate final balance
  $totalFeesDue = $currentTermTotalFees + $outstandingBalance;
}
// Now calculate total balance
$totalBalance = max(0, $totalSessionFee - $totalPaid);
// Output variables (optional: you can echo or use them later)
?>



<!DOCTYPE html>
<html>
<?php @include("includes/head.php"); ?>
<style>
  /* Cards Styling */
  .small-box {
    border-radius: 12px;
    transition: 0.3s ease-in-out;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    background: white;
  }

  .small-box:hover {
    transform: translateY(-4px);
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.15);
  }

  .small-box .inner {
    padding: 20px;
  }

  .small-box p {
    font-size: 1rem;
    font-weight: bold;
    color: whitesmoke;
  }

  .small-box span {
    font-size: 1rem;
    color: #666;
    font-weight: bold;
  }

  .small-box .icon {
    position: absolute;
    right: 20px;
    top: 20px;
    font-size: 3rem;
    color: rgba(255, 255, 255, 0.8);
  }

  .small-box-footer {
    display: block;
    padding: 12px;
    font-weight: 600;
    font-size: 1rem;
    text-align: center;
    background: rgba(0, 0, 0, 0.1);
    border-top: 1px solid rgba(255, 255, 255, 0.2);
  }

  .small-box-footer:hover {
    background: rgba(0, 0, 0, 0.15);
  }

  /* Alert Box Styling */
  .alert-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1050;
  }

  .dashboard-header {
    font-size: 1.3rem;
    font-weight: 400;
    color: #333;
    text-align: center;
    margin-bottom: 10px;
  }

  .alert-box {
    background: white;
    padding: 25px;
    border-radius: 10px;
    text-align: center;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
    max-width: 400px;
    width: 90%;
    animation: fadeIn 0.3s ease-in-out;
  }

  .alert-box p {
    font-size: 1.2rem;
    color: #444;
    margin-bottom: 15px;
  }

  .alert-box button {
    margin-top: 15px;
    padding: 10px 18px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 1rem;
    transition: 0.3s;
  }

  .btn-update {
    background-color: #007bff;
    color: white;
  }

  .btn-update:hover {
    background-color: #0056b3;
  }

  .btn-close {
    background-color: #dc3545;
    color: white;
  }

  .btn-close:hover {
    background-color: #bd2130;
  }

  @keyframes fadeIn {
    from {
      opacity: 0;
      transform: scale(0.9);
    }

    to {
      opacity: 1;
      transform: scale(1);
    }
  }
</style>

<body class="hold-transition sidebar-mini layout-fixed">
  <div class="wrapper">
    <!-- Navbar -->
    <?php @include("includes/headerstd.php"); ?>
    <!-- /.navbar -->

    <!-- Main Sidebar Container -->
    <?php @include("includes/sidebaroldstdboard.php"); ?>

    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
      <!-- Content Header (Page header) -->
      <section class="content-header">
        <div class="container-fluid">
          <div class="row mb-2">
            <div class="col-sm-8">
              <h3 class="text-primary font-weight-bold">
                <i class="fas fa-wallet"></i> Payment Management →
                <span class="font-italic text-secondary" style="font-size: 0.5em;"><?php echo $currentTermName; ?> | <?php echo $currentSessionName; ?></span>
              </h3>
            </div>
            <div class="col-sm-4">
              <ol class="breadcrumb float-sm-right">
                <li class="breadcrumb-item"><a href="#">Home</a></li>
                <li class="breadcrumb-item active">Pay School Fees</li>
              </ol>
            </div>
          </div>
        </div><!-- /.container-fluid -->
      </section>

      <?php if ($cls === 'JSS 3' || $cls === "SS 3"): ?>
        <!-- Main content -->
        <section class="content">
          <div class="container-fluid">
            <div class="row">
              <div class="col-md-12">
                <!-- general form elements -->
                <div class="card card-primary">
                  <div class="card-header">
                    <h5 class="card-title font-weight-bold">
                      <i class="fas fa-wallet"></i> Pay School Fees
                    </h5>
                  </div>
                  <!-- /.card-header -->
                  <!-- form start -->
                  <form role="form" method="" action="confirmpayb.php?tab_id=<?php echo $tabSessionID; ?>">
                    <div class="card-body">

                      <span style="color: brown">
                        <h5><b>School Fees Payment Details</b></h5>
                      </span>
                      <hr>

                      <div class="row">
                        <div class="col-md-12">
                          <div class="alert alert-info">
                            <center>
                              <div class="row">
                                <div class="col-md-6 mb-3">
                                  <h6><b><?php echo $currentSessionName; ?> Session School Fees: ₦<?php echo number_format($totalSessionFee, 2); ?></b></h6>
                                </div>
                                <div class="col-md-6 mb-3 ">
                                  <h6><b>Previous Session Oustanding: ₦<?php echo number_format($outstandingBalance, 2); ?></b></h6>
                                </div>
                                <div class="col-md-6 mb-3">
                                  <h6><b>Amount Paid (Session): ₦<?php echo number_format($totalPaid, 2); ?></b></h6>
                                </div>
                                <div class="col-md-6 mb-3">
                                  <h6><b>To Balance (Session): ₦<span id="balance_display"><?php echo number_format($totalBalance, 2); ?></span></b></h6>
                                </div>
                              </div>
                            </center>
                          </div>
                        </div>




                        <div class="col-md-6 ">
                          <label for="paymen">Payment Option:</label>
                          <select id="payment_option" onchange="calculateAmount()" class="form-control" required>
                            <option value="">-- Select Payment Option --</option>
                            <option value="full_session">Full Session School Fees</option>
                            <option value="full_2">Full Session Fees 2 Installments</option>
                            <option value="full_3">Full Session Fees 3 Installments</option>
                            <option value="full_4">Full Session Fees 4 Installments</option>
                            <option value="custom">Part Payment</option> <!-- NEW -->
                          </select>

                          <!-- Hidden field to store total fees for JavaScript -->
                          <input type="hidden" id="term_fee" value="<?php echo $totalSessionFee; ?>">
                          <input type="hidden" id="std" value="<?php echo $std; ?>">

                        </div>
                        <div id="customAmountDiv" class="col-md-6" style="display: none;">
                          <label for="custom_amount">Part Payment Amount:</label>
                          <input type="number" id="custom_amount" class="form-control" min="0" step="0.01" oninput="updateCustomAmount()">
                          <small id="custom_amount_warning" style="color: red; display: none;">
                            Amount must be at least a quarter of this session's fees and can't be greater than ₦<?php echo number_format($totalBalance); ?>.
                          </small>

                          <!-- New: Live formatted display -->
                          <div id="formatted_amount_display" style="margin-top: 5px; font-weight: bold; color: green; display: none;"></div>
                        </div>



                        <div class="col-md-6">
                          <label for="pay_amount">Amount to Pay (₦):</label>
                          <input type="text" id="pay_amount" name="pay_amount" class="form-control" readonly>
                        </div>

                        <!-- Hidden Input to Store Fee ID -->
                        <input type="hidden" name="fee_id" id="fee_id" value="<?php echo $feeId; ?>">
                        <input type="hidden" name="termtotalpaid" id="termtotalpaid" value="<?php echo $totalPaid; ?>">


                        <div class="col-md-12 text-center mt-3">
                          <a id="payButton" href="#" class="btn btn-primary">Pay <i class="fa fa-credit-card"></i></a>

                        </div>
                      </div>
                    </div>
                  </form>
                  <script>
                    // Assume PHP has passed these values correctly
                    var admissionTerm = <?php echo json_encode($admissionTerm); ?>; // "First Term", "Second Term", "Third Term"
                    var admissionSession = <?php echo json_encode($admissionSession); ?>; // Example: "2024/2025"
                    var currentSession = <?php echo json_encode($currentSessionName); ?>; // Example: "2024/2025"
                    var totalBalance = <?php echo json_encode($totalBalance); ?>; // Remaining balance




                    // Immediately after page load, adjust payment options
                    window.onload = function() {
                      adjustPaymentOptions();
                    };

                    function adjustPaymentOptions() {
                      var paymentSelect = document.getElementById('payment_option');
                      var std = document.getElementById('std');
                      var fullSessionOption = paymentSelect.querySelector("option[value='full_session']");
                      var twoTermsOption = paymentSelect.querySelector("option[value='full_2']");
                      var fullOption = paymentSelect.querySelector("option[value='full_3']");
                      var halfOption = paymentSelect.querySelector("option[value='full_4']");
                      var customOption = paymentSelect.querySelector("option[value='custom']");

                      var termFee = parseFloat(document.getElementById('term_fee').value) || 0;
                      var balance = parseFloat(<?php echo json_encode($totalBalance); ?>) || 0;

                      // Disable all by default
                      [fullSessionOption, twoTermsOption, fullOption, halfOption, customOption].forEach(opt => {
                        if (opt) opt.disabled = true;
                      });

                      // If balance is zero, fully paid
                      if (balance <= 0) {
                        return; // All options remain disabled
                      }

                      // Enable options based on remaining balance
                      if (balance >= termFee) {
                        if (fullSessionOption) fullSessionOption.disabled = false;
                        if (twoTermsOption) twoTermsOption.disabled = false;
                        if (fullOption) fullOption.disabled = false;
                        if (halfOption) halfOption.disabled = false;
                        if (customOption) customOption.disabled = false;
                      } else if (balance >= termFee / 2) {
                        if (twoTermsOption) twoTermsOption.disabled = false;
                        if (fullOption) fullOption.disabled = false;
                        if (halfOption) halfOption.disabled = false;
                        if (customOption) customOption.disabled = false;
                      } else if (balance >= termFee / 3) {
                        if (fullOption) fullOption.disabled = false;
                        if (halfOption) halfOption.disabled = false;
                        if (customOption) customOption.disabled = false;
                      } else if (balance >= termFee / 4) {
                        if (halfOption) halfOption.disabled = false;
                        if (customOption) customOption.disabled = false;
                      } else {
                        // Balance too low for any preset option, allow only custom
                        if (customOption) customOption.disabled = false;
                      }

                      // Optional: Handle student type for full_session option (from your original logic)
                      if (std && std.value === "New" && fullSessionOption) {
                        fullSessionOption.disabled = true;
                      }

                      // Optional: Handle admissionSession/Term logic (from your original logic)
                      if (admissionSession === currentSession) {
                        if (admissionTerm === "Second Term" && fullSessionOption) fullSessionOption.disabled = true;
                        if (admissionTerm === "Third Term") {
                          if (fullSessionOption) fullSessionOption.disabled = true;
                          if (twoTermsOption) twoTermsOption.disabled = true;
                        }
                      }
                    }

                    function calculateAmount() {
                      var termFee = parseFloat(document.getElementById('term_fee').value) || 0;
                      var half_payment = termFee / 2;
                      var paymentOption = document.getElementById('payment_option').value;
                      var amountField = document.getElementById('pay_amount');
                      var customAmountDiv = document.getElementById('customAmountDiv');
                      var payButton = document.getElementById('payButton');
                      var warningText = document.getElementById('custom_amount_warning');
                      var termtotalPaid = parseFloat(document.getElementById('termtotalpaid').value) || 0;
                      var session_fee = <?php echo json_encode($totalBalance); ?>;
                      var amount = 0;

                      if (paymentOption === 'custom') {
                        customAmountDiv.style.display = 'block';
                        var customAmountInput = document.getElementById('custom_amount').value;

                        if (customAmountInput !== '') {
                          var customAmount = parseFloat(customAmountInput) || 0;

                          // Check if session balance is less than half_payment
                          if (session_fee < half_payment) {
                            // Allow any custom amount up to session balance
                            if (customAmount > session_fee) {
                              warningText.style.display = 'block';
                              amountField.value = '';
                              payButton.href = "#";
                              payButton.classList.add('disabled');
                            } else {
                              warningText.style.display = 'none';
                              amount = customAmount;
                              amountField.value = amount.toFixed(2);
                              payButton.href = "confirmpayb.php?fee_id=<?php echo $feeId; ?>&tab_id=<?php echo $tabSessionID; ?>&pay_amount=" + amount.toFixed(2);
                              payButton.classList.remove('disabled');
                            }
                          } else {
                            // Session balance is at least half_payment, apply original checks
                            if (customAmount < half_payment && termtotalPaid < half_payment) {
                              warningText.style.display = 'block';
                              amountField.value = '';
                              payButton.href = "#";
                              payButton.classList.add('disabled');
                            } else if (customAmount > session_fee) {
                              warningText.style.display = 'block';
                              amountField.value = '';
                              payButton.href = "#";
                              payButton.classList.add('disabled');
                            } else {
                              warningText.style.display = 'none';
                              amount = customAmount;
                              amountField.value = amount.toFixed(2);
                              payButton.href = "confirmpayb.php?fee_id=<?php echo $feeId; ?>&tab_id=<?php echo $tabSessionID; ?>&pay_amount=" + amount.toFixed(2);
                              payButton.classList.remove('disabled');
                            }
                          }
                        } else {
                          warningText.style.display = 'none';
                          amountField.value = '';
                          payButton.href = "#";
                          payButton.classList.add('disabled');
                        }

                      } else {
                        customAmountDiv.style.display = 'none';
                        warningText.style.display = 'none';

                        switch (paymentOption) {
                          case 'full_2':
                            amount = termFee / 2;
                            break;
                          case 'full_3':
                            amount = Math.ceil(termFee / 3);
                            break;
                          case 'full_4':
                            amount = termFee / 4;
                            break;
                          case 'full_session':
                            amount = termFee;
                            break;
                          default:
                            amount = 0;
                        }

                        if (amount > 0) {
                          amountField.value = amount.toFixed(2);
                          payButton.href = "confirmpayb.php?fee_id=<?php echo $feeId; ?>&tab_id=<?php echo $tabSessionID; ?>&pay_amount=" + amount.toFixed(2);
                          payButton.classList.remove('disabled');
                        } else {
                          amountField.value = '';
                          payButton.href = "#";
                          payButton.classList.add('disabled');
                        }
                      }
                    }


                    // This handles typing inside the custom amount input box
                    function updateCustomAmount() {
                      calculateAmount();
                      const input = document.getElementById('custom_amount');
                      const display = document.getElementById('formatted_amount_display');

                      const raw = input.value;

                      if (raw === '' || isNaN(raw)) {
                        display.style.display = 'none';
                        return;
                      }

                      const formatted = parseFloat(raw).toLocaleString('en-NG', {
                        style: 'currency',
                        currency: 'NGN'
                      });
                      display.textContent = `You entered: ${formatted}`;
                      display.style.display = 'block';

                    }
                  </script>

                </div>
              </div>
            </div>
        </section>
      <?php else: ?>

        <!-- Main content -->
        <section class="content">
          <div class="container-fluid">
            <div class="row">
              <div class="col-md-12">
                <!-- general form elements -->
                <div class="card card-primary">
                  <div class="card-header">
                    <h5 class="card-title font-weight-bold">
                      <i class="fas fa-wallet"></i> Pay School Fees
                    </h5>
                  </div>
                  <!-- /.card-header -->
                  <!-- form start -->
                  <form role="form" method="" action="confirmpayb.php?tab_id=<?php echo $tabSessionID; ?>">
                    <div class="card-body">

                      <span style="color: brown">
                        <h5><b>School Fees Payment Details</b></h5>
                      </span>
                      <hr>

                      <div class="row">
                        <div class="col-md-12">
                          <div class="alert alert-info">
                            <center>
                              <div class="row">
                                <div class="col-md-4 mb-3">
                                  <h6><b><?php echo $currentSessionName; ?> Session School Fees: ₦<?php echo number_format($totalSessionFee, 2); ?></b></h6>
                                </div>
                                <div class="col-md-4 mb-3">
                                  <h6><b><?php echo $currentTermName; ?> School Fees: ₦<?php echo number_format($totalFees, 2); ?></b></h6>
                                </div>
                                <div class="col-md-4 mb-3 ">
                                  <h6><b>Last Term Oustanding: ₦<?php echo number_format($outstandingBalance, 2); ?></b></h6>
                                </div>
                                <div class="col-md-4 mb-3">
                                  <h6><b>School Fees Due (<?= $currentTermName ?>): ₦<?php echo number_format($totalFeesDue, 2); ?></b></h6>
                                </div>
                                <div class="col-md-4 mb-3">
                                  <h6><b>Amount Paid (Session): ₦<?php echo number_format($totalPaid, 2); ?></b></h6>
                                </div>
                                <div class="col-md-4 mb-3">
                                  <h6><b>To Balance (Session): ₦<span id="balance_display"><?php echo number_format($totalBalance, 2); ?></span></b></h6>
                                </div>
                              </div>
                            </center>
                          </div>
                        </div>




                        <div class="col-md-6 ">
                          <label for="paymen">Payment Option:</label>
                          <select id="payment_option" onchange="calculateAmount()" class="form-control" required>
                            <option value="">-- Select Payment Option --</option>
                            <option value="half">Half Term Payment</option>
                            <option value="full">Full Term Payment</option>
                            <option value="two_terms">Full Two Term Payment</option>
                            <option value="full_session">Full Session Payment</option>
                            <option value="custom">Part Payment</option> <!-- NEW -->
                          </select>

                          <!-- Hidden field to store total fees for JavaScript -->
                          <input type="hidden" id="term_fee" value="<?php echo $currentTermTotalFees; ?>">
                          <input type="hidden" id="std" value="<?php echo $std; ?>">

                        </div>
                        <div id="customAmountDiv" class="col-md-6" style="display: none;">
                          <label for="custom_amount">Part Payment Amount:</label>
                          <input type="number" id="custom_amount" class="form-control" min="0" step="0.01" oninput="updateCustomAmount()">
                          <small id="custom_amount_warning" style="color: red; display: none;">
                            Amount must be at least a half of this term's fees and can't be greater than ₦<?php echo number_format($totalBalance); ?>.
                          </small>

                          <!-- New: Live formatted display -->
                          <div id="formatted_amount_display" style="margin-top: 5px; font-weight: bold; color: green; display: none;"></div>
                        </div>



                        <div class="col-md-6">
                          <label for="pay_amount">Amount to Pay (₦):</label>
                          <input type="text" id="pay_amount" name="pay_amount" class="form-control" readonly>
                        </div>

                        <!-- Hidden Input to Store Fee ID -->
                        <input type="hidden" name="fee_id" id="fee_id" value="<?php echo $feeId; ?>">
                        <input type="hidden" name="termtotalpaid" id="termtotalpaid" value="<?php echo $termtotalPaid; ?>">


                        <div class="col-md-12 text-center mt-3">
                          <a id="payButton" href="#" class="btn btn-primary">Pay <i class="fa fa-credit-card"></i></a>

                        </div>
                      </div>
                    </div>
                  </form>
                  <script>
                    // Assume PHP has passed these values correctly
                    var admissionTerm = <?php echo json_encode($admissionTerm); ?>; // "First Term", "Second Term", "Third Term"
                    var admissionSession = <?php echo json_encode($admissionSession); ?>; // Example: "2024/2025"
                    var currentSession = <?php echo json_encode($currentSessionName); ?>; // Example: "2024/2025"
                    var totalBalance = <?php echo json_encode($totalBalance); ?>; // Remaining balance



                    // Immediately after page load, adjust payment options
                    window.onload = function() {
                      adjustPaymentOptions();
                    };

                    function adjustPaymentOptions() {
                      var paymentSelect = document.getElementById('payment_option');
                      var std = document.getElementById('std');
                      var fullSessionOption = paymentSelect.querySelector("option[value='full_session']");
                      var twoTermsOption = paymentSelect.querySelector("option[value='two_terms']");
                      var fullOption = paymentSelect.querySelector("option[value='full']");
                      var halfOption = paymentSelect.querySelector("option[value='half']");
                      var customOption = paymentSelect.querySelector("option[value='custom']");

                      var termFee = parseFloat(document.getElementById('term_fee').value) || 0;
                      var balance = parseFloat(<?php echo json_encode($totalBalance); ?>) || 0;

                      // Disable all by default
                      [fullSessionOption, twoTermsOption, fullOption, halfOption, customOption].forEach(opt => {
                        if (opt) opt.disabled = true;
                      });

                      // If balance is zero, fully paid
                      if (balance <= 0) {
                        return; // All options remain disabled
                      }

                      // Enable options based on remaining balance
                      if (balance >= termFee * 3) {
                        if (fullSessionOption) fullSessionOption.disabled = false;
                        if (twoTermsOption) twoTermsOption.disabled = false;
                        if (fullOption) fullOption.disabled = false;
                        if (halfOption) halfOption.disabled = false;
                        if (customOption) customOption.disabled = false;
                      } else if (balance >= termFee * 2) {
                        if (twoTermsOption) twoTermsOption.disabled = false;
                        if (fullOption) fullOption.disabled = false;
                        if (halfOption) halfOption.disabled = false;
                        if (customOption) customOption.disabled = false;
                      } else if (balance >= termFee) {
                        if (fullOption) fullOption.disabled = false;
                        if (halfOption) halfOption.disabled = false;
                        if (customOption) customOption.disabled = false;
                      } else if (balance >= termFee / 2) {
                        if (halfOption) halfOption.disabled = false;
                        if (customOption) customOption.disabled = false;
                      } else {
                        // Balance too low for any preset option, allow only custom
                        if (customOption) customOption.disabled = false;
                      }

                      // Optional: Handle student type for full_session option (from your original logic)
                      if (std && std.value === "New" && fullSessionOption) {
                        fullSessionOption.disabled = true;
                      }

                      // Optional: Handle admissionSession/Term logic (from your original logic)
                      if (admissionSession === currentSession) {
                        if (admissionTerm === "Second Term" && fullSessionOption) fullSessionOption.disabled = true;
                        if (admissionTerm === "Third Term") {
                          if (fullSessionOption) fullSessionOption.disabled = true;
                          if (twoTermsOption) twoTermsOption.disabled = true;
                        }
                      }
                    }

                    function calculateAmount() {
                      var termFee = parseFloat(document.getElementById('term_fee').value) || 0;
                      var half_payment = termFee / 2;
                      var paymentOption = document.getElementById('payment_option').value;
                      var amountField = document.getElementById('pay_amount');
                      var customAmountDiv = document.getElementById('customAmountDiv');
                      var payButton = document.getElementById('payButton');
                      var warningText = document.getElementById('custom_amount_warning');
                      var termtotalPaid = parseFloat(document.getElementById('termtotalpaid').value) || 0;
                      var session_fee = <?php echo json_encode($totalBalance); ?>;
                      var amount = 0;

                      if (paymentOption === 'custom') {
                        customAmountDiv.style.display = 'block';
                        var customAmountInput = document.getElementById('custom_amount').value;

                        if (customAmountInput !== '') {
                          var customAmount = parseFloat(customAmountInput) || 0;

                          // Check if session balance is less than half_payment
                          if (session_fee < half_payment) {
                            // Allow any custom amount up to session balance
                            if (customAmount > session_fee) {
                              warningText.style.display = 'block';
                              amountField.value = '';
                              payButton.href = "#";
                              payButton.classList.add('disabled');
                            } else {
                              warningText.style.display = 'none';
                              amount = customAmount;
                              amountField.value = amount.toFixed(2);
                              payButton.href = "confirmpayb.php?fee_id=<?php echo $feeId; ?>&tab_id=<?php echo $tabSessionID; ?>&pay_amount=" + amount.toFixed(2);
                              payButton.classList.remove('disabled');
                            }
                          } else {
                            // Session balance is at least half_payment, apply original checks
                            if (customAmount < half_payment && termtotalPaid < half_payment) {
                              warningText.style.display = 'block';
                              amountField.value = '';
                              payButton.href = "#";
                              payButton.classList.add('disabled');
                            } else if (customAmount > session_fee) {
                              warningText.style.display = 'block';
                              amountField.value = '';
                              payButton.href = "#";
                              payButton.classList.add('disabled');
                            } else {
                              warningText.style.display = 'none';
                              amount = customAmount;
                              amountField.value = amount.toFixed(2);
                              payButton.href = "confirmpayb.php?fee_id=<?php echo $feeId; ?>&tab_id=<?php echo $tabSessionID; ?>&pay_amount=" + amount.toFixed(2);
                              payButton.classList.remove('disabled');
                            }
                          }
                        } else {
                          warningText.style.display = 'none';
                          amountField.value = '';
                          payButton.href = "#";
                          payButton.classList.add('disabled');
                        }

                      } else {
                        customAmountDiv.style.display = 'none';
                        warningText.style.display = 'none';

                        switch (paymentOption) {
                          case 'half':
                            amount = termFee / 2;
                            break;
                          case 'full':
                            amount = termFee;
                            break;
                          case 'two_terms':
                            amount = termFee * 2;
                            break;
                          case 'full_session':
                            amount = termFee * 3;
                            break;
                          default:
                            amount = 0;
                        }

                        if (amount > 0) {
                          amountField.value = amount.toFixed(2);
                          payButton.href = "confirmpayb.php?fee_id=<?php echo $feeId; ?>&tab_id=<?php echo $tabSessionID; ?>&pay_amount=" + amount.toFixed(2);
                          payButton.classList.remove('disabled');
                        } else {
                          amountField.value = '';
                          payButton.href = "#";
                          payButton.classList.add('disabled');
                        }
                      }
                    }



                    // This handles typing inside the custom amount input box
                    function updateCustomAmount() {
                      calculateAmount();
                      const input = document.getElementById('custom_amount');
                      const display = document.getElementById('formatted_amount_display');

                      const raw = input.value;

                      if (raw === '' || isNaN(raw)) {
                        display.style.display = 'none';
                        return;
                      }

                      const formatted = parseFloat(raw).toLocaleString('en-NG', {
                        style: 'currency',
                        currency: 'NGN'
                      });
                      display.textContent = `You entered: ${formatted}`;
                      display.style.display = 'block';

                    }
                  </script>

                </div>
              </div>
            </div>
        </section>
      <?php endif; ?>

      <section class="content">
        <div class="container-fluid">
          <div class="row">
            <div class="col-md-12">
              <?php
              $query1 = "SELECT * FROM fees 
                WHERE class = '$cls' 
                AND stream = '$st' 
                AND student_type = '$std' 
                AND name = 'Lesson Fees'";

              $result1 = mysqli_query($con, $query1);
              ?>
              <div class="card card-primary">
                <div class="card-header">
                  <h5 class="card-title font-weight-bold">
                    <i class="fas fa-wallet"></i> Pay Lesson Fees
                  </h5>
                </div>
                <form role="form" method="" enctype="multipart/form-data">
                  <div class="card-body">
                    <span style="color: brown">
                      <h5><b>Lesson Fees Payment Details</b></h5>
                    </span>
                    <hr>
                    <div class="row">
                      <?php
                      if (mysqli_num_rows($result1) > 0) {
                        while ($row = mysqli_fetch_assoc($result1)) {
                          $feeType = $row['name'];
                          $amount = $row['amount'];
                          $class = $row['class'];
                          $feeId = $row['id'];
                          $stdtype = $row['student_type'];

                          if (strpos($feeType, 'Lesson Fees') !== false) {
                            $bgColor = 'dark';
                          } elseif (strpos($feeType, 'Boarding Fees') !== false) {
                            $bgColor = 'info';
                          } elseif (strpos($feeType, 'FULL 2 TERM') !== false) {
                            $bgColor = 'danger';
                          } elseif (strpos($feeType, 'FULL SESSION') !== false) {
                            $bgColor = 'primary';
                          } else {
                            $bgColor = 'success';
                          }
                      ?>
                          <div class="col-lg-4 col-md-6">
                            <div class="small-box bg-<?php echo $bgColor; ?> text-white">
                              <div class="inner">
                                <p><?php echo $class; ?></p>
                                <p><?php echo $feeType; ?></p>
                                <span>₦<?php echo number_format($amount, 2); ?></span>
                              </div>
                              <div class="icon">
                                <i class="fas fa-money-bill-wave"></i>
                              </div>
                              <a href="confirmpayb.php?fee_id=<?php echo $feeId; ?>&pay_amount=<?php echo $amount;
                                                                                              } ?>" class="small-box-footer text-white">Pay <i class="fa fa-credit-card"></i></a>
                            </div>
                          </div>
                        <?php } else {
                        echo "<p style='color:red; margin: 15px;'>No fees available at the moment. Please check back later.</p>";
                      } ?>
                    </div>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
      </section>

      <section class="content">
        <div class="container-fluid">
          <div class="row">
            <div class="col-md-12">
              <?php
              $query2 = "SELECT * FROM fees 
                WHERE class = '$cls' 
                AND stream = '$st' 
                AND student_type = '$std' 
                AND name LIKE '%Boarding Fees%'";

              $result2 = mysqli_query($con, $query2);
              ?>
              <div class="card card-primary">
                <div class="card-header">
                  <h5 class="card-title font-weight-bold">
                    <i class="fas fa-wallet"></i> Pay Boarding Fees
                  </h5>
                </div>
                <form role="form" method="" enctype="multipart/form-data">
                  <div class="card-body">
                    <span style="color: brown">
                      <h5><b>Boarding Fees Payment Details</b></h5>
                    </span>
                    <hr>
                    <div class="row">
                      <?php
                      if (mysqli_num_rows($result2) > 0) {
                        while ($row = mysqli_fetch_assoc($result2)) {
                          $feeType = $row['name'];
                          $amount = $row['amount'];
                          $class = $row['class'];
                          $feeId = $row['id'];
                          $stdtype = $row['student_type'];

                          if (strpos($feeType, 'Lesson Fees') !== false) {
                            $bgColor = 'dark';
                          } elseif (strpos($feeType, 'Boarding Fees') !== false) {
                            $bgColor = 'info';
                          } elseif (strpos($feeType, 'FULL 2 TERM') !== false) {
                            $bgColor = 'danger';
                          } elseif (strpos($feeType, 'FULL SESSION') !== false) {
                            $bgColor = 'primary';
                          } else {
                            $bgColor = 'success';
                          }
                      ?>
                          <div class="col-lg-4 col-md-6">
                            <div class="small-box bg-<?php echo $bgColor; ?> text-white">
                              <div class="inner">
                                <p><?php echo $class; ?></p>
                                <p><?php echo $feeType; ?></p>
                                <span>₦<?php echo number_format($amount, 2); ?></span>
                              </div>
                              <div class="icon">
                                <i class="fas fa-money-bill-wave"></i>
                              </div>
                              <a href="confirmpayb.php?fee_id=<?php echo $feeId; ?>&pay_amount=<?php echo $amount; ?>" class="small-box-footer text-white">
                                Pay <i class="fa fa-credit-card"></i>
                              </a>
                            </div>
                          </div>
                      <?php
                        }
                      } else {
                        echo "<p style='color:red; margin: 15px;'>No fees available at the moment. Please check back later.</p>";
                      }
                      ?>

                    </div>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
      </section>
    </div>

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

  </div>

  <!-- ./wrapper -->
  <?php @include("includes/foot.php"); ?>
  <script>
    // In your Javascript (external .js resource or <script> tag)
    $(document).ready(function() {
      $('#payment_option').select2();

    });
  </script>

</body>

</html>