<?php

// Includes

include('includes/session.php');

error_reporting(0);

include('includes/dbconnection.php');

require_once __DIR__ . '/includes/session_term_helper.php';



// ==========================================

// HELPER FUNCTIONS

// ==========================================



/**

 * Checks if a fee record exists. Updates it if it does, inserts it if it doesn't.

 */

$feeRecordId = null;

function saveFeeRecord($con, $name, $class, $stream, $student_type, $session, $term, $amount)
{

  $feeRecordId = null;

  $check_query = "SELECT id FROM fee_records 

                    WHERE class = ? AND stream = ? AND student_type = ? 

                      AND session = ? AND term = ? AND name = ? LIMIT 1";

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

  if ($stmt) {

    $stmt->bind_param("ssssss", $class, $stream, $student_type, $session, $term, $name);

    $stmt->execute();

    $stmt->store_result();



    if ($stmt->num_rows === 0) {

      $stmt->close();

      $insert_query = "INSERT INTO fee_records (name, class, stream, student_type, session, term, amount) 

                             VALUES (?, ?, ?, ?, ?, ?, ?)";

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

      $stmt->bind_param("ssssssd", $name, $class, $stream, $student_type, $session, $term, $amount);

      $stmt->execute();

    } else {

      $stmt->bind_result($feeRecordId);

      $stmt->fetch();

      $stmt->close();

      $update_query = "UPDATE fee_records SET amount = ? WHERE id = ?";

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

      $stmt->bind_param("di", $amount, $feeRecordId);

      $stmt->execute();

    }

    if ($stmt) {

      $stmt->close();

    }

  }

}



// ==========================================

// 1. INITIAL DATA & GLOBAL RANKING MAP

// ==========================================



$id = $_SESSION['student_id'];

$cls = trim($_SESSION['class']);

$st = trim($_SESSION['stream']);



$termRanksMap = [

  'First Term' => 1,

  'Second Term' => 2,

  'Third Term' => 3

];



$demote = 0;

$admissionTerm = '';

$admissionSession = '';



$sql = "SELECT demote_status, admission_term, academic_session FROM students WHERE id = ?";

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

if ($stmt) {

  $stmt->bind_param("i", $id);

  $stmt->execute();

  $result = $stmt->get_result();

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

    $demote = $row['demote_status'] ?? 0;

    $admissionTerm = $row['admission_term'] ?? '';

    $admissionSession = $row['academic_session'] ?? '';

  }

  $stmt->close();

}



// Numeric Admission Ranks

$admissionSessionRank = (int) substr($admissionSession, 0, 4);

$admissionTermRank = $termRanksMap[$admissionTerm] ?? 0;



// ==========================================

// 2 & 3. FETCH CURRENT SESSION AND TERM

// ==========================================



$currentSessionId = $currentSessionRank = 0;

$currentSessionName = $currentTermName = null;

$currentTermId = $currentTermRank = 0;



$stResult = resolveCurrentSessionTerm($con);

$currentSessionId = $stResult['session_id'];

$currentSessionName = $stResult['session_name'];

$currentTermId = $stResult['term_id'];

$currentTermName = $stResult['term_name'];

$currentSessionRank = (int) substr($currentSessionName ?? '', 0, 4);

$currentTermRank = $termRanksMap[$currentTermName] ?? 0;



// ==========================================

// 4. FETCH LAST TERM DETAILS

// ==========================================



$lastTermId = $lastTermRank = $lastSessionRank = 0;

$lastTermName = $lastSessionName = null;




if ($currentTermId > 0) {

  $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 < ? ORDER BY t.id DESC LIMIT 1";

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

  if ($stmt) {

    $stmt->bind_param("i", $currentTermId);

    $stmt->execute();

    $lastTermResult = $stmt->get_result();

    if ($lastRow = $lastTermResult->fetch_assoc()) {

      $lastTermId = $lastRow['id'];

      $lastTermName = $lastRow['term_name'];

      $lastSessionName = $lastRow['session_name'];

      $lastTermRank = $termRanksMap[$lastTermName] ?? 0;

      $lastSessionRank = (int) substr($lastSessionName, 0, 4);

    }

    $stmt->close();

  }

}



