<?php
session_name('small_admin_session');
if (!is_dir(dirname(__DIR__) . '/session_data/small')) {
    mkdir(dirname(__DIR__) . '/session_data/small', 0700, true);
}
session_save_path(dirname(__DIR__) . '/session_data/small');
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');
require_once 'includes/wallet_helpers.php';

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_once 'vendor/autoload.php';

$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();

if (empty($_SESSION['sid'])) {
    header('location:logoutsmall.php');
    exit;
}

$msg = "";
$student_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// -----------------------------------------------------------------------
// No ?id= ” show student search form
// -----------------------------------------------------------------------
if ($student_id === 0) {
    // Handle search POST
    $search_results = [];
    $search_query = '';
    if (isset($_POST['search_student'])) {
        $search_query = trim($_POST['search_query'] ?? '');
        if (!empty($search_query)) {
            $sq = "%" . $search_query . "%";
            $ss = $con->prepare(
                "SELECT s.id, s.studentno, s.studentName, s.class, s.section, s.stream, w.balance
                 FROM students s INNER JOIN wallets w ON s.id = w.student_id
                 WHERE s.studentName LIKE ? OR s.studentno LIKE ?
                 ORDER BY s.studentName ASC LIMIT 30"
            );
            $ss->bind_param("ss", $sq, $sq);
            $ss->execute();
            $search_results = $ss->get_result()->fetch_all(MYSQLI_ASSOC);
            $ss->close();
        }
    }
    ?>
    <!DOCTYPE html>
    <html lang="en">

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

        <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
        <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
        <style>
            .search-wrapper {
                max-width: 860px;
                margin: 0 auto;
                padding: 0 0 40px;
            }

            .search-hero {
                background: linear-gradient(135deg, var(--primary), var(--dark));
                border-radius: 20px;
                padding: 28px 32px;
                position: relative;
                overflow: hidden;
                box-shadow: 0 20px 60px linear-gradient(135deg, var(--primary), var(--dark));
                margin-bottom: 24px;
            }

            .search-hero::before {
                content: '';
                position: absolute;
                top: -60px;
                right: -60px;
                width: 220px;
                height: 220px;
                background: linear-gradient(135deg, var(--primary), var(--dark));
                border-radius: 50%;
            }

            .search-hero-title {
                font-size: 1.25rem;
                font-weight: 800;
                color: #f8fafc;
                margin: 0 0 4px;
            }

            .search-hero-sub {
                font-size: .8rem;
                color: #94a3b8;
                margin: 0;
            }

            .search-hero-icon {
                width: 48px;
                height: 48px;
                background: linear-gradient(135deg, var(--primary), var(--dark));
                border-radius: 14px;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 1.2rem;
                color: #fff;
                flex-shrink: 0;
                box-shadow: 0 8px 20px linear-gradient(135deg, var(--primary), var(--dark));
            }

            .search-card {
                background: #fff;
                border-radius: 20px;
                box-shadow: 0 4px 30px linear-gradient(135deg, var(--primary), var(--dark));
                border: 1px solid #e8ecf4;
                overflow: hidden;
            }

            .search-card-header {
                padding: 20px 28px;
                border-bottom: 1px solid #f1f5f9;
                display: flex;
                align-items: center;
                gap: 10px;
            }

            .search-card-header-icon {
                width: 36px;
                height: 36px;
                background: linear-gradient(135deg, var(--primary), var(--dark));
                border-radius: 10px;
                display: flex;
                align-items: center;
                justify-content: center;
                color: #fff;
                font-size: .85rem;
            }

            .search-card-header h5 {
                margin: 0;
                font-size: .95rem;
                font-weight: 700;
                color: #0f172a;
            }

            .search-card-body {
                padding: 28px;
            }

            .search-input-wrap {
                position: relative;
            }

            .search-input-icon {
                position: absolute;
                left: 16px;
                top: 50%;
                transform: translateY(-50%);
                color: #94a3b8;
                font-size: .9rem;
                pointer-events: none;
            }

            .search-input {
                width: 100%;
                height: 50px;
                border: 1.5px solid #e2e8f0;
                border-radius: 14px;
                padding: 0 140px 0 44px;
                font-size: .9rem;
                color: #0f172a;
                background: #f8fafc;
                outline: none;
                transition: border-color .2s, box-shadow .2s;
            }

            .search-input:focus {
                border-color: #6366f1;
                box-shadow: 0 0 0 4px linear-gradient(135deg, var(--primary), var(--dark));
                background: #fff;
            }

            .search-btn {
                position: absolute;
                right: 6px;
                top: 50%;
                transform: translateY(-50%);
                height: 38px;
                padding: 0 20px;
                border-radius: 10px;
                background: linear-gradient(135deg, var(--primary), var(--dark));
                color: #fff;
                border: none;
                font-size: .85rem;
                font-weight: 600;
                display: flex;
                align-items: center;
                gap: 6px;
                cursor: pointer;
                transition: opacity .15s, transform .15s;
            }

            .search-btn:hover {
                opacity: .9;
                transform: translateY(-50%) translateY(-1px);
            }

            .results-table {
                width: 100%;
                border-collapse: collapse;
                margin-top: 20px;
            }

            .results-table thead tr {
                background: #f8fafc;
            }

            .results-table th {
                font-size: .7rem;
                font-weight: 700;
                text-transform: uppercase;
                letter-spacing: .06em;
                color: #64748b;
                padding: 10px 14px;
                border-bottom: 1.5px solid #e8ecf4;
                white-space: nowrap;
            }

            .results-table td {
                padding: 12px 14px;
                border-bottom: 1px solid #f1f5f9;
                font-size: .88rem;
                color: #0f172a;
                vertical-align: middle;
            }

            .results-table tbody tr:hover {
                background: #f8fafc;
            }

            .results-table tbody tr:last-child td {
                border-bottom: none;
            }

            .student-name-cell {
                font-weight: 700;
                display: flex;
                align-items: center;
                gap: 10px;
            }

            .student-avatar-sm {
                width: 34px;
                height: 34px;
                border-radius: 10px;
                flex-shrink: 0;
                background: linear-gradient(135deg, var(--primary), var(--dark));
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: .85rem;
                font-weight: 800;
                color: #fff;
            }

            .balance-positive {
                color: #16a34a;
                font-weight: 700;
            }

            .balance-zero {
                color: #94a3b8;
            }

            .pay-btn {
                display: inline-flex;
                align-items: center;
                gap: 6px;
                height: 34px;
                padding: 0 16px;
                border-radius: 10px;
                background: linear-gradient(135deg, var(--primary), var(--dark));
                color: #fff;
                font-size: .8rem;
                font-weight: 600;
                text-decoration: none;
                transition: opacity .15s, transform .15s;
                box-shadow: 0 4px 12px linear-gradient(135deg, var(--primary), var(--dark));
            }

            .pay-btn:hover {
                opacity: .9;
                transform: translateY(-1px);
                color: #fff;
                text-decoration: none;
            }

            .no-results {
                background: #fffbeb;
                border: 1.5px solid #fde68a;
                border-radius: 12px;
                padding: 14px 18px;
                font-size: .88rem;
                color: #92400e;
                display: flex;
                align-items: center;
                gap: 8px;
                margin-top: 16px;
            }

            @media (max-width: 576px) {
                .search-hero {
                    padding: 20px 18px;
                }

                .search-card-body {
                    padding: 18px 14px;
                }

                .search-input {
                    padding-right: 50px;
                }

                .search-btn span {
                    display: none;
                }

                .search-btn {
                    padding: 0 14px;
                }
            }
        </style>
    </head>

    <body class="hold-transition sidebar-mini layout-fixed">
        <div class="wrapper">
            <?php @include("includes/header3.php"); ?>
            <?php @include("includes/sidebar3.php"); ?>
            <div class="content-wrapper" style="background:#f0f2f8;">
                <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">
                                                Wallet Management
                                                <span class="premium-subtitle text-secondary">Pay Via Wallet</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="dashboard2.php"
                                                    class="text-primary">Home</a></li>
                                            <li class="breadcrumb-item"><a href="small_transfer_funds.php">Transfer
                                                    Funds</a></li>
                                            <li class="breadcrumb-item active" aria-current="page">Pay Fees</li>
                                        </ol>
                                    </nav>
                                </div>
                            </div>
                        </div>
                    </div>
                </section>
                <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> Wallet Details & Transaction History
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <section class="content" style="padding:16px 12px 40px;">
                                            <div class="container-fluid" style="padding-left:0;padding-right:0;">
                                                <div class="search-wrapper">

                                                    <div class="search-hero">
                                                        <div
                                                            style="display:flex;align-items:center;gap:16px;position:relative;z-index:1;">
                                                            <div class="search-hero-icon"><i
                                                                    class="fas fa-money-bill-wave"></i></div>
                                                            <div>
                                                                <p class="search-hero-title">Pay Student Fee via Wallet</p>
                                                                <p class="search-hero-sub">Search for a student by name or
                                                                    admission number to process a wallet fee payment.</p>
                                                            </div>
                                                        </div>
                                                    </div>

                                                    <div class="search-card">
                                                        <div class="search-card-header">
                                                            <div class="search-card-header-icon"><i
                                                                    class="fas fa-search"></i></div>
                                                            <h5>Search Student</h5>
                                                        </div>
                                                        <div class="search-card-body">
                                                            <form method="POST">
                                                                <div class="search-input-wrap">
                                                                    <i class="fas fa-search search-input-icon"></i>
                                                                    <input type="text" name="search_query"
                                                                        class="search-input"
                                                                        placeholder="Enter student name or admission number"
                                                                        value="<?php echo htmlspecialchars($search_query); ?>"
                                                                        required>
                                                                    <button type="submit" name="search_student"
                                                                        class="search-btn">
                                                                        <i class="fas fa-search"></i> <span>Search</span>
                                                                    </button>
                                                                </div>
                                                            </form>

                                                            <?php if (!empty($search_results)): ?>
                                                                <div class="table-responsive">
                                                                    <table class="results-table">
                                                                        <thead>
                                                                            <tr>
                                                                                <th>Student</th>
                                                                                <th>Adm No</th>
                                                                                <th>Class</th>
                                                                                <th>Stream</th>
                                                                                <th>Wallet Balance</th>
                                                                                <th class="text-center">Action</th>
                                                                            </tr>
                                                                        </thead>
                                                                        <tbody>
                                                                            <?php foreach ($search_results as $sr): ?>
                                                                                <tr>
                                                                                    <td>
                                                                                        <div class="student-name-cell">
                                                                                            <div class="student-avatar-sm">
                                                                                                <?php echo strtoupper(substr($sr['studentName'], 0, 1)); ?>
                                                                                            </div>
                                                                                            <span><?php echo htmlspecialchars($sr['studentName']); ?></span>
                                                                                        </div>
                                                                                    </td>
                                                                                    <td><?php echo htmlspecialchars($sr['studentno']); ?>
                                                                                    </td>
                                                                                    <td><?php echo htmlspecialchars($sr['class'] . ' ' . $sr['section']); ?>
                                                                                    </td>
                                                                                    <td><?php echo htmlspecialchars($sr['stream']); ?>
                                                                                    </td>
                                                                                    <td
                                                                                        class="<?php echo $sr['balance'] > 0 ? 'balance-positive' : 'balance-zero'; ?>">
                                                                                        ₦<?php echo number_format((float) $sr['balance'], 2); ?>
                                                                                    </td>
                                                                                    <td class="text-center">
                                                                                        <a href="?id=<?php echo $sr['id']; ?>"
                                                                                            class="pay-btn">
                                                                                            <i class="fas fa-money-bill-wave"></i>
                                                                                            Pay Fee
                                                                                        </a>
                                                                                    </td>
                                                                                </tr>
                                                                            <?php endforeach; ?>
                                                                        </tbody>
                                                                    </table>
                                                                </div>
                                                            <?php elseif (isset($_POST['search_student']) && !empty($search_query)): ?>
                                                                <div class="no-results">
                                                                    <i class="fas fa-exclamation-triangle"></i>
                                                                    No students found for
                                                                    "<?php echo htmlspecialchars($search_query); ?>".
                                                                </div>
                                                            <?php endif; ?>
                                                        </div>
                                                    </div>

                                                </div>
                                            </div>
                                        </section>
                                    </div><!-- /.wpf-wrapper -->
                                </div>
                </section>
            </div><!-- /.content-wrapper -->

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

    </html>
    <?php
    exit;
}

