<?php
session_name('super_admin_session');
if (!is_dir(dirname(__DIR__) . '/session_data/super')) {
  mkdir(dirname(__DIR__) . '/session_data/super', 0700, true);
}
session_save_path(dirname(__DIR__) . '/session_data/super');
session_set_cookie_params(['path' => '/', 'httponly' => true, 'samesite' => 'Strict']);
session_start();
error_reporting(0);
include('includes/dbconnection.php');
require_once __DIR__ . '/includes/session_term_helper.php';
require_once __DIR__ . '/helpers/term_allocation_helpers.php';
// Fetch current session and term (with gap/fallback support)
$stResult = resolveCurrentSessionTerm($con);
$currentSessionId   = $stResult['session_id'];
$currentSessionName = $stResult['session_name'];
$currentTermId      = $stResult['term_id'];
$currentTermName    = $stResult['term_name'];
include('includes/flash.php');

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use Dotenv\Dotenv;

// required files
require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';

// Load Composer dependencies
require_once 'vendor/autoload.php';
// Load environment variables
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();

$school_name = $_ENV['SCHOOL_NAME'];
$school_address = $_ENV['SCHOOL_ADDRESS'];

$message_id = $_GET['id'] ?? 0;

// Ensure $messageData exists, otherwise default to empty array
$messageData = $_SESSION['message_data'] ?? [];

// Assign default values if keys are missing
$discountUsed = $messageData['discount_used'] ?? 'No';
$discountAmount = floatval($messageData['discount_amount'] ?? 0);
$discountPercent = floatval($messageData['discount_percent'] ?? 0);
$amountt = floatval($messageData['amount'] ?? 0);

$studentNo = $messageData['regno'] ?? '';
$demote = 0;
$admission_no = $messageData['fullname'] ?? '';
$currentSession = $messageData['session'] ?? '';
$currentTerm = $messageData['term'] ?? '';
$payfor = $messageData['purpose'] ?? '';
$cls = $messageData['class'] ?? '';
$st = $messageData['school_type'] ?? '';

// Safe fallback if studentNo is missing
if ($studentNo) {
  $sqld = "SELECT * FROM students WHERE studentno = ?";
  $stmtd = $dbh->prepare($sqld);
  $stmtd->execute([$studentNo]);

  if ($stmtd->rowCount() > 0) {
    $fecthemaild = $stmtd->fetch(PDO::FETCH_ASSOC);
    $demote = $fecthemaild['demote_status'] ?? 0;
  }
}

// Calculate original amount before discount
if (!empty($discountPercent) && $discountPercent > 0) {
  $originalAmount = $amountt / (1 - ($discountPercent / 100));
  $originalAmount = round($originalAmount, 2);
  $discountAmount = $originalAmount - $amountt;
} else {
  $originalAmount = $amountt;
  $discountAmount = 0;
  $discountPercent = 0;
}

// Initialize totals
$totalPaidSession = 0;
$totalPaidTerm = 0;

if (!empty($admission_no) && !empty($currentSession)) {
  // Total paid for the session
  $querySession = mysqli_query($con, "SELECT SUM(amount) as total FROM payment WHERE studentName = '$admission_no' AND session = '$currentSession' AND pay_for LIKE '%School Fees%'");
  $rowSession = mysqli_fetch_assoc($querySession);
  $totalPaidSession = $rowSession['total'] ?? 0;

  // Total paid for the term
  if (!empty($currentTerm)) {
    $queryTerm = mysqli_query($con, "SELECT SUM(amount) as total FROM payment WHERE studentName = '$admission_no' AND session = '$currentSession' AND term = '$currentTerm' AND pay_for LIKE '%School Fees%'");
    $rowTerm = mysqli_fetch_assoc($queryTerm);
    $totalPaidTerm = $rowTerm['total'] ?? 0;
  }
}

