<?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';
// 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'];

// Fetch next (upcoming) session and its first term
$nextSessionName     = null;
$nextSessionTermName = null;

$nsStmt = $con->prepare(
    "SELECT session_name FROM school_sessions
     WHERE start_date > CURDATE()
     ORDER BY start_date ASC LIMIT 1"
);
$nsStmt->execute();
$nsRow = $nsStmt->get_result()->fetch_assoc();
$nsStmt->close();
if ($nsRow) {
    $nextSessionName = $nsRow['session_name'];
    $ntStmt = $con->prepare(
        "SELECT t.term_name FROM school_terms t
         JOIN school_sessions s ON t.session_id = s.id
         WHERE s.session_name = ?
         ORDER BY t.start_date ASC LIMIT 1"
    );
    $ntStmt->bind_param("s", $nextSessionName);
    $ntStmt->execute();
    $ntRow = $ntStmt->get_result()->fetch_assoc();
    $ntStmt->close();
    if ($ntRow) {
        $nextSessionTermName = $ntRow['term_name'];
    }
}

// Fetch next term within the current session (upcoming, not yet started)
$nextCurrentTermName = null;
if ($currentSessionId) {
    $nctStmt = $con->prepare(
        "SELECT term_name FROM school_terms
         WHERE session_id = ? AND start_date > CURDATE()
         ORDER BY start_date ASC LIMIT 1"
    );
    $nctStmt->bind_param("i", $currentSessionId);
    $nctStmt->execute();
    $nctRow = $nctStmt->get_result()->fetch_assoc();
    $nctStmt->close();
    if ($nctRow) {
        $nextCurrentTermName = $nctRow['term_name'];
    }
}

include('includes/flash.php');

// Include PHPMailer and QR code libraries
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use Dotenv\Dotenv;

require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';
require 'phpqrcode/qrlib.php'; // Ensure you have the PHP QR Code library


// 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'];
$prefix = $_ENV['Admission_prefix'];
$site = $_ENV['BASE_URL'];
$logo = $_ENV['WEBSITE_LOGO'];
$whatsappLink = $_ENV['WHATSAPP_LINK'];

$message_id = $_GET['id'];
$messageData = $_SESSION['message_data'];
$cls = $messageData['class'];
$st = $messageData['school_type'];
$std = 'New';
$amountpaid = $messageData['amount'] ?? 0;

$admission_no = $messageData['fullname'];
$currentSession = $messageData['session'];
$currentTerm = $messageData['term'];
$payfor = $messageData['purpose'];

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

// Fetch academic_session and admission_term from the student's record
$studentAcademicSession = $currentSession;
$studentAdmissionTerm   = $currentTerm;

// Use regno from messageData, or fall back to manually entered value from POST
$regNo = $messageData['regno'] ?? $_POST['fullname'] ?? '';
if (!empty($regNo)) {
  $stStmt = $con->prepare("SELECT academic_session, admission_term FROM students WHERE studentRegNo = ? LIMIT 1");
  if ($stStmt) {
    $stStmt->bind_param("s", $regNo);
    $stStmt->execute();
    $stRow = $stStmt->get_result()->fetch_assoc();
    $stStmt->close();
    if ($stRow) {
      $studentAcademicSession = $stRow['academic_session'] ?: $currentSession;
      $studentAdmissionTerm   = $stRow['admission_term']   ?: $currentTerm;
    }
  }
}

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

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


// Get total fees — check fee_records for this session/term first, fall back to fees catalogue
$paymentcheck = 0.0;

$feeStmt = $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 ($feeStmt) {
  $feeStmt->bind_param("ssss", $cls, $st, $studentAcademicSession, $studentAdmissionTerm);
  $feeStmt->execute();
  $feeRow = $feeStmt->get_result()->fetch_assoc();
  $feeStmt->close();
  if ($feeRow && (float) $feeRow['amount'] > 0) {
    $paymentcheck = (float) $feeRow['amount'];
  }
}