// ==========================================

// 5. DETERMINE STUDENT TYPE

// ==========================================



$std = 'Old';

$feename = 'School Fees';



// 1. Is the student's admission session in the current academic year?

$isNewAdmitForSession = ($admissionSessionRank === $currentSessionRank);



// 2. Identify "New" status

// Case A: Admitted for a future session entirely

if ($admissionSessionRank > $currentSessionRank) {

  $std = 'New';

  $feename = 'School Fees (New Student)';

}

// Case B: Admitted this session, starting either now or later this year
elseif ($isNewAdmitForSession && $admissionTermRank >= $currentTermRank) {

  $std = 'New';

  $feename = 'School Fees (New Student)';

}



// 3. Logic Gate: Has the student actually started yet?

// This is TRUE only if they joined in a past session or a past/current term of THIS session.

$hasStartedSchool = ($admissionSessionRank < $currentSessionRank) ||

  ($isNewAdmitForSession && $admissionTermRank <= $currentTermRank);





// ==========================================

// 6 & 7. CALCULATE CURRENT TERM FEES

// ==========================================



$currentTermTotalFees = 0.0;

$oldStudentFee = 0.0;



// Base 'Old Student' fee — try fee_records for this session/term first, fall back to fees catalogue

$stmt = $con->prepare("SELECT amount FROM fee_records WHERE class = ? AND stream = ? AND student_type = 'Old' AND name = 'School Fees' AND session = ? AND term = ? ORDER BY id DESC LIMIT 1");

if ($stmt) {

  $stmt->bind_param("ssss", $cls, $st, $currentSessionName, $currentTermName);

  $stmt->execute();

  $result = $stmt->get_result();

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

    $oldStudentFee = (float) $row['amount'];

  }

  $stmt->close();

}

if ($oldStudentFee == 0.0) {

  $stmt = $con->prepare("SELECT amount FROM fees WHERE class = ? AND stream = ? AND student_type = 'Old' AND name = 'School Fees' LIMIT 1");

  if ($stmt) {

    $stmt->bind_param("ss", $cls, $st);

    $stmt->execute();

    $stmt->bind_result($oldStudentFee);

    $stmt->fetch();

    $stmt->close();

    $oldStudentFee = $oldStudentFee ?? 0.0;

  }

}

$currentTermTotalFees = $oldStudentFee;



// Special Scenario Names

$specialFeeName = null;

if ($currentTermRank === 1) {

  if ($cls === 'SS 1' && $demote == 0)

    $specialFeeName = 'First Term SS 1 School Fees';
  elseif ($cls === 'SS 3')

    $specialFeeName = 'First Term SS 3 School Fees';
  elseif ($cls === 'JSS 3')

    $specialFeeName = 'First Term JSS 3 School Fees';

}



if ($specialFeeName) {

  // Try fee_records for this session/term first, fall back to fees catalogue

  $specialFeeAmount = 0.0;

  $stmt = $con->prepare("SELECT amount FROM fee_records WHERE class = ? AND stream = ? AND student_type = 'Old' AND name = ? AND session = ? AND term = ? ORDER BY id DESC LIMIT 1");

  if ($stmt) {

    $stmt->bind_param("sssss", $cls, $st, $specialFeeName, $currentSessionName, $currentTermName);

    $stmt->execute();

    $result = $stmt->get_result();

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

      $specialFeeAmount = (float) $row['amount'];

    }

    $stmt->close();

  }

  if ($specialFeeAmount == 0.0) {

    $stmt = $con->prepare("SELECT amount FROM fees WHERE class = ? AND stream = ? AND student_type = 'Old' AND name = ? LIMIT 1");

    if ($stmt) {

      $stmt->bind_param("sss", $cls, $st, $specialFeeName);

      $stmt->execute();

      $stmt->bind_result($specialFeeAmount);

      $stmt->fetch();

      $stmt->close();

      $specialFeeAmount = $specialFeeAmount ?? 0.0;

    }

  }

  if ($specialFeeAmount > 0) {

    $currentTermTotalFees = $specialFeeAmount;

  }

}