// -----------------------------------------------------------------------
// ?id= present ” fetch student + wallet
// -----------------------------------------------------------------------
$student = null;
$stmt = $con->prepare(
    "SELECT s.id, s.studentno, s.studentName, s.class, s.section, s.stream, s.demote_status, w.balance
     FROM students s INNER JOIN wallets w ON s.id = w.student_id WHERE s.id = ?"
);
$stmt->bind_param("i", $student_id);
$stmt->execute();
$student = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$student) {
    flash_alert('Student not found.', 'dashboard2.php');
    header('Location: dashboard2.php');
    exit;
    exit;
}

// Fetch fees filtered by class + stream
$fees = [];
$feeStmt = $con->prepare("SELECT id, name, amount FROM fees WHERE class=? AND stream=? ORDER BY name ASC");
$feeStmt->bind_param("ss", $student['class'], $student['stream']);
$feeStmt->execute();
$feeResult = $feeStmt->get_result();
while ($row = $feeResult->fetch_assoc()) {
    $fees[] = $row;
}
$feeStmt->close();

// Terms and sessions
$terms = [];
$termStmt = $con->query("SELECT term_name FROM school_terms ORDER BY term_name ASC");
while ($row = $termStmt->fetch_assoc()) {
    $terms[] = $row['term_name'];
}