if ($paymentcheck == 0.0) {
  $feeStmt2 = $con->prepare(
    "SELECT amount FROM fees
     WHERE class = ? AND stream = ? AND student_type = 'New'
       AND name = 'School Fees (New Student)'
     LIMIT 1"
  );
  if ($feeStmt2) {
    $feeStmt2->bind_param("ss", $cls, $st);
    $feeStmt2->execute();
    $feeRow2 = $feeStmt2->get_result()->fetch_assoc();
    $feeStmt2->close();
    $paymentcheck = (float) ($feeRow2['amount'] ?? 0.0);
  }
}



function smartRoundToThousand($value)
{
  $remainder = $value % 1000;

  if ($remainder > 100) {
    return ceil($value / 1000) * 1000;
  } else {
    return floor($value / 1000) * 1000;
  }
}

// check if acceptance fee is paid
$acceptanceRatio = 30000 / 190000; // Acceptance fee to total school fees ratio
$acceptanceFee = smartRoundToThousand($paymentcheck * $acceptanceRatio); // Calculate acceptance fee based on total school fees

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

  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 unrelated, and message status updated successfully!', 'pay.php');
      header('Location: pay.php');
      exit;
    } catch (Exception $e) {
      $dbh->rollBack();
      flash_alert('Failed to mark payment as unrelated. Please try again.', 'pay.php');
      header('Location: pay.php');
      exit;
    }
  }

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

    $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['amount'];
    $payment_for = $_POST['pay_for'];
    $studentname = $_POST['stdname'];
    $email = $_POST['email'];
    $sql = "SELECT * FROM students WHERE studentRegNo =?";
    $stmt = $dbh->prepare($sql);
    $stmt->execute([$adno]);


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

      // check student and email
      $fecthemail = $stmt->fetch(PDO::FETCH_ASSOC);
      $id = $fecthemail['id'];
    }
    try {
      // Update the message status to 'disapproved' (set status = 2, assuming 2 indicates disapproval)
      $stmtDisapprove = $dbh->prepare("UPDATE message SET status = 2 WHERE id = :message_id AND status = 0 LIMIT 1");
      $stmtDisapprove->bindParam(':message_id', $message_id);
      $stmtDisapprove->execute();

      // Notify user via email about disapproval
      $mail = new PHPMailer(true);
      try {
        // SMTP configuration
        $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: #f44336;'>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();
        echo "<script>
  alert('Payment disapproved and Email sent successfully!');
  document.location.href = 'pay.php';
</script>";
      } catch (Exception $e) {
        echo "<script>
  alert('Payment disapproved, but email could not be sent. Please try again.');
  document.location.href = 'pay.php';
</script>";
      }
    } catch (Exception $e) {
      echo "<script>
  alert('Something went wrong. Payment disapproval failed. Please try again.');
</script>";
    }
  }
  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']);
      echo "<script>
  alert('Payment marked as unresolved, and message status updated successfully!');
  document.location.href = 'pay.php';
