<?php

include('includes/session.php');

error_reporting(0);

include('includes/dbconnection.php');

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

// ==========================================
// FETCH CURRENT SESSION AND TERM
// ==========================================

$stResult = resolveCurrentSessionTerm($con);
$currentSessionId   = $stResult['session_id'];
$currentSessionName = $stResult['session_name'];
$currentTermId      = $stResult['term_id'];
$currentTermName    = $stResult['term_name'];

// ==========================================
// STUDENT DETAILS
// ==========================================

$id  = $_SESSION['student_id'];
$cls = trim($_SESSION['class']);
$st  = trim($_SESSION['stream']);
$std = 'New';

// Fetch admission session and term from students table
$admissionSession = '';
$admissionTerm    = '';
$stmt = $con->prepare("SELECT academic_session, admission_term FROM students WHERE id = ? LIMIT 1");
if ($stmt) {
  $stmt->bind_param("i", $id);
  $stmt->execute();
  $row = $stmt->get_result()->fetch_assoc();
  $stmt->close();
  $admissionSession = trim($row['academic_session'] ?? '');
  $admissionTerm    = trim($row['admission_term'] ?? '');
}

$termRanksMap = ['First Term' => 1, 'Second Term' => 2, 'Third Term' => 3];
$admissionSessionRank = (int) substr($admissionSession, 0, 4);
$admissionTermRank    = $termRanksMap[$admissionTerm] ?? 0;
$currentSessionRank   = (int) substr($currentSessionName ?? '', 0, 4);
$currentTermRank      = $termRanksMap[$currentTermName] ?? 0;

// A new student has an outstanding balance only if the current term is strictly
// after their admission term (same session, later term) or in a later session.
$isReturningNewStudent = ($admissionSessionRank < $currentSessionRank) ||
  ($admissionSessionRank === $currentSessionRank && $admissionTermRank < $currentTermRank);

// ==========================================
// FETCH LAST TERM DETAILS
// ==========================================

$lastTermName = $lastSessionName = null;

if ($currentTermId > 0) {
  $stmt = $con->prepare("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");
  if ($stmt) {
    $stmt->bind_param("i", $currentTermId);
    $stmt->execute();
    $lastRow = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    if ($lastRow) {
      $lastTermName    = $lastRow['term_name'];
      $lastSessionName = $lastRow['session_name'];
    }
  }
}

// ==========================================
// CURRENT TERM FEE — fee_records first, fees catalogue fallback
// ==========================================

$totalFees = 0.0;

// Try fee_records for this session/term
$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, $currentTermName);
  $stmt->execute();
  $row = $stmt->get_result()->fetch_assoc();
  $stmt->close();
  if ($row) {
    $totalFees = (float) $row['amount'];
  }
}

// Fall back to fees catalogue
if ($totalFees == 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();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $totalFees = (float) ($row['amount'] ?? 0.0);
  }
}

// ==========================================
// FEE ID (for payment form)
// ==========================================

$feeId = null;
$stmt = $con->prepare("SELECT id 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();
  $row = $stmt->get_result()->fetch_assoc();
  $stmt->close();
  $feeId = $row['id'] ?? null;
}

// ==========================================
// OUTSTANDING BALANCE FROM ADMISSION TERM
// ==========================================

$outstandingBalance = 0.0;

// Only check if the student has been here for more than their admission term
if ($isReturningNewStudent && $admissionSession !== '' && $admissionTerm !== '') {

  // Fee for the admission term — fee_records first, fees catalogue fallback
  $admissionTermFee = 0.0;
  $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, $admissionSession, $admissionTerm);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    if ($row) {
      $admissionTermFee = (float) $row['amount'];
    }
  }
  if ($admissionTermFee == 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();
      $row = $stmt->get_result()->fetch_assoc();
      $stmt->close();
      $admissionTermFee = (float) ($row['amount'] ?? 0.0);
    }
  }

  // Payments made during the admission term
  $admissionTermPaid = 0.0;
  $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, $admissionSession, $admissionTerm);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $admissionTermPaid = (float) ($row['total_paid'] ?? 0.0);
  }

  $outstandingBalance = max(0.0, $admissionTermFee - $admissionTermPaid);
}


// ==========================================
// Total Amount made during the admission term for display
// ==========================================

$totalPaid = 0.0;
$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, $admissionSession, $admissionTerm);
  $stmt->execute();
  $row = $stmt->get_result()->fetch_assoc();
  $stmt->close();
  $totalPaid = (float) ($row['total_paid'] ?? 0.0);
}

// ==========================================
// FINAL BALANCES
// ==========================================

$totalFeesDue = $totalFees + $outstandingBalance;
$totalBalance = max(0.0, $totalFeesDue - $totalPaid);
$termDueOnly  = $totalBalance;





?>