$sessions = [];
$sessionStmt = $con->query("SELECT session_name FROM school_sessions ORDER BY session_name DESC");
while ($row = $sessionStmt->fetch_assoc()) {
    $sessions[] = $row['session_name'];
}

// -----------------------------------------------------------------------
// Helpers
// -----------------------------------------------------------------------
function resolveTermFeeOfficer(mysqli $con, string $class, string $stream, string $session, string $term): float
{
    $amount = 0.0;
    $stmt = $con->prepare(
        "SELECT amount FROM fee_records WHERE name='School Fees' AND class=? AND stream=? AND session=? AND term=? AND student_type='Old' LIMIT 1"
    );
    $stmt->bind_param("ssss", $class, $stream, $session, $term);
    $stmt->execute();
    $stmt->bind_result($amount);
    $stmt->fetch();
    $stmt->close();
    if (!empty($amount) && $amount > 0)
        return (float) $amount;
    $amount = 0.0;
    $stmt = $con->prepare("SELECT amount FROM fees WHERE name='School Fees' AND class=? AND stream=? AND student_type='Old' LIMIT 1");
    $stmt->bind_param("ss", $class, $stream);
    $stmt->execute();
    $stmt->bind_result($amount);
    $stmt->fetch();
    $stmt->close();
    return (float) ($amount ?? 0.0);
}

function sendOfficerWalletPaymentEmail(string $email, string $studentName, string $payFor, float $amount, float $newBalance, string $term, string $session, string $class, string $payId, string $payType): void
{
    $schoolName = $_ENV['SCHOOL_NAME'];
    $year = date('Y');
    $mail = new PHPMailer(true);
    $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 = (int) $_ENV['SMTP_PORT'];
    $mail->Timeout = 10;
    $mail->setFrom($mail->Username, $schoolName);
    $mail->addAddress($email, $studentName);
    $mail->isHTML(true);
    $mail->CharSet = 'UTF-8';
    $mail->Subject = $schoolName . ' - Wallet Fee Payment Confirmation';
    $mail->Body = "<html><body><div style='max-width:600px;margin:auto;font-family:Arial,sans-serif;background:#f4f4f4;padding:20px;'>
        <h1 style='color:#fff;text-align:center;padding:10px 0;background:#4CAF50;'>Payment Successful</h1>
        <p>Dear {$studentName},</p><p>Your fee payment has been processed from your wallet.</p>
        <p><strong>Purpose:</strong> {$payFor}</p><p><strong>Amount:</strong> NGN " . number_format($amount, 2) . "</p>
        <p><strong>Term:</strong> {$term} | <strong>Session:</strong> {$session}</p>
        <p><strong>Pay ID:</strong> {$payId}</p>
        <p><strong>Remaining Balance:</strong> NGN " . number_format($newBalance, 2) . "</p>
        <center><p>{$schoolName} &copy; {$year}</p></center></div></body></html>";
    $mail->send();
}

function generateOfficerToken(int $length = 10): string
{
    $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $token = '';
    for ($i = 0; $i < $length; $i++) {
        $token .= $chars[random_int(0, strlen($chars) - 1)];
    }
    return $token;
}