</script>";
    } catch (Exception $e) {
      $dbh->rollBack();
      echo "<script>
  alert('Failed to mark payment as unresolved. Please try again.');
  document.location.href = 'pay.php';
</script>";
    }
  }





  if (isset($_POST['submit'])) {
    $regno = $_POST['fullname'];
    $adno = $_POST['fullname'];
    $term = $_POST['term'] ?? $currentTermName;
    $session = $_POST['session'] ?? $currentSessionName;
    $class = $_POST['class'];
    $school_type = $_POST['school_type'];
    $payment_type = $_POST['payment_type'];
    $pay_id = $_POST['pay_id'];
    $amount = $_POST['amount'];
    $payment_for = $_POST['pay_for'];
    $studentname = $_POST['stdname'];
    $method = $_POST['method'];
    $email = $_POST['email'];
    $section = $_POST['arm'];
    $uniformDate = $_POST['uniform'] ?? date('Y-m-d');
    $uniformTime = $_POST['time'] ?? date('H:i:s');
    $uniformDate1 = $_POST['uniform1'] ?? date('Y-m-d');
    $uniformTime1 = $_POST['time1'] ?? date('H:i:s');

    // Format the primary date
    if (!empty($uniformDate)) {
      $uniformDateFormatted = date('jS \o\f F Y', strtotime($uniformDate)); // e.g., 10th of July 2025
    } else {
      $uniformDateFormatted = '';
    }

    // Format the primary time
    if (!empty($uniformTime)) {
      $uniformTimeFormatted = date('g:i A', strtotime($uniformTime)); // e.g., 10:00 AM
    } else {
      $uniformTimeFormatted = '';
    }

    // Format the alternate date
    if (!empty($uniformDate1)) {
      $uniformDate1Formatted = date('jS \o\f F Y', strtotime($uniformDate1));
    } else {
      $uniformDate1Formatted = '';
    }

    // Format the alternate time
    if (!empty($uniformTime1)) {
      $uniformTime1Formatted = date('g:i A', strtotime($uniformTime1));
    } else {
      $uniformTime1Formatted = '';
    }

    $status = 1;


    // Convert session format to short version (e.g., "2024/2025" -> "24/25")
    $sessionParts = explode("/", $session);
    $shortSession = substr($sessionParts[0], -2) . "/" . substr($sessionParts[1], -2);

    // Determine if the student is JSS 1
    $isJss1 = (trim($class) === 'JSS 1' || trim($class) === 'JSS1');

    // Define the session prefix
    $sessionPrefix = "$prefix/$shortSession/";

    // Query for the highest existing number in the current session
    if ($isJss1) {
      $stmt = $dbh->prepare("SELECT studentno FROM students 
        WHERE studentno LIKE ? AND class IN ('JSS 1', 'JSS1') 
        ORDER BY CAST(SUBSTRING_INDEX(studentno, '/', -1) AS UNSIGNED) DESC 
        LIMIT 1");
      $stmt->execute(["$sessionPrefix%"]);
    } else {
      $stmt = $dbh->prepare("SELECT studentno FROM students 
        WHERE studentno LIKE ? AND class NOT IN ('JSS 1', 'JSS1') 
        ORDER BY CAST(SUBSTRING_INDEX(studentno, '/', -1) AS UNSIGNED) DESC 
        LIMIT 1");
      $stmt->execute(["$sessionPrefix%"]);
    }

    $lastRow = $stmt->fetch(PDO::FETCH_ASSOC);

    // Determine next number
    if ($lastRow) {
      preg_match('/(\d+)$/', $lastRow['studentno'], $matches);
      $lastNumber = isset($matches[1]) ? intval($matches[1]) : 0;

      if ($isJss1) {
        if ($lastNumber >= 150) {
          echo "<script>
                    alert('JSS 1 admission is full. Cannot assign more than 150 students.');
                    document.location.href = 'pay.php';
                </script>";
          exit;
        }
        $newNumber = $lastNumber + 1;
      } else {
        $newNumber = max($lastNumber + 1, 151);
      }
    } else {
      $newNumber = $isJss1 ? 1 : 151;
    }

    // Loop until a unique number is found
    do {
      $new_number = str_pad($newNumber, 3, '0', STR_PAD_LEFT);
      $new_admission_number = "$prefix/$shortSession/$new_number";

      $dupCheck = $dbh->prepare("SELECT COUNT(*) FROM students WHERE studentno = ?");
      $dupCheck->execute([$new_admission_number]);

      if ($dupCheck->fetchColumn() > 0) {
        $newNumber++;
        continue; // Try next number
      }
      break; // Found unique number
    } while (true);



    // Default values
    $hashedPassword = password_hash($new_admission_number, PASSWORD_BCRYPT);

    // Fetch student email
    $sql = "SELECT * FROM students WHERE studentRegNo = ?";
    $stmt = $dbh->prepare($sql);
    $stmt->execute([$adno]);

    if ($stmt->rowCount() > 0) {
      $studentData = $stmt->fetch(PDO::FETCH_ASSOC);
      $id = $studentData['id'];

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





      // Format posting date
      $formattedDate = date('M j, Y', strtotime($studentData['postingDate']));
      // Generate QR code with student details
      $qrText = "This admission letter is valid and authorized by $school_name to
      Admission No: $new_admission_number
      Student Name: {$studentData['studentName']}
      Class: $class
      Session Admitted: $session
      Thanks for verifying this admission letter.";
      $qrFilePath = 'temp_qr.png';
      QRcode::png($qrText, $qrFilePath, QR_ECLEVEL_L, 4); // Generate QR code

      // Define the HTML content for the PDF
      $htmlContent = "
      <!DOCTYPE html>
      <html lang='en'>

      <head>
        <meta charset='UTF-8'>
        <title>Admission Letter</title>
        <style>
          body {
            font-family: Times New Roman, serif;
            margin: 0;
            padding: 0;
          }

          .container {
            width: 80%;
            margin: auto;
            border: 2px dotted #000;
            padding: 20px;
            line-height: 1.6;
          }

          .header {
            text-align: center;
            padding: 0;
            margin: 0;
          }

          .header img {
            height: 100px;
            margin: 0;
            padding: 0;
          }

          .header h1 {
            font-size: 35px;
            font-weight: bold;
            margin: 0;
            padding: 0;
          }

          .header b {
            font-size: 10px;
            margin: 0;
            padding: 0;
          }

          .title {
            text-align: center;
            font-size: 18px;
            font-weight: bold;
            margin: 20px 0;
          }

          .details {


            width: 100%;

          }

          .child {
            float: left;
            width: 50%;

          }

          .left {
            margin-left: 100%;

            font-size: 14px;
            font-weight: bold;
          }

          .right {
            margin-left: 50%;

            font-size: 14px;
            font-weight: bold;
          }

          .content {
            text-align: justify;
          }

          .content p {
            font-size: 15px;
          }

          .signature {
            margin-top: 50px;
            text-align: center;
            font-size: 14px;
          }

          .signature img {
            height: 100px;
            margin-top: 10px;
          }

          .signature p {
            margin: 0;
            text-align: center;
          }

          .congratulations {
            text-align: center;
            margin-top: 30px;
            /* Optional margin for spacing */
          }

          .congratulations p {
            font-family: 'brushscriptmt';
            font-size: 40px;
            font-weight: bold;
            margin: 0;
          }

          /* Prevent automatic page break */
          @page {
            margin: 10mm;
          }
        </style>
      </head>

      <body>

        <div class='container'>
          <!-- Header with School Logo and Details -->
          <div class='header'>
            <h1>" . strtoupper($school_name) . "</h1>
            <b><i>$school_address</i></b><br>
            <img src=$logo alt='logo' height='120'><br>
            <b style='font-size:9;'>(Government Approved)</b>
          </div>
          <br><br>

          <!-- Details Section -->
          <div class='details'>
            <div class='child'>
              <div class='left'>Admission No: $new_admission_number</div>
            </div>
            <div class='child'>
              <div class='right'>Date: $formattedDate</div>
            </div>
          </div>
          <!-- Admission Letter Title -->
          <div class='title'>
            ADMISSION LETTER
          </div>

          <!-- Main Content of the Letter -->
          <div class='content'>
            <p>Dear <strong>{$studentData['studentName']}</strong>,</p>
            <p>
              We are pleased to inform you that you have been offered a provisional admission into <strong>{$studentData['class']} $section</strong> for the year {$studentData['academic_session']} academic session.
            </p>
            <p>
              Be informed that your full admission is subject to the full payment of the school fees,
              submission of one recent passport photograph and medical reports.
            </p>

            <p>
              For official documentation, this admission letter is subject to verification by scanning the barcode below.
            </p>
          </div>

          <!-- Congratulations Section -->
          <div class='congratulations'>
            <p>
              Congratulations<br>
              <img src='{$qrFilePath}' alt='QR Code' width='105' height='105'><!-- QR Code on top of the signature -->
            </p>
          </div>

          <!-- Signature Section with QR Code -->
          <div class='signature'>
            <b>Signed,</b><br>
            <b>School Management</b>
          </div>
        </div>

      </body>

      </html>
      ";

      // Generate the PDF using mPDF
      include("vendor/autoload.php");
      $mpdf = new \Mpdf\Mpdf(['format' => 'A4', 'default_font_size' => 12, 'default_font' => 'Times New Roman']);
      $mpdf->WriteHTML($htmlContent);

      // Set PDF metadata
      $mpdf->SetTitle("Admission Letter - {$studentData['studentName']}");
      $mpdf->SetAuthor($school_name);

      // Disable page breaks to keep content on one page
      $mpdf->SetWatermarkImage($logo, 0.1); // 0.1 for light opacity, 'F' for fit to page
      $mpdf->showWatermarkImage = true;
      $pdfContent = $mpdf->Output('', 'S'); // Get the PDF as a string for email attachment


      // Clean up QR code image file
      unlink($qrFilePath);


      // Insert payment record
      $query = $dbh->prepare("INSERT INTO payment (studentno, studentName, Term, session, class, school_type, payment_type, pay_id, amount, pay_for, student_id,method,section)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
      $query->execute([$adno, $studentname, $term, $session, $class, $school_type, $payment_type, $pay_id, $amount, $payment_for, $id, $method, $section]);

      // Update message status
      // Update message status using the passed id
      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();
      }
      $updatesec = "UPDATE students SET section = ? WHERE studentRegNo = ?";
      $updateStmt1 = $dbh->prepare($updatesec);
      $updateStmt1->execute([$section, $adno]);


      // Fetch the current term fees
      $currentTermFeesQuery = "SELECT amount FROM fees
      WHERE class = ?
      AND stream = ?
      AND student_type = 'New'
      AND name = ?
      LIMIT 1";

      $currentTermFeesStmt = $con->prepare($currentTermFeesQuery);
      $currentTermFeesStmt->bind_param("sss", $class, $school_type, $payment_for);
      $currentTermFeesStmt->execute();
      $currentTermFeesResult = $currentTermFeesStmt->get_result();
      $currentTermFeesRow = $currentTermFeesResult->fetch_assoc();
      $currentTermTotalFees = $currentTermFeesRow['amount'] ?? 0;

      // Fetch total amount paid by the student for the current term
      $totalPaidQuery = "SELECT SUM(amount) as total_paid FROM payment
      WHERE student_id = ?
      AND class = ?
      AND pay_for = ?
      AND school_type = ?
      AND session = ?
      AND Term = ?";

      $totalPaidStmt = $con->prepare($totalPaidQuery);
      $totalPaidStmt->bind_param("isssss", $id, $class, $payment_for, $school_type, $session, $term);
      $totalPaidStmt->execute();
      $totalPaidResult = $totalPaidStmt->get_result();
      $totalPaidRow = $totalPaidResult->fetch_assoc();
      $totalPaidAmount = $totalPaidRow['total_paid'] ?? 0;

      // Check if the student has paid the full amount
      if ($totalPaidAmount >= $currentTermTotalFees) {
        // Update studentno with the new admission number in students table
        $updateQuery = "UPDATE students
      SET studentno = ?,
      status = ?,
      section = ?,
      password = ?,
      adclass = ?,
      admission_term = ?,
      postingDate = CURDATE()
      WHERE studentRegNo = ?";

        $updateStmt = $dbh->prepare($updateQuery);
        $updateStmt->execute([$new_admission_number, $status, $section, $hashedPassword, $class, $term, $adno]);

        // Attempt to send email before inserting payment
        $mail = new PHPMailer(true);
        try {
          $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->addBCC($_ENV['ADMISSION_EMAIL'], $school_name . ' Admissions Number Generated');
          $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>Congratulations!!!</p>
          <p>We are pleased to inform you that your payment of NGN $amount has been confirmed and
            Admission Number issued successfully. </p>
          <hr>
          <p><strong>Admission Number:</strong> $new_admission_number</p>
          <p><strong>Password:</strong> $new_admission_number</p>
          <p>Click <a href='$site'>here</a> to log in.</p>


          <p>Please note that your Admission Number will <strong>now</strong> be required to log into your student portal</p>
          <hr>
          <h5>Admission Details</h5>
          <hr>
          <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>Your admission letter has been attached below in this mail.<br>
            Please log into your student portal to download your receipt.</p>
          <p style='color:red;'>It is essential that you bring a printed copy of the school receipt and admission letter for your enrolment
            process, documentation and uniform collection upon resumption.</p>

          <p> kindly click <a href='$whatsappLink'>here</a> to join $school_name Parents WhatsApp Community to receive updates from the school.</p>

          <p>Thank you!</p>
          <hr>
          <p>If you have any questions or need further assistance, please feel free to reach out to us. Thank you!</p>
          <hr>
          <center>
            <p>$school_name &copy; " . date("Y") . ". All Rights Reserved.</p>
          </center>
          <hr>
        </div>
      </body>

      </html>";
          // Attach PDF
          $boardinglist = ('ACI_BOARDING_LIST.pdf');
          $mail->addStringAttachment($pdfContent, 'Admission_Letter.pdf');
          if ($school_type == 'Boarding' || $school_type == 'boarding' || $school_type == 'BOARDING') {
            $mail->addAttachment($boardinglist, $prefix . '_BOARDING_LIST.pdf');
          }

          $mail->send();
          echo "<script>
        alert('Payment approved, Admission Number updated successfully');
        document.location.href = 'pay.php';
      </script>";
        } catch (Exception $e) {
          echo "<script>
        alert('Email could not be sent. Payment approved, Admission Number updated successfully.');
      </script>";
        }
      } else {
        $mail = new PHPMailer(true);
        try {
          $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>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>";
          // Attach PDF
          $mail->send();
          echo "<script>
        alert('Payment approved, Admission Number not updated.');
        document.location.href = 'pay.php';
      </script>";
        } catch (Exception $e) {
          echo "<script>
        alert('Email could not be sent. Payment approved, Admission Number not updated..');
      </script>";
        }
      }


      unset($_SESSION['id']);
      unset($_SESSION['message_data']);

    } else {
      echo "<script>
        alert('Student not found. Please try again.');
      </script>";
    }
  }
}
?>

<!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 (Non 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
                    without 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">Registration No. | FullName</label>
                        <select class="form-control" id="fullname" name="fullname" required style="width:100%">
                          <?php
                          $preRegno = htmlspecialchars($messageData['regno'] ?? '');
                          $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 registration 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>
                        <select name="term" id="term" class="form-control" required>
                          <?php
                          $termResult = $con->query("SELECT DISTINCT id, term_name FROM school_terms ORDER BY term_name  ASC");
                          while ($row = $termResult->fetch_assoc()) {
                            $selected = ($messageData['term'] ?? '') == $row['term_name'] ? 'selected' : '';
                            echo "<option value='{$row['term_name']}' $selected>{$row['term_name']}</option>";
                          }
                          ?>
                          <option value="Fourth Term">Fourth Term</option>
                        </select>
                      </div>
                      <div class="form-group col-md-4">
                        <label for="sex">Session</label>
                        <!-- option for session using preselect -->
                        <select name="session" id="session" class="form-control" required>
                          <option value="">-- Select Session --</option>

                          <?php
                          $sessionResult = $con->query("SELECT DISTINCT id, session_name FROM school_sessions ORDER BY session_name DESC");
                          while ($row = $sessionResult->fetch_assoc()) {
                            $selected = ($messageData['session'] ?? '') == $row['session_name'] ? 'selected' : '';
                            echo "<option value='{$row['session_name']}' $selected>{$row['session_name']}</option>";
                          }
                          ?>
                        </select>

                      </div>


                      <div class="form-group col-md-4">
                        <label for="class">Class</label>
                        <input type="text" class="form-control" id="class" name="class"
                          value="<?php echo htmlspecialchars($messageData['class']); ?>" required readonly>
                      </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 readonly>

                      </div>
                    </div>
                    <div class="row">
                      <div class="form-group col-md-4">
                        <label for="age">Payment Type</label>
                        <select type="select" class="form-control" id="payment_type" name="payment_type" required>
                          <option value=""></option>
                          <option value="Acceptance Fees Payment">Acceptance Fees Payment</option>
                          <option value="Balance after acceptance">Balance after acceptance</option>
                          <option value="Full Payment">Full 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="amount_display">Amount Paid (NGN)</label>
                        <!-- Visible, formatted for user -->
                        <input type="text" class="form-control" id="amount_display"
                          value="<?php echo number_format($messageData['amount']); ?>"
                          oninput="updateHiddenAmount(this)">

                        <!-- Hidden, real value for DB -->
                        <input type="hidden" id="amount" name="amount" value="<?php echo $messageData['amount']; ?>">
                      </div>

                      <?php 
                      // Calculate total including current payment
                      $totalIncludingCurrent = $totalPaidTerm + $amountpaid;
                      if ($totalIncludingCurrent >= $paymentcheck): 
                      ?>
                      <div class="form-group col-md-4">
                        <label for="arm">Class Arm to be Admitted to</label>
                        <select name="arm" id="arm" class="form-control" required>
                          <option value="">Select Arm</option>
                        </select>
                      </div>
                      <?php endif; ?>
                      <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>
                      <?php
                      // Show uniform fields if student is admitted into a future session/term
                      $showUniformFields = false;
                      
                      // Parse sessions for comparison (e.g., "2026/2027" vs "2025/2026")
                      $studentSessionYear = null;
                      $currentSessionYear = null;
                      
                      if (preg_match('/(\d{4})\/(\d{4})/', $studentAcademicSession, $matches)) {
                        $studentSessionYear = (int)$matches[1];
                      }
                      if (preg_match('/(\d{4})\/(\d{4})/', $currentSessionName, $matches)) {
                        $currentSessionYear = (int)$matches[1];
                      }
                      
                      if ($studentSessionYear && $currentSessionYear) {
                        if ($studentSessionYear > $currentSessionYear) {
                          // Future session - always show
                          $showUniformFields = true;
                        } elseif ($studentSessionYear == $currentSessionYear) {
                          // Same session - check if admission term is in the future
                          if (!empty($studentAdmissionTerm)) {
                            // Query to check if student's admission term start date is in the future
                            $termCheckStmt = $con->prepare(
                              "SELECT COUNT(*) as is_future FROM school_terms t
                               JOIN school_sessions s ON t.session_id = s.id
                               WHERE s.session_name = ? AND t.term_name = ? AND t.start_date > CURDATE()"
                            );
                            if ($termCheckStmt) {
                              $termCheckStmt->bind_param("ss", $studentAcademicSession, $studentAdmissionTerm);
                              $termCheckStmt->execute();
                              $termCheckResult = $termCheckStmt->get_result()->fetch_assoc();
                              $termCheckStmt->close();
                              if ($termCheckResult && $termCheckResult['is_future'] > 0) {
                                $showUniformFields = true;
                              }
                            }
                          }
                        }
                      }
                      
                      if ($showUniformFields): ?>
                      <?php if ($totalIncludingCurrent == $acceptanceFee): ?>
                      <div class="form-group col-md-4">
                          <label for="age">Uniform Measurement Date</label>
                          <input type="date" class="form-control" id="uniform1" name="uniform1" required>
                        </div>
                        <div class="form-group col-md-4">
                          <label for="age">Uniform Measurement Time</label>
                          <input type="time" class="form-control" id="time1" name="time1" required>
                        </div>
                      <?php elseif ($totalIncludingCurrent > $acceptanceFee): ?>
                      <div class="form-group col-md-4">
                          <label for="age">Uniform Collection Date</label>
                          <input type="date" class="form-control" id="uniform" name="uniform" required>
                        </div>
                        <div class="form-group col-md-4">
                          <label for="age">Uniform Collection Time</label>
                          <input type="time" class="form-control" id="time" name="time" required>
                        </div>
                      <?php endif; ?>
                      <?php endif; ?>
                      <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="totalsession_display_term"
                          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"> <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>
    $(document).ready(function () {
      // Student search: Select2 with AJAX — pre-admission students by studentRegNo
      $('#fullname').select2({
        placeholder: 'Search by registration no. or name',
        allowClear: true,
        minimumInputLength: 1,
        ajax: {
          url: 'fetch_student_search.php',
          dataType: 'json',
          delay: 300,
          data: function (params) {
            return { q: params.term };
          },
          processResults: function (data) {
            return { results: data.results };
          },
          cache: true
        }
      });

      // Update fields only when a different student is selected
      $('#fullname').on('select2:select', function (e) {
        var data = e.params.data;
        $('#stdname').val(data.studentName || '');
        $('#class').val(data.class || '');
        $('#school_type').val(data.stream || '');
        if (data.email) $('#email').val(data.email);

        // Fetch totals using academic_session and admission_term
        var acSession = data.academic_session || '';
        var adTerm    = data.admission_term || '';
        if (acSession) {
          $.ajax({
            url: 'fetch_student_totals.php',
            type: 'GET',
            data: { regno: data.id, session: acSession, term: adTerm },
            dataType: 'json',
            success: function (totals) {
              var sessionTotal = totals.total_session || 0;
              var termTotal    = totals.total_term || 0;
              $('#totalsession_display').val(sessionTotal.toLocaleString());
              $('#total_session').val(sessionTotal);
              $('#totalsession_display_term').val(termTotal.toLocaleString());
              $('#total_term').val(termTotal);
            }
          });
        }
      });

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

      $('#arm').select2();
      $('#payment_type').select2();
      $('#session').select2();
      $('#term').select2();
    });
  </script>
  <script>
    $(document).ready(function () {
      function fetchArms(className) {
        if (className.trim() !== '') {
          $.ajax({
            url: 'fetch_arm.php', // PHP script to fetch class arms
            type: 'POST',
            data: {
              class: className
            },
            success: function (response) {
              $('#arm').html(response); // Populate the arms dropdown
            }
          });
        } else {
          $('#arm').html('<option value="">Select Arm</option>'); // Reset dropdown
        }
      }

      // Detect pre-filled value and fetch arms on page load
      var preFilledClass = $('#class').val().trim();
      if (preFilledClass !== '') {
        fetchArms(preFilledClass);
      }

      // Detect changes to the class input (both user input and programmatic changes)
      let lastValue = preFilledClass;
      setInterval(function () {
        var currentValue = $('#class').val().trim();
        if (currentValue !== lastValue) {
          lastValue = currentValue;
          fetchArms(currentValue);
        }
      }, 500); // Check every 500ms for changes
    });
    function updateHiddenAmount(displayInput) {
      // 1. Remove everything except numbers (and one decimal point if needed)
      // This turns "1,500.00" into "1500.00"
      let cleanValue = displayInput.value.replace(/[^0-9.]/g, '');

      // 2. Update the hidden field with the raw number
      document.getElementById('amount').value = cleanValue;

      // 3. Optional: Re-format the display field (so user sees commas as they type)
      // Note: To prevent cursor jumping, we only format on "blur" usually, 
      // but here is a simple way to keep the hidden field in sync:
      console.log("Hidden value is now: " + document.getElementById('amount').value);
    }
  </script>

</body>

</html>