// ==========================================

// 8 & 9. RECORD MANAGEMENT

// ==========================================



saveFeeRecord($con, $feename, $cls, $st, $std, $currentSessionName, $currentTermName, $currentTermTotalFees);



if ($specialFeeName) {

  saveFeeRecord($con, $specialFeeName, $cls, $st, 'Old', $currentSessionName, $currentTermName, $currentTermTotalFees);

}



// ==========================================

// 10. OUTSTANDING BALANCE CALCULATION

// ==========================================



$lastTermTotalFees = 0.0;

$lastTermTotalPaid = 0.0;

$outstandingBalance = 0.0;



/**

 * GATEKEEPER CHECK:

 * We only look for outstanding fees if the student was admitted BEFORE the current term.

 * If (Admission Session < Current Session) OR (Same Session AND Admission Term < Current Term)

 */

$isReturningStudent = ($admissionSessionRank < $currentSessionRank) ||

  ($admissionSessionRank === $currentSessionRank && $admissionTermRank < $currentTermRank);



if ($lastTermName !== null && $isReturningStudent) {



  $lastTermFeeName = 'School Fees';

  $lastTermStudentType = $std;



  // Transition Logic for special classes

  if ($currentTermRank === 2 && in_array($cls, ['JSS 3', 'SS 1', 'SS 3'])) {

    $lastTermFeeName = "First Term $cls School Fees";

    $lastTermStudentType = 'Old';

  }



  // Check if Last Term was exactly their Admission Term

  if ($lastSessionRank === $admissionSessionRank && $lastTermRank === $admissionTermRank) {

    $lastTermFeeName = 'School Fees (New Student)';

    $lastTermStudentType = 'New';

  }



  // 1. Get Fee Amount from History

  $stmt = $con->prepare("SELECT amount FROM fee_records WHERE class = ? AND stream = ? AND student_type = ? AND session = ? AND term = ? AND name = ? ORDER BY id DESC LIMIT 1");

  if ($stmt) {

    $stmt->bind_param("ssssss", $cls, $st, $lastTermStudentType, $lastSessionName, $lastTermName, $lastTermFeeName);

    $stmt->execute();

    $result = $stmt->get_result();

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

      $lastTermTotalFees = $row['amount'] ?? 0.0;

    }

    $stmt->close();

  }



  // 2. Get Payments for that specific Last Term

  $stmt = $con->prepare("SELECT SUM(amount) AS total_paid FROM payment WHERE student_id = ? AND class = ? AND school_type = ? AND session = ? AND Term = ? AND pay_for LIKE '%School Fees%'");

  if ($stmt) {

    $stmt->bind_param("issss", $id, $cls, $st, $lastSessionName, $lastTermName);

    $stmt->execute();

    $result = $stmt->get_result();

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

      $lastTermTotalPaid = $row['total_paid'] ?? 0.0;

    }

    $stmt->close();

  }



  // Calculate the balance only if they were actually here

  $outstandingBalance = max(0.0, $lastTermTotalFees - $lastTermTotalPaid);

} else {

  // If they are brand new this term, outstanding is automatically 0

  $outstandingBalance = 0.0;

}

// ==========================================

// 11. PAYMENT TOTALS

// ==========================================



$totalPaid = 0.0;

$termtotalPaid = 0.0;



// Total Session Payments

$stmt = $con->prepare("SELECT SUM(amount) AS total_paid FROM payment WHERE student_id = ? AND class = ? AND school_type = ? AND session = ? AND pay_for LIKE '%School Fees%'");

if ($stmt) {

  $stmt->bind_param("isss", $id, $cls, $st, $currentSessionName);

  $stmt->execute();

  $result = $stmt->get_result();

  $totalPaid = $result->fetch_assoc()['total_paid'] ?? 0.0;

  $stmt->close();

}



// Current Term Payments

$stmt = $con->prepare("SELECT SUM(amount) AS total_paid FROM payment WHERE student_id = ? AND class = ? AND school_type = ? AND session = ? AND term = ? AND pay_for LIKE '%School Fees%'");