if (strlen($_SESSION['sid']) == 0) {
  header('location:logout.php');
} else {

  if (isset($_POST['submit'])) {

    $regno = $_POST['fullname'];
    $adno = $_POST['fullname'];
    $term = $_POST['term'];
    $session = $_POST['session'];
    $class = $_POST['class'];
    $school_type = $_POST['school_type'];
    $payment_type = $_POST['payment_type'];
    $pay_id = $_POST['pay_id'];
    $amount = $_POST['original_amount'];
    $payment_for = $_POST['pay_for'];
    $studentname = $_POST['stdname'];
    $method = $_POST['method'];
    $email = $_POST['email'];
    $reg_id = $_POST['reg_id'];
    $discountUsed = $_POST['discount_used'];
    $discountAmount = $_POST['discount_amount'];
    $discountPercent = $_POST['discount_percent'];


    $sql = "SELECT * FROM students WHERE studentno = ?";
    $stmt = $dbh->prepare($sql);
    $stmt->execute([$adno]);

    if ($stmt->rowCount() > 0) {

      $fecthemail = $stmt->fetch(PDO::FETCH_ASSOC);
      $id = $fecthemail['id'];
      $section = $fecthemail['section'];
      $repeat = $fecthemail['demote_status'];

      // Escape all user-supplied string variables for mysqli_query calls (Bug 5 fix)
      $safe_adno         = mysqli_real_escape_string($con, $adno);
      $safe_studentname  = mysqli_real_escape_string($con, $studentname);
      $safe_session      = mysqli_real_escape_string($con, $session);
      $safe_class        = mysqli_real_escape_string($con, $class);
      $safe_school_type  = mysqli_real_escape_string($con, $school_type);
      $safe_payment_type = mysqli_real_escape_string($con, $payment_type);
      $safe_pay_id       = mysqli_real_escape_string($con, $pay_id);
      $safe_method       = mysqli_real_escape_string($con, $method);
      $safe_section      = mysqli_real_escape_string($con, $section);
      $safe_payment_for  = mysqli_real_escape_string($con, $payment_for);
      $safe_discountUsed = mysqli_real_escape_string($con, $discountUsed);
      $safe_id           = (int) $id;
      $safe_discountAmt  = (float) $discountAmount;
      $safe_discountPct  = (float) $discountPercent;


      try {
        // Check for duplicate payment before proceeding
        $duplicateCheck = mysqli_query($con, "SELECT id FROM payment WHERE studentno = '$safe_adno' AND pay_id = '$safe_pay_id' LIMIT 1");
        if (mysqli_num_rows($duplicateCheck) > 0) {
          flash_alert('Duplicate payment detected! This payment has already been approved.', 'pay_tuition.php');
          header('Location: pay_tuition.php');
          exit;
        }

        $dbh->beginTransaction();

        $mail = new PHPMailer(true);

        // SMTP configuration from .env
        $mail->isSMTP();
        $mail->Host = $_ENV['SMTP_HOST'];
        $mail->SMTPAuth = true;
        $mail->Username = $_ENV['SMTP_NO_REPLY'];
        $mail->Password = $_ENV['SMTP_NO_REPLY_PASSWORD'];
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port = $_ENV['SMTP_PORT'];
        $mail->Timeout = 10;

        $mail->setFrom($_ENV['SMTP_NO_REPLY'], $_ENV['SCHOOL_NAME']);
        $mail->addAddress($email, $studentname);
        $mail->isHTML(true);
        $mail->Subject = $school_name . 'School Fees payment Approval Notification';
        $mail->Body = "
                <html>
                <body>
                    <div style='max-width: 600px; margin: auto; font-family: Arial, sans-serif; background-color: #f4f4f4; padding: 20px;'>
                        <h1 style='color: #ffffff; text-align: center; padding: 10px 0; background-color: #4CAF50;'>Payment Approved</h1>
                        <p>Dear $studentname,</p>
                        <p>We are pleased to inform you that your payment of NGN $amount has been confirmed successfully.</p>
                        <hr>
                        <h5>Payment Details</h5>
                        <hr>
                        <p><strong>Amount Paid:</strong> NGN $amount</p>
                        <p><strong>Class:</strong> $class</p>
                        <p><strong>Term:</strong> $term</p>
                        <p><strong>Session:</strong> $session</p>
                        <p><strong>Purpose of Payment:</strong> $payment_for</p>
                        <p><strong>Payment Method:</strong> $method</p>" .
          ($discountUsed === 'Yes' ? "<p><strong>Discount Applied:</strong> NGN $discountAmount ($discountPercent%)</p>" : "") .
          "<p>Please login to your student portal to view and download your receipt and other necessary documents.</p>
                                      <p>Thank you!</p>
                        <hr>
                        <center>
                            <p>$school_name &copy; " . date("Y") . ". All Rights Reserved.</p>
                        </center>
                    </div>
                </body>
                </html>";

        // ... (Your existing code fetching student details and sending mail)

        $mail->send();

        // ✅ LOGIC START: Identify Final Year Students (SS 3 and JSS 3)
        $isFinalYear = (trim($class) === 'SS 3' || trim($class) === 'JSS 3');

        // ── Future session guard ───────────────────────────────────────────────
        if (isFutureSession($safe_session, $currentSessionName)) {
            if (!validateFutureSessionPayment($con, $safe_id, $currentSessionName, $class, $st, $safe_session)) {
                $dbh->rollBack();
                flash_alert('Future session payment rejected: student still has unpaid fees in the current session (' . $currentSessionName . '). Please clear those first.', 'pay_tuition.php');
                header('Location: pay_tuition.php');
                exit;
            }
        }

        // Determine if student is NEW or OLD
        $isNew = isNewStudent($con, $safe_id, $safe_session);
        $admissionTerm = null;
        
        if ($isNew) {
          // For NEW students, get admission term
          $admissionTerm = getAdmissionTerm($con, $safe_id, $safe_session);
          if (!$admissionTerm) {
            $admissionTerm = 'First Term'; // Default if not found
          }
        }
        
        // Use helper function to allocate payment across terms
        $allocations = allocatePaymentAcrossTerms($con, $safe_id, $amount, $safe_session, $class, $st, $admissionTerm);
        
        // Insert payment records for each allocation
        $allInserted = true;
        $excessAmount = 0;
        
        foreach ($allocations as $allocation) {
          $allocSession = $allocation['session'];
          $allocTerm = $allocation['term'];
          $allocAmount = $allocation['amount'];
          $payFor = $allocation['pay_for'];
          
          // Check if this is an excess/carry-over allocation to next session
          if ($allocSession !== $safe_session) {
            // This is excess payment being carried to next session
            $excessAmount = $allocAmount;
            
            // Insert into payment table for next session
            $term_pay_id = $pay_id . '_next_' . strtolower(str_replace(' ', '_', $allocTerm));
            $safe_term_pay_id = mysqli_real_escape_string($con, $term_pay_id);
            $safe_alloc_session = mysqli_real_escape_string($con, $allocSession);
            $safe_alloc_term = mysqli_real_escape_string($con, $allocTerm);
            $safe_pay_for = mysqli_real_escape_string($con, $payFor);
            
            $q = mysqli_query($con, "INSERT INTO payment (studentno, studentName, Term, session, class, school_type, payment_type, pay_id, amount, pay_for, student_id, method, section, discount_used, discount_amount, discount_percent)
              VALUES ('$safe_adno', '$safe_studentname', '$safe_alloc_term', '$safe_alloc_session', '$safe_class', '$safe_school_type', '$safe_payment_type', '$safe_term_pay_id', '" . (float)$allocAmount . "', '$safe_pay_for', '$safe_id', '$safe_method', '$safe_section', 'No', 0, 0)");
            if (!$q) { $allInserted = false; break; }
          } else {
            // This is a regular allocation to current session
            $term_pay_id = $pay_id . '_' . str_replace(' ', '_', strtolower($allocTerm));
            $safe_term_pay_id = mysqli_real_escape_string($con, $term_pay_id);
            $safe_alloc_term = mysqli_real_escape_string($con, $allocTerm);
            $safe_pay_for = mysqli_real_escape_string($con, $payFor);
            
            $q = mysqli_query($con, "INSERT INTO payment (studentno, studentName, Term, session, class, school_type, payment_type, pay_id, amount, pay_for, student_id, method, section, discount_used, discount_amount, discount_percent)
              VALUES ('$safe_adno', '$safe_studentname', '$safe_alloc_term', '$safe_session', '$safe_class', '$safe_school_type', '$safe_payment_type', '$safe_term_pay_id', '" . (float)$allocAmount . "', '$safe_pay_for', '$safe_id', '$safe_method', '$safe_section', '$safe_discountUsed', '$safe_discountAmt', '$safe_discountPct')");
            if (!$q) { $allInserted = false; break; }
          }
        }
        
        // Handle excess for final year students (create refund record)
        if ($allInserted && $isFinalYear && $excessAmount > 0) {
          mysqli_query($con, "INSERT INTO refund (student_id, studentno, studentName, class, section, session, term, amount, pay_id, method, school_type, payment_type, status, reason)
            VALUES ('$safe_id', '$safe_adno', '$safe_studentname', '$safe_class', '$safe_section', '$safe_session', 'Second Term', '$excessAmount', '$safe_pay_id', '$safe_method', '$safe_school_type', '$safe_payment_type', 'pending', 'Excess payment from Final Year student (Both terms fully paid)')");
        }
        // Update the message status to 1 for approved payments
        if ($allInserted) {
          if (!empty($message_id)) {
            $stmtUpdate = $dbh->prepare("UPDATE message SET status = 1 WHERE id = :message_id AND status = 0 LIMIT 1");
            $stmtUpdate->bindParam(':message_id', $message_id);
            $stmtUpdate->execute();
          }
          $dbh->commit();
          unset($_SESSION['id']);
          unset($_SESSION['message_data']);
          flash_alert('Payment approved and Email sent successfully!', 'pay_tuition.php');
          header('Location: pay_tuition.php');
          exit;
        } else {
          $dbh->rollBack();
          flash_alert('Something went wrong. Payment was not approved. Please try again.');
          header('Location: pay_tuition.php');
          exit;
        }
      } catch (Exception $e) {
        $dbh->rollBack();
        flash_alert('Payment was not approved because email could not be sent. Please try again.', 'pay_tuition.php');
        header('Location: pay_tuition.php');
        exit;
      }
    }
  }

  if (isset($_POST['disapprove'])) {
    $studentname = $_POST['stdname'];
    $amount      = $_POST['original_amount'] ?? 0;
    $email = $_POST['email'];
    try {
      $dbh->beginTransaction();

      $mail = new PHPMailer(true);
      // SMTP configuration from .env
      $mail->isSMTP();
      $mail->Host = $_ENV['SMTP_HOST'];
      $mail->SMTPAuth = true;
      $mail->Username = $_ENV['SMTP_NO_REPLY'];
      $mail->Password = $_ENV['SMTP_NO_REPLY_PASSWORD'];
      $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
      $mail->Port = $_ENV['SMTP_PORT'];
      $mail->Timeout = 10;

      $mail->setFrom($_ENV['SMTP_NO_REPLY'], $_ENV['SCHOOL_NAME']);
      $mail->addAddress($email, $studentname);
      $mail->isHTML(true);
      $mail->Subject = $school_name . ' School Fees Payment Disapproval Notification';
      $mail->Body = "
            <html>
            <body>
                <div style='max-width: 600px; margin: auto; font-family: Arial, sans-serif; background-color: #f4f4f4; padding: 20px;'>
                    <h1 style='color: #ffffff; text-align: center; padding: 10px 0; background-color: #FF0000;'>Payment Disapproved</h1>
                    <p>Dear $studentname,</p>
                    <p>We regret to inform you that your payment of NGN $amount has been disapproved.</p>
                    <p>The payment was disapproved due to uncertainity of the payment</p>
                    <p>Kindly wait for two days to confirm if your bank has reversed the transaction made. Then, make the payment again.</p>
                    <p>For more questions and clarifications, please fill the feedback form at the bottom right of the student portal and you will be responded to.</p>
                    <p>Thank you!</p>
                    <hr>
                    <center>
                        <p>$school_name &copy; " . date("Y") . ". All Rights Reserved.</p>
                    </center>
                </div>
            </body>
            </html>";

      $mail->send();

      if (!empty($message_id)) {
        $stmtUpdate = $dbh->prepare("UPDATE message SET status = 2 WHERE id = :message_id AND status = 0 LIMIT 1");
        $stmtUpdate->bindParam(':message_id', $message_id);
        $stmtUpdate->execute();
      }
      $dbh->commit();
      unset($_SESSION['id']);
      unset($_SESSION['message_data']);
      flash_alert('Payment disapproved and Email sent successfully!', 'pay_tuition.php');
      header('Location: pay_tuition.php');
      exit;
    } catch (Exception $e) {
      $dbh->rollBack();
      flash_alert('Payment was not disapproved because the email could not be sent. Please try again.', 'pay_tuition.php');
      header('Location: pay_tuition.php');
      exit;
    }
  }

  if (isset($_POST['unresolved'])) {
    try {
      $dbh->beginTransaction();

      // Update the message status to 2 for unresolved payments
      if (!empty($message_id)) {
        $stmtUpdate = $dbh->prepare("UPDATE message SET status = 3 WHERE id = :message_id AND status = 0 LIMIT 1");
        $stmtUpdate->bindParam(':message_id', $message_id, PDO::PARAM_INT);
        $stmtUpdate->execute();
      }

      $dbh->commit();
      unset($_SESSION['id']);
      unset($_SESSION['message_data']);
      flash_alert('Payment marked as unresolved, and message status updated successfully!', 'pay_tuition.php');
      header('Location: pay_tuition.php');
      exit;
    } catch (Exception $e) {
      $dbh->rollBack();
      flash_alert('Failed to mark payment as unresolved. Please try again.', 'pay_tuition.php');
      header('Location: pay_tuition.php');
      exit;
    }
  }

  if (isset($_POST['unrelated'])) {
    try {
      $dbh->beginTransaction();

      // Update the message status to 2 for unresolved payments
      if (!empty($message_id)) {
        $stmtUpdate = $dbh->prepare("UPDATE message SET status = 5 WHERE id = :message_id AND status = 0 LIMIT 1");
        $stmtUpdate->bindParam(':message_id', $message_id, PDO::PARAM_INT);
        $stmtUpdate->execute();
      }

      $dbh->commit();
      unset($_SESSION['id']);
      unset($_SESSION['message_data']);
      flash_alert('Payment marked as unresolved, and message status updated successfully!', 'pay_tuition.php');
      header('Location: pay_tuition.php');
      exit;
    } catch (Exception $e) {
      $dbh->rollBack();
      flash_alert('Failed to mark payment as unresolved. Please try again.', 'pay_tuition.php');
      header('Location: pay_tuition.php');
      exit;
    }
  }
}
?>




<!DOCTYPE html>
<html>
<?php @include("includes/head.php"); ?>

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

    <!-- Main Sidebar Container -->
    <?php @include("includes/sidebar.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">Shool Fees (Admitted Students)</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="dashboard.php" class="text-primary">Home</a></li>
                    <li class="breadcrumb-item">
                      <rove href="approve.php" class="text-primary">Approve Payment</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> School Fees Payment For Student
                    with Admission No.</h5>
                </div>
                <!-- /.card-header -->
                <!-- form start -->
                <form role="form" method="post" enctype="multipart/form-data">
                  <div class="card-body">
                    <span style="color: brown">
                      <h5>Student's Details</h5>
                    </span>
                    <hr>
                    <div class="row">

                      <div class="form-group col-md-4">
                        <label for="sex">Admission No. | Fullname</label>
                        <select class="form-control" id="fullname" name="fullname" required style="width:100%">
                          <?php
                          $preRegno = htmlspecialchars($messageData['regno'] ?? $studentNo ?? '');
                          $preName  = htmlspecialchars($messageData['fullname'] ?? '');
                          if ($preRegno): ?>
                            <option value="<?php echo $preRegno; ?>" selected>
                              <?php echo $preRegno . ($preName ? ' | ' . $preName : ''); ?>
                            </option>
                          <?php endif; ?>
                        </select>
                        <small class="text-muted">Search by admission no. or name</small>
                      </div>
                      <div class="form-group col-md-4">
                        <label for="age">Student's Fullname</label>
                        <input type="text" class="form-control" id="stdname" name="stdname"
                          value="<?php echo $messageData['fullname']; ?>" required readonly>
                      </div>
                      <div class="form-group col-md-4">
                        <label for="age">Term</label>
                        <input type="text" class="form-control" id="term" name="term"
                          value="<?php echo $messageData['term']; ?>" required>
                      </div>
                      <div class="form-group col-md-4">
                        <label for="sex">Session</label>
                        <input type="text" class="form-control" id="session" name="session"
                          value="<?php echo $messageData['session']; ?>" required>


                      </div>
                      <div class="form-group col-md-4">
                        <label for="age">Class</label>
                        <input type="text" class="form-control" id="class" name="class"
                          value="<?php echo $messageData['class']; ?>" required>

                      </div>

                      <div class="form-group col-md-4">
                        <label for="age">School Type</label>
                        <input type="text" class="form-control" id="school_type" name="school_type"
                          value="<?php echo $messageData['school_type']; ?>" required>

                      </div>
                    </div>
                    <div class="row">
                      <div class="form-group col-md-4">
                        <label for="age">Payment Option</label>
                        <select type="select" class="form-control" id="payment_type" name="payment_type" required>
                          <option value="">-- Select Payment Option --</option>
                          <option value="Half Term">Half Term Payment</option>
                          <option value="Full Term">Full Term Payment</option>
                          <option value="Two Terms">Full Two Term Payment</option>
                          <option value="Full Session">Full Session Payment</option>
                          <option value="Part Payment">Part Payment</option>
                        </select>
                      </div>
                      <div class="form-group col-md-4">
                        <label for="age">Payment ID</label>
                        <input type="text" class="form-control" name="pay_id" id="pay_id" value="<?php
                        function generate_pay_ID($length = 15)
                        {
                          $char = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSQTUVWXYZ';
                          $charlength = strlen($char);
                          $randomString = '';
                          for ($i = 0; $i < $length; $i++) {
                            # code...
                            $randomString .= $char[rand(0, $charlength - 1)];
                          }
                          return $randomString;
                        }
                        $tid = generate_pay_ID();
                        echo isset($pay_id) ? $pay_id : $tid ?>" required readonly>
                      </div>

                      <div class="form-group col-md-4">
                        <label for="age">Payment For</label>
                        <input type="text" class="form-control" id="pay_for" name="pay_for"
                          value="<?php echo $messageData['purpose']; ?>" required>
                      </div>

                      <div class="form-group col-md-4">
                        <label for="age">Payment Method</label>
                        <input type="text" class="form-control" id="method" name="method"
                          value="<?php echo $messageData['method']; ?>" required>
                      </div>



                      <div class="form-group col-md-4">
                        <label for="discount_used">Discount Used?</label>
                        <input type="text" class="form-control" id="discount_used" name="discount_used"
                          value="<?php echo $messageData['discount_used'] ?? 'No'; ?>" readonly>
                      </div>

                      <div class="form-group col-md-4">
                        <label for="discount_percent">Discount Percentage (%)</label>
                        <input type="number" class="form-control" id="discount_percent" name="discount_percent"
                          value="<?php echo $discountPercent ?? 0; ?>" readonly>
                      </div>

                      <div class="form-group col-md-4">
                        <label for="discount_amount">Discount Amount (NGN)</label>
                        <input type="text" class="form-control money-input" id="discount_amount_display"
                          value="<?php echo number_format($discountAmount ?? 0); ?>" required readonly>
                        <input type="hidden" id="discount_amount" name="discount_amount"
                          value="<?php echo $discountAmount ?? 0; ?>">
                      </div>
                      <div class="form-group col-md-4">
                        <label for="original_amount">Original Amount (NGN)</label>
                        <input type="text" class="form-control money-input" id="original_amount_display"
                          value="<?php echo number_format($originalAmount ?? 0); ?>" required>
                        <!-- Hidden input for actual DB value -->
                        <input type="hidden" id="original_amount" name="original_amount"
                          value="<?php echo $originalAmount ?? 0; ?>">
                      </div>

                      <div class="form-group col-md-4">
                        <label for="amount">Amount Paid (NGN)</label>
                        <input type="text" class="form-control money-input" id="amount_display"
                          value="<?php echo number_format($messageData['amount']); ?>" required readonly
                          oninput="updateHiddenAmount(this)">
                        <!-- Hidden input for actual DB value -->
                        <input type="hidden" id="amount" name="amount" value="<?php echo $messageData['amount']; ?>">
                      </div>
                      <div class="form-group col-md-4">
                        <label for="age">Email</label>
                        <input type="email" class="form-control" id="email" name="email"
                          value="<?php echo $messageData['email']; ?>" required>
                      </div>

                      <div class="form-group col-md-4">
                        <label for="total_session">Total Paid This Session (NGN)</label>
                        <input type="text" class="form-control money-input" id="totalsession_display"
                          value="<?php echo number_format($totalPaidSession ?? 0); ?>" required readonly>
                        <input type="hidden" id="total_session" name="total_session"
                          value="<?php echo $totalPaidSession; ?>">
                      </div>

                      <div class="form-group col-md-4">
                        <label for="total_term">Total Paid This Term (NGN)</label>
                        <input type="text" class="form-control money-input" id="totalpaid_display"
                          value="<?php echo number_format($totalPaidTerm ?? 0); ?>" required readonly>
                        <input type="hidden" id="total_term" name="total_term" value="<?php echo $totalPaidTerm; ?>">
                      </div>

                      <script>
                        // Format number with commas
                        function formatNumber(num) {
                          return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                        }

                        // Remove commas
                        function unformatNumber(num) {
                          return num.replace(/,/g, '');
                        }

                        // Handle typing in amount fields
                        document.querySelectorAll('.money-input').forEach(function (input) {
                          input.addEventListener('input', function () {
                            let raw = unformatNumber(this.value);
                            if (!isNaN(raw) && raw !== "") {
                              this.value = formatNumber(raw); // show with commas
                              let hiddenInput = document.getElementById(this.id.replace('_display', ''));
                              hiddenInput.value = raw; // keep raw value for DB
                            }
                          });
                        });
                      </script>

                    </div>

                    <!-- /.card-body -->
                    <div class="card-footer">
                      <center>
                        <button type="submit" name="unrelated" id="unrelated" class="btn btn-warning mb-3"><i
                            class="fas fa-exclamation-circle"></i> Mark as Unrelated</button>
                        <button type="submit" name="submit" id="submit" class="btn btn-success mb-3"
                          onclick="<?php if ($demote == 1) { ?> return confirm('This student is marked as DEMOTED. Are you sure you want to approve payment?'); <?php } ?>">
                          <i class="fas fa-check-circle"></i> Approve
                        </button>
                        <button type="submit" name="disapprove" id="disapprove" class="btn btn-danger mb-3"><i
                            class="fas fa-times-circle"></i> Disapprove</button>
                        <button type="submit" name="unresolved" id="unresolved" class="btn btn-info mb-3"><i
                            class="fas fa-question-circle"></i> Mark as Unresolved</button>
                      </center>
                    </div>
                </form>
              </div>
              <!-- /.card -->
            </div>
            <!-- /.col -->
          </div>
          <!-- /.row -->
        </div>
        <!-- /.container-fluid -->
      </section>
      <!-- /.content -->
    </div>
    <!-- /.content-wrapper -->
    <?php @include("includes/footer.php"); ?>

  </div>


  <!-- ./wrapper -->
  <?php @include("includes/foot.php"); ?>
  <script src="dist/js/jquery-3.7.1.min.js"></script>
  <script src="dist/js/select2.min.js"></script>

  <script>
    $(document).ready(function () {
      // Initialize Select2 with AJAX search — admitted students only
      $('#fullname').select2({
        placeholder: 'Search by admission no. or name',
        allowClear: true,
        minimumInputLength: 1,
        ajax: {
          url: 'fetch_student_search1.php',
          dataType: 'json',
          delay: 300,
          data: function (params) {
            return { q: params.term };
          },
          processResults: function (data) {
            return { results: data.results };
          },
          cache: true
        }
      });

      // When a different student is selected — update fields
      $('#fullname').on('select2:select', function (e) {
        var data = e.params.data;
        $('#stdname').val(data.studentName || '');
        $('#class').val(data.class || '');
        $('#school_type').val(data.stream || '');
        // email stays as-is unless the new student has one
        if (data.email) $('#email').val(data.email);
      });

      // Clear fields only when selection is explicitly removed
      $('#fullname').on('select2:clear', function () {
        $('#stdname').val('');
        $('#class').val('');
        $('#school_type').val('');
      });

      // Other Select2 inits
      $('#payment_type').select2();
    });

    function updateHiddenAmount(displayInput) {
      let cleanValue = displayInput.value.replace(/[^0-9.]/g, '');
      document.getElementById('amount').value = cleanValue;
      console.log("Hidden value is now: " + document.getElementById('amount').value);
    }
  </script>
</body>

</html>