// -----------------------------------------------------------------------
// POST handler
// -----------------------------------------------------------------------
if (isset($_POST['pay'])) {
    $pay_for = trim($_POST['pay_for'] ?? '');
    $term = trim($_POST['term'] ?? '');
    $session = trim($_POST['session'] ?? '');
    $pay_type = trim($_POST['payment_type'] ?? '');
    $amount = filter_var($_POST['amount'] ?? '', FILTER_VALIDATE_FLOAT);

    $sid = (int) $student['id'];
    $adno = $student['studentno'];
    $sname = $student['studentName'];
    $class = $student['class'];
    $section = $student['section'];
    $school_type = $student['stream'];
    $demote = (int) $student['demote_status'];
    $balance = (float) $student['balance'];

    $payments_enabled = (int) getWalletSetting($con, 'payments_enabled', 1);
    $min_balance = (float) getWalletSetting($con, 'min_balance', 0);

    if (!$payments_enabled) {
        $msg = "danger|Wallet payments are currently disabled by the system administrator.";
    } elseif ($amount !== false && ($balance - $amount) < $min_balance) {
        $msg = "danger|This payment would reduce the wallet balance below the minimum threshold of ₦" . number_format($min_balance, 2) . ".";
    }

    if (empty($msg) && ($amount === false || $amount <= 0)) {
        $msg = "danger|Please enter a valid amount.";
    } elseif (empty($msg) && $amount > $balance) {
        $msg = "danger|Insufficient wallet balance. Available: ₦" . number_format($balance, 2);
    } elseif (empty($msg) && (empty($pay_for) || empty($term) || empty($session))) {
        $msg = "danger|Please fill in all required fields.";
    } elseif (empty($msg)) {
        $pay_id = 'WLT-' . substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 12);

        $dupStmt = $con->prepare("SELECT id FROM payment WHERE studentno=? AND pay_id=? LIMIT 1");
        $dupStmt->bind_param("ss", $adno, $pay_id);
        $dupStmt->execute();
        $dupStmt->store_result();
        $isDuplicate = $dupStmt->num_rows > 0;
        $dupStmt->close();

        if ($isDuplicate) {
            $msg = "danger|Duplicate payment detected. Please try again.";
        } else {
            $term_inserts = [];
            $refund_insert = null;
            $token_insert = null;
            $single_insert = null;

            if ($pay_for === 'School Fees') {
                // --- Corrected allocation logic using helper functions ---
                $isFinalYear = (trim($class) === 'SS 3' || trim($class) === 'JSS 3');

                // ── Future session guard ───────────────────────────────────────
                if (isFutureSession($session, $currentSessionName)) {
                    if (!validateFutureSessionPayment($con, $sid, $currentSessionName, $class, $school_type, $session)) {
                        $msg = "danger|Future session payment rejected: student still has unpaid fees in the current session ({$currentSessionName}). Please clear those first.";
                    }
                }

                if (empty($msg)) {

                // Determine if student is NEW or OLD
                $isNew = isNewStudent($con, $sid, $session);
                $admissionTerm = null;
                if ($isNew) {
                    $admissionTerm = getAdmissionTerm($con, $sid, $session);
                    if (!$admissionTerm) {
                        $admissionTerm = 'First Term';
                    }
                }

                // Use helper to allocate payment across terms in correct order
                $allocations = allocatePaymentAcrossTerms($con, $sid, $amount, $session, $class, $school_type, $admissionTerm);

                $remaining = $amount;
                foreach ($allocations as $alloc) {
                    $allocSession = $alloc['session'];
                    $allocTerm   = $alloc['term'];
                    $allocAmount = $alloc['amount'];
                    $term_slug   = str_replace(' ', '_', strtolower($allocTerm));

                    if ($allocSession !== $session) {
                        // Excess carry-over to next session
                        $term_inserts[] = [
                            'term'    => $allocTerm,
                            'amount'  => $allocAmount,
                            'pay_id'  => $pay_id . '_next_' . $term_slug,
                            'session' => $allocSession,
                        ];
                    } else {
                        $term_inserts[] = [
                            'term'   => $allocTerm,
                            'amount' => $allocAmount,
                            'pay_id' => $pay_id . '_' . $term_slug,
                        ];
                    }
                    $remaining -= $allocAmount;
                }

                // Excess handling for final year (refund)
                if ($remaining > 0 && $isFinalYear) {
                    $refund_insert = [
                        'student_id'   => $sid,
                        'studentno'    => $adno,
                        'studentName'  => $sname,
                        'class'        => $class,
                        'section'      => $section,
                        'session'      => $session,
                        'term'         => 'Second Term',
                        'amount'       => $remaining,
                        'pay_id'       => $pay_id,
                        'method'       => 'Wallet',
                        'school_type'  => $school_type,
                        'payment_type' => $pay_type,
                        'status'       => 'pending',
                        'reason'       => 'Excess payment from Final Year student (Both terms fully paid)',
                    ];
                }
                } // end if (empty($msg)) future session guard
            } elseif ($pay_for === 'Lesson Fees') {
                $single_insert = ['pay_for' => $pay_for, 'term' => $term, 'amount' => $amount, 'pay_id' => $pay_id, 'session' => $session];
            } else {
                $single_insert = ['pay_for' => $pay_for, 'term' => $term, 'amount' => $amount, 'pay_id' => $pay_id, 'session' => $session];
                $boardingFeeNames = ['JSS 1-3 FULL (ONE TERM) BOARDING FEES (NEW STUDENT)', 'JSS 1-3 FULL (2 TERMS) BOARDING FEES (NEW STUDENT)', 'JSS 1-3 FULL SESSION BOARDING FEES (NEW STUDENT)', 'SS 1-3 FULL (ONE TERM) BOARDING FEES (NEW STUDENT)', 'SS 1-3 FULL (2 TERMS) BOARDING FEES (NEW STUDENT)', 'SS 1-3 FULL SESSION BOARDING FEES (NEW STUDENT)'];
                if (in_array(trim($pay_for), $boardingFeeNames)) {
                    $token_insert = ['studentno' => $adno, 'student_name' => $sname, 'token_for' => $pay_for, 'class' => $class, 'term' => $term, 'session' => $session, 'school_type' => $school_type, 'token' => generateOfficerToken(), 'token_status' => 'pending'];
                }
            }

            // ---------------------------------------------------------------
            // Atomic transaction — only proceed if no validation errors
            // ---------------------------------------------------------------
            if (!empty($msg)) {
                // Validation failed (e.g. future session guard) — do not touch wallet
            } else {
            mysqli_begin_transaction($con);
            try {
                $s1 = $con->prepare("UPDATE wallets SET balance = balance - ? WHERE student_id = ? AND balance >= ?");
                $s1->bind_param("did", $amount, $sid, $amount);
                $s1->execute();
                if ($s1->affected_rows !== 1)
                    throw new Exception("Wallet deduction failed.");
                $s1->close();

                $ref = "WP-" . strtoupper(dechex(time())) . rand(100, 999);
                $wtype = "Wallet Payment - " . $pay_for;
                $notes = "Officer wallet fee payment: $pay_for | $term $session";
                $s2 = $con->prepare("INSERT INTO wallet_transactions (student_id, amount, reference, type, status, notes, created_at) VALUES (?, ?, ?, ?, 'success', ?, NOW())");
                $s2->bind_param("idsss", $sid, $amount, $ref, $wtype, $notes);
                $s2->execute();
                $s2->close();

                if ($pay_for === 'School Fees') {
                    foreach ($term_inserts as $ins) {
                        $ins_session = $ins['session'] ?? $session;
                        $s3 = $con->prepare("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 (?, ?, ?, ?, ?, ?, ?, ?, ?, 'School Fees', ?, 'Wallet', ?, 'No', 0, 0)");
                        $s3->bind_param("ssssssssdis", $adno, $sname, $ins['term'], $ins_session, $class, $school_type, $pay_type, $ins['pay_id'], $ins['amount'], $sid, $section);
                        $s3->execute();
                        $s3->close();
                    }
                } else {
                    $s3 = $con->prepare("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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'Wallet', ?, 'No', 0, 0)");
                    $s3->bind_param("ssssssssdsis", $adno, $sname, $single_insert['term'], $single_insert['session'], $class, $school_type, $pay_type, $single_insert['pay_id'], $single_insert['amount'], $single_insert['pay_for'], $sid, $section);
                    $s3->execute();
                    $s3->close();
                }

                if ($token_insert !== null) {
                    $ti = $token_insert;
                    $s4 = $con->prepare("INSERT INTO registration_tokens (studentno, student_name, token_for, class, term, session, school_type, token, token_status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                    $s4->bind_param("sssssssss", $ti['studentno'], $ti['student_name'], $ti['token_for'], $ti['class'], $ti['term'], $ti['session'], $ti['school_type'], $ti['token'], $ti['token_status']);
                    $s4->execute();
                    $s4->close();
                }

                if ($refund_insert !== null) {
                    $ri = $refund_insert;
                    $s5 = $con->prepare("INSERT INTO refund (student_id, studentno, studentName, class, section, session, term, amount, pay_id, method, school_type, payment_type, status, reason) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                    $s5->bind_param("issssssdssssss", $ri['student_id'], $ri['studentno'], $ri['studentName'], $ri['class'], $ri['section'], $ri['session'], $ri['term'], $ri['amount'], $ri['pay_id'], $ri['method'], $ri['school_type'], $ri['payment_type'], $ri['status'], $ri['reason']);
                    $s5->execute();
                    $s5->close();
                }

                mysqli_commit($con);

                $rs = $con->prepare("SELECT balance FROM wallets WHERE student_id = ?");
                $rs->bind_param("i", $sid);
                $rs->execute();
                $student['balance'] = $rs->get_result()->fetch_assoc()['balance'];
                $rs->close();

                try {
                    $emailStmt = $con->prepare("SELECT email FROM students WHERE id = ?");
                    $emailStmt->bind_param("i", $sid);
                    $emailStmt->execute();
                    $emailRow = $emailStmt->get_result()->fetch_assoc();
                    $emailStmt->close();
                    if (!empty($emailRow['email'])) {
                        sendOfficerWalletPaymentEmail($emailRow['email'], $sname, $pay_for, $amount, (float) $student['balance'], $term, $session, $class, $pay_id, $pay_type);
                    }
                } catch (Exception $mailEx) {
                    error_log("Officer wallet payment email failed: " . $mailEx->getMessage());
                }

                $msg = "success|Payment of ₦" . number_format($amount, 2) . " for \"$pay_for\" processed. Pay ID: $pay_id";

            } catch (Exception $e) {
                mysqli_rollback($con);
                $msg = "danger|Transaction failed: " . $e->getMessage();
            }
            } // end else (validation passed — transaction allowed)
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">

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

    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <style>
        .wpf-wrapper {
            max-width: 780px;
            margin: 0 auto;
            padding: 0 0 40px;
        }

        .student-hero {
            background: linear-gradient(135deg, var(--primary), var(--dark));
            border-radius: 20px;
            padding: 28px 32px;
            position: relative;
            overflow: hidden;
            box-shadow: 0 20px 60px linear-gradient(135deg, var(--primary), var(--dark));
            margin-bottom: 24px;
        }

        .student-hero::before {
            content: '';
            position: absolute;
            top: -60px;
            right: -60px;
            width: 220px;
            height: 220px;
            background: linear-gradient(135deg, var(--primary), var(--dark));
            border-radius: 50%;
        }

        .student-hero::after {
            content: '';
            position: absolute;
            bottom: -40px;
            left: 30%;
            width: 160px;
            height: 160px;
            background: radial-gradient(circle, rgba(16, 185, 129, .15) 0%, transparent 70%);
            border-radius: 50%;
        }

        .hero-inner {
            display: flex;
            align-items: center;
            justify-content: space-between;
            position: relative;
            z-index: 1;
            gap: 12px;
        }

        .hero-info {
            display: flex;
            align-items: center;
            gap: 16px;
            min-width: 0;
        }

        .hero-avatar {
            width: 54px;
            height: 54px;
            background: linear-gradient(135deg, var(--primary), var(--dark));
            border-radius: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.4rem;
            font-weight: 800;
            color: #fff;
            box-shadow: 0 8px 20px linear-gradient(135deg, var(--primary), var(--dark));
            flex-shrink: 0;
        }

        .hero-name {
            font-size: 1.15rem;
            font-weight: 700;
            color: #f8fafc;
            margin: 0;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .hero-meta {
            font-size: .75rem;
            color: #94a3b8;
            margin: 3px 0 0;
        }

        .hero-badge {
            background: rgba(255, 255, 255, .07);
            border: 1px solid rgba(255, 255, 255, .12);
            border-radius: 10px;
            padding: 10px 20px;
            text-align: right;
            backdrop-filter: blur(6px);
        }

        .hero-badge-label {
            font-size: .65rem;
            text-transform: uppercase;
            letter-spacing: .1em;
            color: #64748b;
        }

        .hero-badge-amount {
            font-size: 1.5rem;
            font-weight: 800;
            color: #34d399;
            line-height: 1.2;
        }

        .form-card {
            background: #fff;
            border-radius: 20px;
            box-shadow: 0 4px 30px linear-gradient(135deg, var(--primary), var(--dark));
            overflow: hidden;
            border: 1px solid #e8ecf4;
        }

        .form-card-header {
            padding: 20px 28px;
            border-bottom: 1px solid #f1f5f9;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .form-card-header-icon {
            width: 36px;
            height: 36px;
            background: linear-gradient(135deg, var(--primary), var(--dark));
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;
            font-size: .85rem;
        }

        .form-card-header h5 {
            margin: 0;
            font-size: .95rem;
            font-weight: 700;
            color: #0f172a;
        }

        .form-card-body {
            padding: 28px;
        }

        .field-label {
            font-size: .75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: .06em;
            color: #64748b;
            margin-bottom: 7px;
            display: block;
        }

        .wpf-input {
            width: 100%;
            height: 46px;
            border: 1.5px solid #e2e8f0;
            border-radius: 12px;
            padding: 0 14px;
            font-size: .9rem;
            color: #0f172a;
            background: #f8fafc;
            outline: none;
            transition: border-color .2s, box-shadow .2s;
        }

        .wpf-input:focus {
            border-color: #6366f1;
            box-shadow: 0 0 0 4px linear-gradient(135deg, var(--primary), var(--dark));
            background: #fff;
        }

        .amount-group {
            position: relative;
        }

        .amount-prefix {
            position: absolute;
            left: 14px;
            top: 50%;
            transform: translateY(-50%);
            font-weight: 700;
            color: #6366f1;
            font-size: .95rem;
            pointer-events: none;
        }

        .amount-group .wpf-input {
            padding-left: 32px;
        }

        .select2-container {
            width: 100% !important;
        }

        .select2-container--default .select2-selection--single {
            height: 46px !important;
            border: 1.5px solid #e2e8f0 !important;
            border-radius: 12px !important;
            background: #f8fafc !important;
            display: flex;
            align-items: center;
            padding: 0 14px;
            transition: border-color .2s, box-shadow .2s;
        }

        .select2-container--default.select2-container--open .select2-selection--single,
        .select2-container--default.select2-container--focus .select2-selection--single {
            border-color: #6366f1 !important;
            box-shadow: 0 0 0 4px rgba(99, 102, 241, .1) !important;
            background: #fff !important;
        }

        .select2-container--default .select2-selection--single .select2-selection__rendered {
            color: #0f172a;
            font-size: .9rem;
            line-height: 46px !important;
            padding: 0;
        }

        .select2-container--default .select2-selection--single .select2-selection__placeholder {
            color: #94a3b8;
        }

        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 46px !important;
            right: 12px;
        }

        .select2-dropdown {
            border: 1.5px solid #e2e8f0 !important;
            border-radius: 12px !important;
            box-shadow: 0 10px 40px rgba(15, 23, 42, .12) !important;
            overflow: hidden;
        }

        .select2-container--default .select2-results__option--highlighted {
            background: #007bff !important;
        }

        .select2-search--dropdown .select2-search__field {
            border-radius: 8px !important;
            border: 1.5px solid #e2e8f0 !important;
            padding: 6px 10px;
        }

        .breakdown-panel {
            background: linear-gradient(135deg, #eff6ff, #f0fdf4);
            border: 1.5px solid #bfdbfe;
            border-radius: 14px;
            padding: 16px 20px;
            margin-bottom: 20px;
        }

        .breakdown-panel-title {
            font-size: .75rem;
            font-weight: 700;
            color: #3b82f6;
            margin-bottom: 10px;
            text-transform: uppercase;
            letter-spacing: .06em;
        }

        .breakdown-item {
            display: inline-flex;
            flex-direction: column;
            margin-right: 24px;
            margin-bottom: 8px;
        }

        .breakdown-item-label {
            font-size: .68rem;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: .05em;
        }

        .breakdown-item-value {
            font-size: .95rem;
            font-weight: 700;
            color: #1e40af;
        }

        .section-divider {
            height: 1px;
            background: #f1f5f9;
            margin: 24px 0;
        }

        .notice-bar {
            background: #fffbeb;
            border: 1.5px solid #fde68a;
            border-radius: 12px;
            padding: 12px 16px;
            font-size: .82rem;
            color: #92400e;
            display: flex;
            align-items: flex-start;
            gap: 8px;
            margin-bottom: 24px;
        }

        .notice-bar i {
            margin-top: 1px;
            color: #f59e0b;
            flex-shrink: 0;
        }

        .wpf-alert {
            border-radius: 14px;
            padding: 14px 18px;
            font-size: .88rem;
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 20px;
            border: none;
        }

        .wpf-alert.success {
            background: #f0fdf4;
            color: #166534;
            border-left: 4px solid #22c55e;
        }

        .wpf-alert.danger {
            background: #fef2f2;
            color: #991b1b;
            border-left: 4px solid #ef4444;
        }

        .wpf-alert .close {
            margin-left: auto;
            background: none;
            border: none;
            font-size: 1.1rem;
            color: inherit;
            opacity: .6;
            cursor: pointer;
        }

        .btn-pay {
            color: #fff;
            border: none;
            height: 48px;
            padding: 0 32px;
            border-radius: 12px;
            font-size: .9rem;
            font-weight: 700;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            cursor: pointer;
            box-shadow: 0 6px 20px rgba(99, 102, 241, .35);
            transition: transform .15s, box-shadow .15s, opacity .15s;
        }

        .btn-pay:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 10px 28px rgba(99, 102, 241, .45);
        }

        .btn-pay:disabled {
            opacity: .5;
            cursor: not-allowed;
        }

        .btn-cancel {
            height: 48px;
            padding: 0 28px;
            border-radius: 12px;
            font-size: .9rem;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            border: 1.5px solid #e2e8f0;
            background: #fff;
            color: #64748b;
            text-decoration: none;
            transition: border-color .15s, color .15s;
        }

        .btn-cancel:hover {
            border-color: #6366f1;
            color: #6366f1;
            text-decoration: none;
        }

        .bal-warn {
            font-size: .78rem;
            color: #ef4444;
            font-weight: 600;
            margin-top: 6px;
            display: none;
        }

        .bal-warn.show {
            display: flex;
            align-items: center;
            gap: 5px;
        }

        @media (max-width: 576px) {
            .hero-inner {
                flex-direction: column;
                align-items: flex-start;
            }

            .hero-badge {
                width: 100%;
                text-align: left;
                padding: 10px 14px;
            }

            .hero-badge-amount {
                font-size: 1.25rem;
            }

            .hero-name {
                font-size: 1rem;
                white-space: normal;
            }

            .student-hero {
                padding: 20px 18px;
            }

            .form-card-body {
                padding: 18px 14px;
            }

            .form-card-header {
                padding: 16px 14px;
            }
        }

        @media (max-width: 767px) {
            .col-md-6 {
                width: 100% !important;
                flex: 0 0 100% !important;
                max-width: 100% !important;
            }

            .btn-pay,
            .btn-cancel {
                width: 100%;
                justify-content: center;
            }
        }
    </style>
</head>

<body class="hold-transition sidebar-mini layout-fixed bg-slate-50">
    <div class="wrapper">
        <?php include("includes/header3.php"); ?>
        <?php include("includes/sidebar3.php"); ?>

        <div class="content-wrapper" style="background:#f0f2f8;">
            <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">
                                            Wallet Management
                                            <span class="premium-subtitle text-secondary">Pay From Wallet</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="dashboard2.php"
                                                class="text-primary">Home</a></li>
                                        <li class="breadcrumb-item active" aria-current="page">Pay Fees</li>
                                    </ol>
                                </nav>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
            <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 From Wallet
                                    </h5>
                                </div>
                                <div class="card-body">

                                    <section class="content" style="padding:16px 12px 40px;">
                                        <div class="container-fluid" style="padding-left:0;padding-right:0;">
                                            <div class="wpf-wrapper">

                                                <?php if ($msg):
                                                    [$type, $text] = explode('|', $msg, 2); ?>
                                                    <div
                                                        class="wpf-alert <?= $type === 'success' ? 'success' : 'danger' ?> alert-dismissible">
                                                        <i
                                                            class="fas <?= $type === 'success' ? 'fa-check-circle' : 'fa-times-circle' ?>"></i>
                                                        <span><?= htmlspecialchars($text) ?></span>
                                                        <button type="button" class="close" data-dismiss="alert"
                                                            aria-label="Close">&times;</button>
                                                    </div>
                                                <?php endif; ?>

                                                <div class="student-hero">
                                                    <div class="hero-inner">
                                                        <div class="hero-info">
                                                            <div class="hero-avatar">
                                                                <?= strtoupper(substr($student['studentName'], 0, 1)) ?>
                                                            </div>
                                                            <div>
                                                                <p class="hero-name">
                                                                    <?= htmlspecialchars($student['studentName']) ?></p>
                                                                <p class="hero-meta">ADM:
                                                                    <?= htmlspecialchars($student['studentno']) ?>
                                                                    &nbsp;·&nbsp;
                                                                    <?= htmlspecialchars($student['class'] . ' ' . $student['section']) ?>
                                                                    &nbsp;·&nbsp;
                                                                    <?= htmlspecialchars($student['stream']) ?></p>
                                                            </div>
                                                        </div>
                                                        <div class="hero-badge">
                                                            <p class="hero-badge-label">Wallet Balance</p>
                                                            <p class="hero-badge-amount">
                                                                ₦<?= number_format((float) $student['balance'], 2) ?>
                                                            </p>
                                                        </div>
                                                    </div>
                                                </div>

                                                <div class="form-card">
                                                    <div class="form-card-header">
                                                        <div class="form-card-header-icon"><i
                                                                class="fas fa-receipt"></i></div>
                                                        <h5>Fee Payment Details</h5>
                                                    </div>
                                                    <div class="form-card-body">
                                                        <form method="POST">
                                                            <div class="row">
                                                                <div class="col-md-6" style="margin-bottom:20px;">
                                                                    <label class="field-label">Fee Type /
                                                                        Purpose</label>
                                                                    <select name="pay_for" id="pay_for"
                                                                        class="select2-field" required>
                                                                        <option value="">Select fee type</option>
                                                                        <?php foreach ($fees as $fee): ?>
                                                                            <option
                                                                                value="<?= htmlspecialchars($fee['name']) ?>"
                                                                                data-amount="<?= $fee['amount'] ?>">
                                                                                <?= htmlspecialchars($fee['name']) ?>
                                                                            </option>
                                                                        <?php endforeach; ?>
                                                                        <?php if (empty($fees)): ?>
                                                                            <option disabled>No fees available for this
                                                                                student</option><?php endif; ?>
                                                                    </select>
                                                                </div>
                                                                <div class="col-md-6" style="margin-bottom:20px;">
                                                                    <label class="field-label">Payment Type</label>
                                                                    <select name="payment_type" id="payment_type"
                                                                        class="select2-field" required>
                                                                        <option value="">Select payment type</option>
                                                                        <option value="Full Payment">Full Payment
                                                                        </option>
                                                                        <option value="Part Payment">Part Payment
                                                                        </option>
                                                                        <option value="Full Term">Full Term</option>
                                                                        <option value="Half Term">Half Term Payment
                                                                        </option>
                                                                        <option value="Full Session">Full Session
                                                                            Payment</option>
                                                                    </select>
                                                                </div>
                                                                <div class="col-md-6" style="margin-bottom:20px;">
                                                                    <label class="field-label">Term</label>
                                                                    <select name="term" id="term" class="select2-field"
                                                                        required>
                                                                        <option value="">Select term</option>
                                                                        <?php foreach ($terms as $t): ?>
                                                                            <option value="<?= htmlspecialchars($t) ?>">
                                                                                <?= htmlspecialchars($t) ?></option>
                                                                        <?php endforeach; ?>
                                                                    </select>
                                                                </div>
                                                                <div class="col-md-6" style="margin-bottom:20px;">
                                                                    <label class="field-label">Session</label>
                                                                    <select name="session" id="session"
                                                                        class="select2-field" required>
                                                                        <option value="">Select session</option>
                                                                        <?php foreach ($sessions as $s): ?>
                                                                            <option value="<?= htmlspecialchars($s) ?>">
                                                                                <?= htmlspecialchars($s) ?></option>
                                                                        <?php endforeach; ?>
                                                                    </select>
                                                                </div>
                                                                <div class="col-md-12" style="margin-bottom:20px;">
                                                                    <label class="field-label">Amount (₦)</label>
                                                                    <div class="amount-group">
                                        
                                                                        <input type="number" step="0.01" min="0.01"
                                                                            max="<?= $student['balance'] ?>"
                                                                            name="amount" id="amount" class="wpf-input"
                                                                            placeholder="0.00" required
                                                                            oninput="checkBalance(this.value)">
                                                                    </div>
                                                                    <div id="balance_warn" class="bal-warn"><i
                                                                            class="fas fa-exclamation-circle"></i>
                                                                        Amount exceeds wallet balance.</div>
                                                                </div>
                                                            </div>

                                                            <!-- School Fees breakdown panel -->
                                                            <div id="school-fees-panel" class="breakdown-panel"
                                                                style="display:none;">
                                                                <p class="breakdown-panel-title"><i
                                                                        class="fas fa-layer-group mr-1"></i> Term Fee
                                                                    Breakdown</p>
                                                                <div id="term-fee-details"
                                                                    style="display:flex;flex-wrap:wrap;gap:8px 0;">
                                                                </div>
                                                            </div>

                                                            <div class="section-divider"></div>

                                                            <div class="notice-bar">
                                                                <i class="fas fa-shield-alt"></i>
                                                                <span>This will deduct the amount from the student's
                                                                    wallet and record it as a payment. <strong>This
                                                                        action cannot be undone.</strong></span>
                                                            </div>
                                                            <div style="display:flex;gap:12px;flex-wrap:wrap;">
                                                                <button type="submit" name="pay" id="payBtn"
                                                                    class="btn-pay btn btn-primary" <?= empty($fees) ? 'disabled' : '' ?>>
                                                                    <i class="fas fa-check-circle"></i> Confirm &amp;
                                                                    Pay
                                                                </button>
                                                                <a href="small_wallet_pay_fee.php" class="btn-cancel">
                                                                    <i class="fas fa-arrow-left"></i> Search Another
                                                                </a>
                                                                <a href="dashboard2.php" class="btn-cancel">
                                                                    <i class="fas fa-home"></i> Dashboard
                                                                </a>
                                                            </div>
                                                        </form>
                                                    </div><!-- /.form-card-body -->
                                                </div><!-- /.form-card -->
                                            </div><!-- /.wpf-wrapper -->
                                        </div><!-- /.container-fluid (inner) -->
                                    </section><!-- /.content (inner) -->
                                </div><!-- /.card-body -->
                            </div><!-- /.card -->
                        </div><!-- /.col-md-12 -->
                    </div><!-- /.row -->
                </div><!-- /.container-fluid (outer) -->
            </section><!-- /.content (outer) -->
        </div><!-- /.content-wrapper -->

        <?php @include("includes/footer.php"); ?>
        <?php @include("includes/foot.php"); ?>
    </div><!-- /.wrapper -->
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            document.querySelectorAll('.alert-dismissible').forEach(function (el) {
                setTimeout(function () {
                    const btn = el.querySelector('[data-dismiss="alert"]');
                    if (btn) btn.click();
                }, 10000);
            });
        });

        const walletBalance = <?= (float) $student['balance'] ?>;
        const studentClass = <?= json_encode($student['class']) ?>;
        const studentStream = <?= json_encode($student['stream']) ?>;

        $(document).ready(function () {
            $('.select2-field').select2({ width: '100%' });
            $('#pay_for').on('change', onFeeChange);
            $('#term').on('change', fetchFeeAmount);
            $('#session').on('change', function () {
                fetchFeeAmount();
                if ($('#pay_for').val() === 'School Fees') fetchSchoolFeeBreakdown();
            });
        });

        function checkBalance(val) {
            const warn = document.getElementById('balance_warn');
            const btn = document.getElementById('payBtn');
            const over = parseFloat(val) > walletBalance;
            warn.classList.toggle('show', over);
            btn.disabled = over || <?= empty($fees) ? 'true' : 'false' ?>;
        }

        function onFeeChange() {
            fetchFeeAmount();
            const feeName = $('#pay_for').val();
            const panel = document.getElementById('school-fees-panel');
            if (feeName === 'School Fees') {
                panel.style.display = 'block';
                const session = $('#session').val();
                if (session) fetchSchoolFeeBreakdown();
                else document.getElementById('term-fee-details').innerHTML = '<em style="color:#3b82f6;font-size:.82rem;">Select a session to see the breakdown.</em>';
            } else {
                panel.style.display = 'none';
            }
        }

        function fetchFeeAmount() {
            const feeName = $('#pay_for').val();
            const term = $('#term').val();
            const session = $('#session').val();
            if (!feeName || !term || !session) return;
            fetch(`get_fee_amount.php?fee_name=${encodeURIComponent(feeName)}&class=${encodeURIComponent(studentClass)}&stream=${encodeURIComponent(studentStream)}&term=${encodeURIComponent(term)}&session=${encodeURIComponent(session)}`)
                .then(r => r.json())
                .then(data => {
                    if (data.amount > 0) {
                        document.getElementById('amount').value = data.amount;
                        checkBalance(data.amount);
                    }
                });
        }

        function fetchSchoolFeeBreakdown() {
            const session = $('#session').val();
            if (!session) return;
            const termNames = ['First Term', 'Second Term', 'Third Term'];
            const container = document.getElementById('term-fee-details');
            container.innerHTML = '<em style="color:#64748b;font-size:.82rem;">Loading</em>';
            Promise.all(termNames.map(t =>
                fetch(`get_fee_amount.php?fee_name=School+Fees&class=${encodeURIComponent(studentClass)}&stream=${encodeURIComponent(studentStream)}&term=${encodeURIComponent(t)}&session=${encodeURIComponent(session)}`)
                    .then(r => r.json())
                    .then(d => ({ term: t, amount: d.amount }))
            )).then(results => {
                container.innerHTML = results.map(r =>
                    `<div class="breakdown-item">
                <span class="breakdown-item-label">${r.term}</span>
                <span class="breakdown-item-value">₦${parseFloat(r.amount).toLocaleString('en-NG', { minimumFractionDigits: 2 })}</span>
             </div>`
                ).join('');
            });
        }
    </script>
</body>

</html>