if ($stmt) {

  $stmt->bind_param("issss", $id, $cls, $st, $currentSessionName, $currentTermName);

  $stmt->execute();

  $result = $stmt->get_result();

  $termtotalPaid = $result->fetch_assoc()['total_paid'] ?? 0.0;

  $stmt->close();

}



// ==========================================

// 12. TOTAL SESSION FEE CALCULATION

// ==========================================



$t1_amount = $t2_amount = $t3_amount = 0.0;



if ($admissionSessionRank > $currentSessionRank) {

  // Future Student

  $t1_amount = $t2_amount = $t3_amount = 0.0;

} elseif ($isNewAdmitForSession) {

  // New Admit this session — try fee_records for the admission term first, fall back to fees catalogue

  $newStudentFee = 0.0;

  $admissionTermName = array_search($admissionTermRank, $termRanksMap) ?: '';

  $stmt = $con->prepare("SELECT amount FROM fee_records WHERE class = ? AND stream = ? AND student_type = 'New' AND name = 'School Fees (New Student)' AND session = ? AND term = ? ORDER BY id DESC LIMIT 1");

  if ($stmt) {

    $stmt->bind_param("ssss", $cls, $st, $currentSessionName, $admissionTermName);

    $stmt->execute();

    $result = $stmt->get_result();

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

      $newStudentFee = (float) $row['amount'];

    }

    $stmt->close();

  }

  if ($newStudentFee == 0.0) {

    $stmt = $con->prepare("SELECT amount FROM fees WHERE class = ? AND stream = ? AND student_type = 'New' AND name = 'School Fees (New Student)' LIMIT 1");

    if ($stmt) {

      $stmt->bind_param("ss", $cls, $st);

      $stmt->execute();

      $stmt->bind_result($newStudentFee);

      $stmt->fetch();

      $stmt->close();

      $newStudentFee = $newStudentFee ?? 0.0;

    }

  }



  if ($admissionTermRank === 1) {

    $t1_amount = $newStudentFee;

    $t2_amount = $oldStudentFee;

    $t3_amount = $oldStudentFee;

  } elseif ($admissionTermRank === 2) {

    $t1_amount = 0.0;

    $t2_amount = $newStudentFee;

    $t3_amount = $oldStudentFee;

  } elseif ($admissionTermRank === 3) {

    $t1_amount = 0.0;

    $t2_amount = 0.0;

    $t3_amount = $newStudentFee;

  }

} else {

  // Regular Old Student

  $t1_amount = $t2_amount = $t3_amount = $oldStudentFee;



  // Adjust projection from history 

  // We order by created_at ASC so that the LATEST record is processed LAST in the loop,

  // effectively overwriting any older records for the same term.

  $stmt = $con->prepare("SELECT term, amount FROM fee_records 

                       WHERE session = ? AND class = ? AND stream = ? 

                         AND student_type = 'Old' AND name LIKE '%School Fees%'

                       ORDER BY created_at ASC");



  if ($stmt) {

    $stmt->bind_param("sss", $currentSessionName, $cls, $st);

    $stmt->execute();

    $result = $stmt->get_result();



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

      $termName = $row['term'];

      $amt = (float) ($row['amount'] ?? 0.0);



      if ($amt > 0) {

        if ($termName === 'First Term') {

          $t1_amount = $amt;

        } elseif ($termName === 'Second Term') {

          $t2_amount = $amt;

        } elseif ($termName === 'Third Term') {

          $t3_amount = $amt;

        }

      }

    }

    $stmt->close();

  }

}

$totalSessionFee = $t1_amount + $t2_amount + $t3_amount;



// ==========================================

// 13 & 14. FINAL BALANCES & AUXILIARY

// ==========================================



$totalFeesDue = $currentTermTotalFees + $outstandingBalance;

$totalBalance = max(0.0, $totalSessionFee - $totalPaid);

$termDueOnly = max(0.0, $totalFeesDue - $termtotalPaid);

$totalFees = $currentTermTotalFees;