<!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/sidebarstdboard.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"><?php echo $currentTermName; ?> |
                        <?php echo $currentSessionName; ?></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="newstdboard.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>



      <!-- 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="confirmpaynb.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));">

                          <div class="row">



                            <div class="col-sm-4 mb-1">

                              <h6><b>Full School Fees: ₦<?php echo number_format($totalFees, 2); ?></b></h6>

                            </div>

                            <div class="col-sm-4 mb-1">

                              <h6><b>Full School Fees (Paid): ₦<?php echo number_format($totalPaid, 2); ?></b></h6>

                            </div>

                            <div class="col-sm-4 mb-1">

                              <h6><b>Full School Fees (Outstanding): ₦<span
                                    id="balance_display"><?php echo number_format($totalBalance, 2); ?></span></b></h6>

                            </div>

                          </div>

                        </div>

                      </div>



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

                        <label for="percentage">Payment Option</label>

                        <select id="payment_option" name="payment_option" class="form-control"
                          onchange="calculateAmount()">

                          <option value="">-- Select Payment Option --</option>

                          <?php if ($admissionSessionRank > $currentSessionRank): ?>
                          <option value="half">Acceptance Fees Payment</option>

                          <option value="bal">Balance after Acceptance Fees</option>
                          <?php endif; ?>

                          <option value="full">Full School Fees Payment</option>

                          <option value="custom">Custom Amount</option>

                        </select>

                        <!-- Hidden field to store total fees for JavaScript -->

                        <input type="hidden" id="term_fee" value="<?php echo $totalFees; ?>">

                        <input type="hidden" id="total_paid" value="<?php echo $totalPaid; ?>">

                        <input type="hidden" id="total_balance" value="<?php echo $totalBalance; ?>">

                      </div>

                      <div id="customAmountDiv" class="col-md-6" style="display: none;">

                        <label for="custom_amount">Enter Custom 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 the
                          Acceptance Fee and cannot exceed the outstanding balance of ₦<?php echo number_format($totalBalance, 2); ?>.</small>
                          <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>

                      <?php $acceptancePercentage = 100000; ?>

                      <input type="hidden" id="acceptance_percentage" value="<?php echo $acceptancePercentage; ?>">



                      <!-- Hidden Input to Store Fee ID -->

                      <input type="hidden" name="fee_id" id="fee_id" value="<?php echo $feeId; ?>">





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

                  $(document).ready(function () {

                    $('#payment_option').select2();



                    const totalPaid = parseFloat(document.getElementById('total_paid').value) || 0;

                    const acceptanceFee = smartRoundToThousand(acceptanceRatio * parseFloat(document.getElementById('term_fee').value || 0));



                    const paymentOption = document.getElementById('payment_option');

                    const halfOption = paymentOption.querySelector('option[value="half"]');

                    const balOption = paymentOption.querySelector('option[value="bal"]');

                    const fullOption = paymentOption.querySelector('option[value="full"]');



                    if (totalPaid < acceptanceFee) {

                      // Disable "Balance after Acceptance"

                      if (balOption) {

                        balOption.disabled = true;

                        balOption.textContent += " (Not eligible)";

                      }

                    }



                    if (totalPaid >= acceptanceFee) {

                      // Disable "Acceptance Fees"

                      if (halfOption) {

                        halfOption.disabled = true;

                        halfOption.textContent += " (Already paid)";

                        // Disable "Full School Fees" if acceptance fee is paid

                        fullOption.disabled = true;

                        fullOption.textContent += " (Not eligible)";

                      }

                    }

                  });

                  // Function to round to the nearest thousand intelligently

                  function smartRoundToThousand(value) {

                    let remainder = value % 1000;



                    if (remainder > 100) {

                      return Math.ceil(value / 1000) * 1000;

                    } else {

                      return Math.floor(value / 1000) * 1000;

                    }

                  }



                  let acceptanceRatio = 30000 / 190000; // Acceptance Fee



                  function calculateAmount() {

                    var termFee = parseFloat(document.getElementById('term_fee').value) || 0;

                    var acceptancePercentage = parseFloat(document.getElementById('acceptance_percentage').value) || 0;

                    var acceptanceFee = smartRoundToThousand(acceptanceRatio * termFee); // Calculate acceptance fee based on total fee amount

                    var totalBalance = parseFloat(document.getElementById('total_balance').value) || 0;

                    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 amount = 0;



                    if (paymentOption === 'custom') {

                      customAmountDiv.style.display = 'block';

                      var customAmountInput = document.getElementById('custom_amount').value;



                      if (customAmountInput !== '') { // User has typed something

                        var customAmount = parseFloat(customAmountInput) || 0;



                        if (customAmount < acceptanceFee || customAmount > totalBalance) {

                          warningText.style.display = 'block'; // Show warning

                          amountField.value = '';

                          payButton.href = "#";

                          payButton.classList.add('disabled');

                        } else {

                          warningText.style.display = 'none'; // Hide warning

                          amount = customAmount;

                          amountField.value = amount.toFixed(2);

                          payButton.href = "confirmpaynb.php?fee_id=<?php echo $feeId; ?>&termdue=<?php echo $termDueOnly ?>&tab_id=<?php echo $tabSessionID; ?>&pay_amount=" + amount.toFixed(2) + "&adm_session=<?php echo urlencode($admissionSession); ?>&adm_term=<?php echo urlencode($admissionTerm); ?>";

                          payButton.classList.remove('disabled');

                        }

                      } else {

                        warningText.style.display = 'none'; // Hide warning when empty

                        amountField.value = '';

                        payButton.href = "#";

                        payButton.classList.add('disabled');

                      }

                    } else {

                      customAmountDiv.style.display = 'none';

                      warningText.style.display = 'none'; // Hide warning for other options



                      switch (paymentOption) {

                        case 'half':

                          amount = acceptanceFee;

                          break;

                        case 'full':

                          amount = termFee;

                          break;

                        case 'bal':

                          amount = termFee - acceptanceFee;

                          break;

                        case 'full_session':

                          amount = termFee * 3;

                          break;

                        default:

                          amount = 0;

                      }



                      if (amount > 0) {

                        amountField.value = amount.toFixed(2);

                        payButton.href = "confirmpaynb.php?fee_id=<?php echo $feeId; ?>&termdue=<?php echo $termDueOnly ?>&tab_id=<?php echo $tabSessionID; ?>&pay_amount=" + amount.toFixed(2) + "&adm_session=<?php echo urlencode($admissionSession); ?>&adm_term=<?php echo urlencode($admissionTerm); ?>";

                        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>

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