$hasPaidBoardingForm = false;

$stmt = $con->prepare("SELECT COUNT(*) AS count FROM payment WHERE student_id = ? AND session = ? AND term = ? AND pay_for LIKE 'BOARDING FORM%'");

if ($stmt) {

  $stmt->bind_param("iss", $id, $currentSessionName, $currentTermName);

  $stmt->execute();

  $result = $stmt->get_result();

  $hasPaidBoardingForm = ($result->fetch_assoc()['count'] ?? 0) > 0;

  $stmt->close();

}



// ==========================================

// 15. FEE ID

// ==========================================

$feeId = null;

$query = "SELECT id

          FROM fees

          WHERE class = ? AND stream = ? AND student_type = 'Old'

            AND name = 'School Fees'

          LIMIT 1";

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

if ($stmt) {

  $stmt->bind_param("ss", $cls, $st);

  $stmt->execute();

  $result = $stmt->get_result();

  $row = $result->fetch_assoc();

  $feeId = $row['id'] ?? null;

  $stmt->close();

  unset($row);

}



?>





<!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/sidebaroldstd.php"); ?>



    <!-- Content Wrapper. Contains page content -->

    <div class="content-wrapper">

      <!-- Content Header (Page header) -->

      <section class="content-header premium-header">

        <div class="container-fluid">

          <div class="header-glass-card">

            <div class="row align-items-center">

              <div class="col-md-8">

                <div class="title-section">

                  <div class="icon-box bg-primary-gradient shadow-sm">

                    <i class="fas fa-wallet"></i>

                  </div>

                  <div>

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

                      Payment Management

                      <span class="premium-subtitle text-secondary">
                      </span>

                    </h1>
                    <div class="mt-1">
                      <?php if ($currentSessionName): ?>
                        <span class="badge badge-primary mr-1">
                          <i class="fas fa-calendar-alt"></i>
                          <?= htmlspecialchars($currentSessionName) ?>
                        </span>
                      <?php endif; ?>
                      <?php if ($currentTermName): ?>
                        <span class="badge badge-success">
                          <i class="fas fa-bookmark"></i>
                          <?= htmlspecialchars($currentTermName) ?>
                        </span>
                      <?php else: ?>
                        <span class="badge badge-warning">
                          <i class="fas fa-exclamation-triangle"></i> No active term
                        </span>
                      <?php endif; ?>
                    </div>


                  </div>

                </div>

              </div>


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

                <nav aria-label="breadcrumb">

                  <ol class="breadcrumb premium-breadcrumb">

                    <li class="breadcrumb-item"><a href="oldstdday.php" class="text-primary">Home</a></li>

                    <li class="breadcrumb-item active" aria-current="page">Pay Tuition Fees</li>

                  </ol>

                </nav>

              </div>

            </div>

          </div>

        </div>

      </section>

      <!-- Wallet instant-approval banner -->
      <?php
      $_wid  = $_SESSION['student_id'] ?? 0;
      $_wq   = mysqli_query($con, "SELECT balance FROM wallets WHERE student_id = '$_wid' LIMIT 1");
      $_wrow = $_wq ? mysqli_fetch_assoc($_wq) : null;
      $_wbal = $_wrow ? floatval($_wrow['balance']) : -1;
      ?>
      <div style="margin:16px auto 4px;padding:0 15px;">
        <?php if ($_wbal > 0): ?>
          <div style="background:linear-gradient(135deg,#1e3a5f,#3b82f6);border-radius:14px;padding:16px 20px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;">
            <div style="display:flex;align-items:center;gap:12px;">
              <div style="width:40px;height:40px;background:rgba(255,255,255,.15);border-radius:10px;display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                <i class="fas fa-bolt" style="color:#fff;font-size:.95rem;"></i>
              </div>
              <div>
                <p style="margin:0;font-weight:700;color:#fff;font-size:.92rem;">Get Instant Payment Approval!</p>
                <p style="margin:0;font-size:.78rem;color:rgba(255,255,255,.8);">Pay with your School Wallet and your payment is approved immediately — no waiting for admin. Wallet Balance: <strong>₦<?= number_format($_wbal, 2) ?></strong></p>
              </div>
            </div>
            <a href="wallet_details.php?tab_id=<?= $tabSessionID ?>" style="background:rgba(255,255,255,.18);border:1.5px solid rgba(255,255,255,.35);color:#fff;height:38px;padding:0 20px;border-radius:10px;font-size:.82rem;font-weight:700;display:inline-flex;align-items:center;gap:6px;text-decoration:none;white-space:nowrap;">
              <i class="fas fa-wallet"></i> Manage Wallet
            </a>
          </div>
        <?php else: ?>
          <div style="background:linear-gradient(135deg,#0f172a,#1e293b);border-radius:14px;padding:16px 20px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;">
            <div style="display:flex;align-items:center;gap:12px;">
              <div style="width:40px;height:40px;background:rgba(255,255,255,.1);border-radius:10px;display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                <i class="fas fa-wallet" style="color:#94a3b8;font-size:.95rem;"></i>
              </div>
              <div>
                <p style="margin:0;font-weight:700;color:#f1f5f9;font-size:.92rem;">Want Instant Payment Approval?</p>
                <p style="margin:0;font-size:.78rem;color:#94a3b8;"><?= $_wbal < 0 ? "You don't have a wallet yet." : "Your wallet has no funds." ?> Fund your School Wallet and your payment will be approved instantly — no admin needed.</p>
              </div>
            </div>
            <a href="wallet_details.php?tab_id=<?= $tabSessionID ?>" style="background:linear-gradient(135deg,#1e3a5f,#3b82f6);color:#fff;height:38px;padding:0 20px;border-radius:10px;font-size:.82rem;font-weight:700;display:inline-flex;align-items:center;gap:6px;text-decoration:none;white-space:nowrap;">
              <i class="fas fa-wallet"></i> <?= $_wbal < 0 ? 'Set Up Wallet' : 'Fund Wallet' ?>
            </a>
          </div>
        <?php endif; ?>
      </div>

      <?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="confirmpay.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"
                            style="background: linear-gradient(135deg, var(--dark), var(--primary));">

                            <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 Instalments</option>

                            <option value="full_3">Full Session Fees 3 Instalments</option>

                            <!-- <option value="full_4">Full Session Fees 4 Instalments</option> -->

                            <option value="custom">Custom Payment (School Fees)</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 1/3 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; ?>">

                        <input type="hidden" name="termdue" id="termdue" value="<?php echo $termDueOnly; ?>">



                        <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) {

                        if (customOption) customOption.disabled = false;



                        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 / 3;

                      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;



                          if (session_fee <= 0) {

                            // Balance is zero, allow any custom amount (new session)

                            warningText.style.display = 'none';

                            amount = customAmount;

                            amountField.value = amount.toFixed(2);

                            payButton.href = "confirmpay.php?fee_id=<?php echo $feeId; ?>&termdue=<?php echo $termDueOnly ?>&tab_id=<?php echo $tabSessionID; ?>&pay_amount=" + amount.toFixed(2);

                            payButton.classList.remove('disabled');

                          } else 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 = "confirmpay.php?fee_id=<?php echo $feeId; ?>&tab_id=<?php echo $tabSessionID; ?>&termdue=<?php echo $totalBalance ?>&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 = "confirmpay.php?fee_id=<?php echo $feeId; ?>&tab_id=<?php echo $tabSessionID; ?>&termdue=<?php echo $totalBalance ?>&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 = "confirmpay.php?fee_id=<?php echo $feeId; ?>&tab_id=<?php echo $tabSessionID; ?>&termdue=<?php echo $totalBalance ?>&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="confirmpay.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"
                            style="background: linear-gradient(135deg, var(--dark), var(--primary));">

                            <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($termDueOnly, 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 Terms Payment</option>

                            <option value="full_session">Full Session Payment</option>

                            <option value="custom">Custom Payment (School Fees)</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; ?>">

                        <input type="hidden" name="termdue" id="termdue" value="<?php echo $termDueOnly; ?>">



                        <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) {

                        // Allow only custom payment to enable future session payments

                        if (customOption) customOption.disabled = false;

                        return;

                      }





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



                          if (session_fee <= 0) {

                            // Balance is zero, allow any custom amount (new session)

                            warningText.style.display = 'none';

                            amount = customAmount;

                            amountField.value = amount.toFixed(2);

                            payButton.href = "confirmpay.php?fee_id=<?php echo $feeId; ?>&termdue=<?php echo $termDueOnly ?>&tab_id=<?php echo $tabSessionID; ?>&pay_amount=" + amount.toFixed(2);

                            payButton.classList.remove('disabled');

                          } else 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 = "confirmpay.php?fee_id=<?php echo $feeId; ?>&termdue=<?php echo $termDueOnly ?>&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 = "confirmpay.php?fee_id=<?php echo $feeId; ?>&termdue=<?php echo $termDueOnly ?>&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 = "confirmpay.php?fee_id=<?php echo $feeId; ?>&termdue=<?php echo $termDueOnly ?>&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

              // Determine summer school fee name based on class
              
              $summerFeeName = '';

              if (in_array($cls, ['JSS 1', 'JSS 2', 'JSS 3'])) {

                $summerFeeName = 'JSS 1 - 3 SUMMER SCHOOL';

              } elseif (in_array($cls, ['SS 1', 'SS 2', 'SS 3'])) {

                $summerFeeName = 'SS 1 - 3 SUMMER SCHOOL';

              }



              // Build the fee query
              
              $query1 = "SELECT * FROM fees 

  WHERE class = '$cls' 

    AND stream = '$st' 

    AND student_type = 'Old'

    AND (

      name IN ('Lesson Fees', 'GCE CLASS FEES'" .

                ($summerFeeName ? ", '$summerFeeName'" : '') .

                ")

  )";



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

                    <br>

                    <hr>

                    <br>

                    <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-4 gap-4 mb-10">

                      <?php

                      if (mysqli_num_rows($result1) > 0) {



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



                          $feeType = htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8');

                          $amount = (float) $row['amount'];

                          $class = htmlspecialchars($row['class'], ENT_QUOTES, 'UTF-8');

                          $feeId = (int) $row['id'];



                          /* -------------------------------

                             STYLE MAPPING (SECURE + CLEAN)

                          -------------------------------- */

                          if (stripos($feeType, 'FULL TERM') !== false) {

                            $style = ["bg" => "bg-cyan-50", "text" => "text-cyan-600"];

                          } elseif (stripos($feeType, 'PART PAYMENT') !== false) {

                            $style = ["bg" => "bg-orange-50", "text" => "text-orange-600"];

                          } elseif (stripos($feeType, 'FULL 2 TERM') !== false) {

                            $style = ["bg" => "bg-rose-50", "text" => "text-rose-600"];

                          } elseif (stripos($feeType, 'FULL SESSION') !== false) {

                            $style = ["bg" => "bg-blue-50", "text" => "text-blue-600"];

                          } else {

                            $style = ["bg" => "bg-emerald-50", "text" => "text-emerald-600"];

                          }

                          ?>

                          <div class="bento-card group">

                            <div class="flex justify-between items-start mb-4">

                              <div
                                class="w-10 h-10 <?php echo $style['bg']; ?> <?php echo $style['text']; ?> rounded-xl flex items-center justify-center transition-transform group-hover:scale-110">

                                <i class="fas fa-money-bill-wave"></i>

                              </div>



                              <a href="confirmpay.php?fee_id=<?php echo $feeId; ?>&pay_amount=<?php echo $amount; ?>"
                                class="text-[12px] font-black text-slate-400 group-hover:text-slate-900 transition-colors tracking-tighter">

                                <i class="fas fa-arrow-right"></i> PAY HERE

                              </a>

                            </div>



                            <h5 class="text-[14px] font-bold text-slate-600 truncate">

                              <?php echo $class; ?>

                            </h5>



                            <p class="text-[11px] font-bold uppercase text-slate-500 truncate">

                              <?php echo $feeType; ?>

                            </p>



                            <p class="mt-2 text-[13px] font-extrabold <?php echo $style['text']; ?>">

                              ₦<?php echo number_format($amount, 2); ?>

                            </p>



                            <div class="mt-4 w-full h-1 bg-slate-200/50 rounded-full overflow-hidden">

                              <div
                                class="h-full <?php echo str_replace('text-', 'bg-', $style['text']); ?> opacity-40 w-full transform -translate-x-1/2 group-hover:translate-x-0 transition-transform duration-1000">

                              </div>

                            </div>

                          </div>

                          <?php

                        }

                      } else {

                        echo "<p class='text-red-500 col-span-full text-sm'>No lesson fee available at the moment.</p>";

                      }

                      ?>

                    </div>



                  </div>

                </form>







              </div>

            </div>

          </div>

        </div>

      </section>



      <?php if ($hasPaidBoardingForm): ?>

        <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 = 'Old' 

          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 (New Student)

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

                      <br>

                      <hr>

                      <br>

                      <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-4 gap-4 mb-10">

                        <?php

                        if (mysqli_num_rows($result2) > 0) {



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



                            $feeType = htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8');

                            $amount = (float) $row['amount'];

                            $class = htmlspecialchars($row['class'], ENT_QUOTES, 'UTF-8');

                            $feeId = (int) $row['id'];



                            /* -------------------------------

                               STYLE MAPPING (SECURE + CLEAN)

                            -------------------------------- */

                            if (stripos($feeType, 'FULL TERM') !== false) {

                              $style = ["bg" => "bg-cyan-50", "text" => "text-cyan-600"];

                            } elseif (stripos($feeType, 'PART PAYMENT') !== false) {

                              $style = ["bg" => "bg-orange-50", "text" => "text-orange-600"];

                            } elseif (stripos($feeType, 'FULL 2 TERM') !== false) {

                              $style = ["bg" => "bg-rose-50", "text" => "text-rose-600"];

                            } elseif (stripos($feeType, 'FULL SESSION') !== false) {

                              $style = ["bg" => "bg-blue-50", "text" => "text-blue-600"];

                            } else {

                              $style = ["bg" => "bg-emerald-50", "text" => "text-emerald-600"];

                            }

                            ?>

                            <div class="bento-card group">

                              <div class="flex justify-between items-start mb-4">

                                <div
                                  class="w-10 h-10 <?php echo $style['bg']; ?> <?php echo $style['text']; ?> rounded-xl flex items-center justify-center transition-transform group-hover:scale-110">

                                  <i class="fas fa-money-bill-wave"></i>

                                </div>



                                <a href="confirmpay.php?fee_id=<?php echo $feeId; ?>&pay_amount=<?php echo $amount; ?>"
                                  class="text-[12px] font-black text-slate-400 group-hover:text-slate-900 transition-colors tracking-tighter">

                                  <i class="fas fa-arrow-right"></i> PAY HERE

                                </a>

                              </div>



                              <h5 class="text-[14px] font-bold text-slate-600 truncate">

                                <?php echo $class; ?>

                              </h5>



                              <p class="text-[11px] font-bold uppercase text-slate-500 truncate">

                                <?php echo $feeType; ?>

                              </p>



                              <p class="mt-2 text-[13px] font-extrabold <?php echo $style['text']; ?>">

                                ₦<?php echo number_format($amount, 2); ?>

                              </p>



                              <div class="mt-4 w-full h-1 bg-slate-200/50 rounded-full overflow-hidden">

                                <div
                                  class="h-full <?php echo str_replace('text-', 'bg-', $style['text']); ?> opacity-40 w-full transform -translate-x-1/2 group-hover:translate-x-0 transition-transform duration-1000">

                                </div>

                              </div>

                            </div>

                            <?php

                          }

                        } else {

                          echo "<p class='text-red-500 col-span-full text-sm'>No lesson fee available at the moment.</p>";

                        }

                        ?>

                      </div>

                    </div>

                  </form>

                </div>

              </div>

            </div>

          </div>

        </section>

      <?php endif; ?>



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