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


if (strlen($_SESSION['sid'] == 0)) {

    header('location:logout.php');

    exit;

}

// --- DVA: Server-side form processing + fetch available banks ---
require_once 'vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
$paystackSecretKey = $_ENV['PAYSTACK_SECRET_KEY'];

$va_message = '';
$va_error   = '';

// Payment type definitions
$paymentTypes = [
    'entrance'        => 'Entrance Payment',
    'lesson'          => 'Lesson Fees',
    'certificate'     => 'Certificate / Testimonial Fees',
    'new_student_day' => 'New Day Student Fees',
    'new_student_board' => 'New Boarding Student Fees',
];

// Fetch available banks for DVA from Paystack
$availableBanks = [];
$banksCh = curl_init('https://api.paystack.co/dedicated_account/available_providers');
curl_setopt_array($banksCh, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => ['Authorization: Bearer ' . $paystackSecretKey],
]);
$banksResp = curl_exec($banksCh);
curl_close($banksCh);
if ($banksResp) {
    $banksData = json_decode($banksResp, true);
    if (!empty($banksData['status']) && !empty($banksData['data'])) {
        $availableBanks = $banksData['data'];
    }
}

// Handle create virtual account form POST
if (isset($_POST['create_va'])) {
    $customerName  = trim($_POST['customer_last']  ?? '');
    $customerLast  = trim($_POST['customer_name']   ?? '');
    $customerEmail = trim($_POST['customer_email']  ?? '');
    $customerPhone = trim($_POST['customer_phone']  ?? '');
    $preferredBank = trim($_POST['preferred_bank']  ?? '');
    $paymentType   = trim($_POST['payment_type']    ?? '');

    if ($customerName && $customerLast && $customerEmail && $customerPhone && $preferredBank && $paymentType && isset($paymentTypes[$paymentType])) {
        // Check if this payment type already has an active account
        $existCheck = $con->prepare("SELECT id FROM school_virtual_accounts WHERE payment_type = ? AND is_active = 1 LIMIT 1");
        $existCheck->bind_param('s', $paymentType);
        $existCheck->execute();
        $existRow = $existCheck->get_result()->fetch_assoc();
        $existCheck->close();

        if ($existRow) {
            $va_error = 'An active virtual account already exists for ' . $paymentTypes[$paymentType] . '. Deactivate it first before creating a new one.';
        } else {
            // Step 1: Create Paystack customer
            $custPayload = json_encode([
                'first_name' => $customerName,
                'last_name'  => $customerLast,
                'email'      => $customerEmail,
                'phone'      => $customerPhone,
            ]);
            $custCh = curl_init('https://api.paystack.co/customer');
            curl_setopt_array($custCh, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POST           => true,
                CURLOPT_POSTFIELDS     => $custPayload,
                CURLOPT_HTTPHEADER     => [
                    'Authorization: Bearer ' . $paystackSecretKey,
                    'Content-Type: application/json',
                ],
            ]);
            $custResp = curl_exec($custCh);
            curl_close($custCh);
            $custData = json_decode($custResp, true);

            if (!empty($custData['status']) && !empty($custData['data']['customer_code'])) {
                $customerCode = $custData['data']['customer_code'];

                // Step 2: Create dedicated virtual account
                $dvaPayload = json_encode([
                    'customer'       => $customerCode,
                    'preferred_bank' => $preferredBank,
                ]);
                $dvaCh = curl_init('https://api.paystack.co/dedicated_account');
                curl_setopt_array($dvaCh, [
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_POST           => true,
                    CURLOPT_POSTFIELDS     => $dvaPayload,
                    CURLOPT_HTTPHEADER     => [
                        'Authorization: Bearer ' . $paystackSecretKey,
                        'Content-Type: application/json',
                    ],
                ]);
                $dvaResp = curl_exec($dvaCh);
                curl_close($dvaCh);
                $dvaData = json_decode($dvaResp, true);

                if (!empty($dvaData['status']) && !empty($dvaData['data'])) {
                    $d             = $dvaData['data'];
                    $bankName      = $d['bank']['name']   ?? '';
                    $accountNum    = $d['account_number'] ?? '';
                    $accountName   = $d['account_name']   ?? '';
                    $paystackCust  = $customerCode;
                    $paystackDvaId = (string)($d['id']    ?? '');

                    $insStmt = $con->prepare(
                        "INSERT INTO school_virtual_accounts
                         (payment_type, bank_name, account_number, account_name, paystack_customer_id, paystack_dva_id, is_active)
                         VALUES (?, ?, ?, ?, ?, ?, 1)"
                    );
                    $insStmt->bind_param('ssssss', $paymentType, $bankName, $accountNum, $accountName, $paystackCust, $paystackDvaId);
                    if ($insStmt->execute()) {
                        $va_message = $paymentTypes[$paymentType] . ' virtual account created successfully!';
                    } else {
                        $va_error = 'Account created on Paystack but could not be saved to database.';
                    }
                    $insStmt->close();
                } else {
                    $va_error = $dvaData['message'] ?? 'Failed to create virtual account on Paystack.';
                }
            } else {
                $va_error = $custData['message'] ?? 'Failed to create Paystack customer.';
            }
        }
    } else {
        $va_error = 'All fields are required, including payment type.';
    }
}

// Fetch all virtual accounts grouped by payment type
$allVaAccounts = [];
$vaAllResult = mysqli_query($con, "SELECT * FROM school_virtual_accounts ORDER BY payment_type ASC, created_at DESC");
if ($vaAllResult) {
    while ($r = mysqli_fetch_assoc($vaAllResult)) {
        $allVaAccounts[$r['payment_type']][] = $r;
    }
}

// For backward compat — single active account (used by confirm pages)
$vaRow = null;
$vaResult = mysqli_query($con, "SELECT * FROM school_virtual_accounts WHERE is_active = 1 LIMIT 1");
if ($vaResult) $vaRow = mysqli_fetch_assoc($vaResult);





// --- 1. CONFIG & PAGINATION ---

$limit = 50;

$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;

if ($page < 1) $page = 1;

$offset = ($page - 1) * $limit;

$search = isset($_GET['search']) ? trim($_GET['search']) : '';



// --- 2. SYSTEM STATS (Secure & Optimized) ---

$stats_query = "SELECT 

    (SELECT SUM(balance) FROM wallets) as total_liquidity,

    (SELECT SUM(amount) FROM wallet_transactions WHERE type='deposit' AND status='success') as total_in,

    (SELECT SUM(amount) FROM wallet_transactions WHERE type LIKE 'Wallet Payment%' AND status='success') as total_out";

$stats_res = mysqli_query($con, $stats_query);

$stat_row = mysqli_fetch_assoc($stats_res);



$total_liquidity = $stat_row['total_liquidity'] ?? 0;

$total_in = $stat_row['total_in'] ?? 0;

$total_out = $stat_row['total_out'] ?? 0;



// --- 3. FETCH STUDENT BALANCES ---

$base_query = "FROM wallets w LEFT JOIN students s ON w.student_id = s.id";

$search_where = "";

$params = [];

$types = "";



if (!empty($search)) {

    $search_where = " WHERE s.studentName LIKE ? OR s.studentno LIKE ? OR w.student_id LIKE ?";

    $search_term = "%$search%";

    $params = [$search_term, $search_term, $search_term];

    $types = "sss";

}



$count_stmt = $con->prepare("SELECT COUNT(*) as total " . $base_query . $search_where);

if (!empty($search)) {

    $count_stmt->bind_param($types, ...$params);

}

$count_stmt->execute();

$total_rows = $count_stmt->get_result()->fetch_assoc()['total'];

$total_pages = ceil($total_rows / $limit);



$data_query = "SELECT w.student_id, w.balance, s.studentName, s.studentno, s.class, s.section " . 

               $base_query . $search_where . " ORDER BY s.studentName ASC LIMIT ? OFFSET ?";

$data_stmt = $con->prepare($data_query);



if (!empty($search)) {

    $bind_params = array_merge($params, [$limit, $offset]);

    $data_stmt->bind_param($types . "ii", ...$bind_params);

} else {

    $data_stmt->bind_param("ii", $limit, $offset);

}



$data_stmt->execute();

$result = $data_stmt->get_result();

?>

<!DOCTYPE html>

<html lang="en">

<head>

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



    <style>

        .bento-card { @apply bg-white p-5 rounded-3xl border border-slate-100 shadow-sm hover:shadow-xl hover:border-blue-100 transition-all duration-300; }

        .pagination .page-item.active .page-link { background-color: #3b82f6 !important; border-color: #3b82f6 !important; color: white !important; }

        .page-link { color: #64748b; border-radius: 8px !important; margin: 0 2px; }



    </style>

</head>

<body class="hold-transition sidebar-mini layout-fixed">

    <div class="wrapper">

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

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



        <div class="content-wrapper">

<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">Administrative Control</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 active">Wallet Manager</li>

                            <li class="breadcrumb-item active" aria-current="page">Manage Wallets</li>

                        </ol>

                    </nav>

                </div>

            </div>

        </div>

    </div>

</section>


            <!-- ===== VIRTUAL ACCOUNT MANAGER SECTION ===== -->
            <section class="content" style="padding-top:0;">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-md-12">

                            <!-- Virtual Account Management Card -->
                            <div class="card card-primary mb-4">
                                <div class="card-header">
                                    <h5 class="card-title font-weight-bold">
                                        <i class="fas fa-university"></i> Virtual Account Management
                                    </h5>
                                </div>
                                <div class="card-body">

                                    <?php if ($va_message): ?>
                                    <div class="alert alert-success"><i class="fas fa-check-circle mr-2"></i><?= htmlspecialchars($va_message) ?></div>
                                    <?php endif; ?>
                                    <?php if ($va_error): ?>
                                    <div class="alert alert-danger"><i class="fas fa-times-circle mr-2"></i><?= htmlspecialchars($va_error) ?></div>
                                    <?php endif; ?>

                                    <!-- Existing accounts table -->
                                    <?php if (!empty($allVaAccounts)): ?>
                                    <div class="table-responsive mb-4">
                                        <table class="table table-hover table-sm align-middle mb-0">
                                            <thead class="bg-light text-muted" style="font-size:.75rem;text-transform:uppercase;">
                                                <tr>
                                                    <th>Payment Type</th>
                                                    <th>Bank</th>
                                                    <th>Account Number</th>
                                                    <th>Account Name</th>
                                                    <th>Status</th>
                                                    <th>Created</th>
                                                    <th class="text-center">Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($allVaAccounts as $type => $accounts): ?>
                                                    <?php foreach ($accounts as $va): ?>
                                                    <tr>
                                                        <td><span class="badge badge-primary"><?= htmlspecialchars($paymentTypes[$type] ?? $type) ?></span></td>
                                                        <td><?= htmlspecialchars($va['bank_name']) ?></td>
                                                        <td><strong style="font-family:monospace;"><?= htmlspecialchars($va['account_number']) ?></strong></td>
                                                        <td><?= htmlspecialchars($va['account_name']) ?></td>
                                                        <td>
                                                            <?php if ($va['is_active']): ?>
                                                                <span class="badge badge-success">Active</span>
                                                            <?php else: ?>
                                                                <span class="badge badge-secondary">Inactive</span>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td style="font-size:.78rem;"><?= date('d M Y', strtotime($va['created_at'])) ?></td>
                                                        <td class="text-center">
                                                            <?php if ($va['is_active']): ?>
                                                            <button class="btn btn-xs btn-outline-danger rounded-pill px-3"
                                                                onclick="deactivateDVA(<?= $va['id'] ?>)">
                                                                <i class="fas fa-ban"></i> Deactivate
                                                            </button>
                                                            <?php else: ?>
                                                            <span class="text-muted" style="font-size:.75rem;">—</span>
                                                            <?php endif; ?>
                                                        </td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    <?php endif; ?>

                                    <div id="dva-deactivate-msg" class="mb-3" style="display:none;"></div>

                                    <!-- Create new virtual account -->
                                    <h6 class="font-weight-bold mb-3"><i class="fas fa-plus-circle text-primary mr-2"></i> Create New Virtual Account</h6>
                                    <form method="POST">
                                        <div class="row">
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label class="font-weight-bold" style="font-size:.8rem;text-transform:uppercase;">Payment Type</label>
                                                    <select name="payment_type" id="payment_type" class="form-control" required>
                                                        <option value="">-- Select Type --</option>
                                                        <?php foreach ($paymentTypes as $key => $label): ?>
                                                        <option value="<?= $key ?>"><?= $label ?></option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label class="font-weight-bold" style="font-size:.8rem;text-transform:uppercase;">First Name</label>
                                                    <input type="text" name="customer_name" class="form-control" placeholder="e.g. Entrance" required>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label class="font-weight-bold" style="font-size:.8rem;text-transform:uppercase;">Last Name</label>
                                                    <input type="text" name="customer_last" class="form-control" placeholder="e.g. Form" required>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label class="font-weight-bold" style="font-size:.8rem;text-transform:uppercase;">Contact Email</label>
                                                    <input type="email" name="customer_email" class="form-control" placeholder="school@example.com" required>
                                                    <small class="text-muted">Use different email for each account</small>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label class="font-weight-bold" style="font-size:.8rem;text-transform:uppercase;">Phone Number</label>
                                                    <input type="text" name="customer_phone" class="form-control" placeholder="+2348012345678" required>
                                                    <small class="text-muted">Include country code, e.g. +234...</small>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label class="font-weight-bold" style="font-size:.8rem;text-transform:uppercase;">Preferred Bank</label>
                                                    <select name="preferred_bank" id="preferred_bank" class="form-control" required>
                                                        <option value="">-- Select Bank --</option>
                                                        <?php foreach ($availableBanks as $bank): ?>
                                                        <option value="<?= htmlspecialchars($bank['slug'] ?? $bank['provider_slug'] ?? '') ?>">
                                                            <?= htmlspecialchars($bank['bank_name'] ?? $bank['name'] ?? '') ?>
                                                        </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                        <button type="submit" name="create_va" class="btn btn-primary">
                                            <i class="fas fa-plus-circle mr-1"></i> Create Virtual Account
                                        </button>
                                    </form>

                                </div>
                            </div>

                        </div>
                    </div>
                </div>
            </section>
            <!-- ===== END VIRTUAL ACCOUNT MANAGER ===== -->

            <section class="content">

                <div class="container-fluid">

                    <div class="row">

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

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



                                    <div class="mb-6">

                                        <div class="bg-gradient-to-br from-slate-800 to-slate-900 rounded-3xl p-6 text-white shadow-lg flex items-center justify-between border-b-4 border-blue-500">

                                            <div>

                                                <p class="text-slate-400 text-xs font-bold uppercase tracking-widest">Available System Liquidity</p>

                                                <h2 class="text-4xl font-black mt-1">₦<?php echo number_format($total_liquidity, 2); ?></h2>

                                                <div class="mt-2 text-xs flex gap-4">

                                                    <span class="text-emerald-400">Total Deposits: ₦<?php echo number_format($total_in, 2); ?></span>

                                                    <span class="text-rose-400">Total Payments: ₦<?php echo number_format($total_out, 2); ?></span>

                                                </div>

                                            </div>

                                            <div class="text-5xl text-blue-500 opacity-50">

                                                <i class="fas fa-chart-line"></i>

                                            </div>

                                        </div>

                                    </div>



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

                                        <?php

                                        $dashboard_items = [

                                            ["label" => "FUND WALLET", "desc" => "Manual Credit", "icon" => "fas fa-university", "bg" => "bg-blue-50", "text" => "text-blue-600", "link" => "fund_wallet.php"],

                                            ["label" => "TRANSFER FUNDS", "desc" => "Inter-Wallet Transfer", "icon" => "fas fa-exchange-alt", "bg" => "bg-rose-50", "text" => "text-rose-600", "link" => "transfer_funds.php"],

                                            ["label" => "LOGS", "desc" => "Audit Trail", "icon" => "fas fa-history", "bg" => "bg-emerald-50", "text" => "text-emerald-600", "link" => "wallet_logs.php"],

                                            ["label" => "SETTINGS", "desc" => "Wallet Limits", "icon" => "fas fa-cog", "bg" => "bg-amber-50", "text" => "text-amber-600", "link" => "wallet_settings.php"],

                                        ];



                                        foreach ($dashboard_items as $item) { ?>

                                            <div class="bento-card group cursor-pointer" onclick="window.location.href='<?php echo $item['link']; ?>'">

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

                                                    <div class="w-10 h-10 <?php echo $item['bg']; ?> <?php echo $item['text']; ?> rounded-xl flex items-center justify-center text-base transition-all group-hover:rotate-12">

                                                        <i class="<?php echo $item['icon']; ?>"></i>

                                                    </div>

                                                    <span class="text-slate-300 group-hover:text-blue-500 transition-colors"><i class="fas fa-external-link-alt fa-xs"></i></span>

                                                </div>

                                                <h5 class="text-[14px] font-bold text-slate-700 tracking-tight uppercase"><?php echo $item['label']; ?></h5>

                                                <p class="text-[10px] font-medium text-slate-400 uppercase"><?php echo $item['desc']; ?></p>

                                            </div>

                                        <?php } ?>

                                    </div>



                                    <div class="card card-outline card-primary shadow-sm rounded-2xl overflow-hidden border-0">

                                        <div class="card-header text-white py-4 flex flex-col md:flex-row justify-between items-center gap-4">

                                            <h3 class="card-title font-weight-bold"><i class="fas fa-list mr-2"></i> Student Balances</h3>

                                            <div class="card-tools w-full md:w-auto">

                                                <form method="GET">

                                                    <div class="input-group input-group-sm">

                                                        <input type="text" name="search" class="form-control rounded-l-lg border-slate-200" placeholder="Search ID, Name..." value="<?php echo htmlspecialchars($search); ?>">

                                                        <div class="input-group-append">

                                                            <button type="submit" class="btn btn-primary rounded-r-lg"><i class="fas fa-search"></i></button>

                                                        </div>

                                                    </div>

                                                </form>

                                            </div>

                                        </div>



                                        <div class="card-body p-0">

                                            <div class="block md:hidden p-4 space-y-4">

                                                <?php 

                                                if(mysqli_num_rows($result) > 0):

                                                    while ($row = mysqli_fetch_assoc($result)): 

                                                        $bal = (float)$row['balance'];

                                                        $status_class = ($bal > 0) ? 'text-emerald-600 bg-emerald-50' : (($bal < 0) ? 'text-rose-600 bg-rose-50' : 'text-slate-400 bg-slate-50');

                                                ?>

                                                    <div class="bg-white border border-slate-200 rounded-2xl p-4 shadow-sm">

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

                                                            <div>

                                                                <div class="font-bold text-slate-800 text-lg"><?php echo htmlspecialchars($row['studentName']); ?></div>

                                                                <div class="text-xs text-slate-500 font-mono">ADM: <?php echo htmlspecialchars($row['studentno']); ?></div>

                                                            </div>

                                                            <div class="px-3 py-1 rounded-full font-bold text-sm <?php echo $status_class; ?>">

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

                                                            </div>

                                                        </div>

                                                        <div class="text-sm text-slate-600 mb-4 flex items-center">

                                                            <span class="badge badge-light border mr-2"><?php echo htmlspecialchars($row['class'] . " " . $row['section']); ?></span>

                                                        </div>

                                                        <div class="grid grid-cols-3 gap-2">

                                                            <a href="fund_wallet.php?id=<?php echo $row['student_id']; ?>" class="flex flex-col items-center justify-center p-2 bg-blue-50 text-blue-600 rounded-xl text-[10px] font-bold uppercase">

                                                                <i class="fas fa-plus-circle mb-1 text-base"></i> Fund

                                                            </a>

                                                            <a href="wallet_pay_fee.php?id=<?php echo $row['student_id']; ?>" class="flex flex-col items-center justify-center p-2 bg-emerald-50 text-emerald-600 rounded-xl text-[10px] font-bold uppercase <?php if($bal <= 0) echo 'opacity-50 pointer-events-none'; ?>">

                                                                <i class="fas fa-money-bill-wave mb-1 text-base"></i> Pay

                                                            </a>

                                                            <a href="wallet_history.php?id=<?php echo $row['student_id']; ?>" class="flex flex-col items-center justify-center p-2 bg-slate-50 text-slate-600 rounded-xl text-[10px] font-bold uppercase">

                                                                <i class="fas fa-history mb-1 text-base"></i> Logs

                                                            </a>

                                                        </div>

                                                    </div>

                                                <?php endwhile; 

                                                endif; ?>

                                            </div>



                                            <div class="hidden md:block table-responsive">

                                                <table class="table table-hover align-middle mb-0">

                                                    <thead class="bg-slate-50 text-slate-500 uppercase text-xs">

                                                        <tr>

                                                            <th class="px-6 py-3">Student Info</th>

                                                            <th>Class Detail</th>

                                                            <th>Wallet Balance</th>

                                                            <th class="text-center">Action</th>

                                                        </tr>

                                                    </thead>

                                                    <tbody>

                                                        <?php 

                                                        mysqli_data_seek($result, 0); // Reset pointer for second loop

                                                        while ($row = mysqli_fetch_assoc($result)): 

                                                            $bal = (float)$row['balance'];

                                                            $status_class = ($bal > 0) ? 'text-emerald-600 bg-emerald-50' : (($bal < 0) ? 'text-rose-600 bg-rose-50' : 'text-slate-400 bg-slate-50');

                                                        ?>

                                                            <tr>

                                                                <td class="px-6">

                                                                    <div class="font-bold text-dark"><?php echo htmlspecialchars($row['studentName']); ?></div>

                                                                    <div class="text-xs text-muted">ADM No: <?php echo htmlspecialchars($row['studentno']); ?></div>

                                                                </td>

                                                                <td><span class="badge badge-light border"><?php echo htmlspecialchars($row['class'] . " " . $row['section']); ?></span></td>

                                                                <td>

                                                                    <div class="inline-block px-3 py-1 rounded-full font-bold <?php echo $status_class; ?>">

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

                                                                    </div>

                                                                </td>

                                                                <td class="text-center">

                                                                    <a href="fund_wallet.php?id=<?php echo $row['student_id']; ?>" class="btn btn-xs btn-primary px-3 rounded-pill shadow-sm"><i class="fas fa-plus-circle"></i> Fund</a>

                                                                    <a href="wallet_pay_fee.php?id=<?php echo $row['student_id']; ?>" class="btn btn-xs btn-success px-3 rounded-pill shadow-sm ml-1 <?php if($bal <= 0) echo 'disabled'; ?>"><i class="fas fa-money-bill-wave"></i> Pay Fee</a>

                                                                    <a href="wallet_history.php?id=<?php echo $row['student_id']; ?>" class="btn btn-xs btn-outline-secondary px-3 rounded-pill ml-1">Logs</a>

                                                                </td>

                                                            </tr>

                                                        <?php endwhile; ?>

                                                    </tbody>

                                                </table>

                                            </div>

                                            

                                            <?php if(mysqli_num_rows($result) == 0): ?>

                                                <div class="text-center py-10 text-muted">No student wallet records found.</div>

                                            <?php endif; ?>

                                        </div>



                                        <div class="card-footer bg-white py-4">

                                            <div class="flex flex-col md:flex-row justify-between items-center gap-4">

                                                <div class="text-xs text-slate-500 order-2 md:order-1">

                                                    Showing <b><?php echo $total_rows > 0 ? ($offset + 1) : 0; ?></b> to <b><?php echo min($offset + $limit, $total_rows); ?></b> of <b><?php echo $total_rows; ?></b> entries

                                                </div>

                                                <nav class="order-1 md:order-2">

                                                    <ul class="pagination pagination-sm mb-0 flex-wrap justify-center">

                                                        <li class="page-item <?php if($page <= 1) echo 'disabled'; ?>">

                                                            <a class="page-link" href="?page=<?php echo $page-1; ?>&search=<?php echo urlencode($search); ?>"><i class="fas fa-chevron-left"></i></a>

                                                        </li>

                                                        <?php 

                                                        $range = 1;

                                                        for($i = 1; $i <= $total_pages; $i++): 

                                                            if($i == 1 || $i == $total_pages || ($i >= $page - $range && $i <= $page + $range)):

                                                        ?>

                                                            <li class="page-item <?php echo ($page == $i) ? 'active' : ''; ?>">

                                                                <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>"><?php echo $i; ?></a>

                                                            </li>

                                                        <?php elseif($i == $page - $range - 1 || $i == $page + $range + 1): ?>

                                                            <li class="page-item disabled"><span class="page-link">...</span></li>

                                                        <?php endif; endfor; ?>

                                                        <li class="page-item <?php if($page >= $total_pages) echo 'disabled'; ?>">

                                                            <a class="page-link" href="?page=<?php echo $page+1; ?>&search=<?php echo urlencode($search); ?>"><i class="fas fa-chevron-right"></i></a>

                                                        </li>

                                                    </ul>

                                                </nav>

                                            </div>

                                        </div>

                                    </div>

                                </div>

                            </div>

                        </div>

                    </div>

                </div>

            </section>


        </div>



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

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

    </div>
    <script>
        $(document).ready(function () {
            $('#preferred_bank, #payment_type').select2({
                allowClear: true,
                placeholder: '-- Select --'
            });
        });
    </script>
<script>
function createDVA() {
    var customerCode  = document.getElementById('dva-customer-code').value.trim();
    var preferredBank = document.getElementById('dva-preferred-bank').value;
    var msgEl         = document.getElementById('dva-create-msg');

    if (!customerCode) {
        msgEl.style.display = 'block';
        msgEl.innerHTML = '<div class="alert alert-warning">Please enter a Paystack customer code.</div>';
        return;
    }

    msgEl.style.display = 'block';
    msgEl.innerHTML = '<div class="alert alert-info"><i class="fas fa-spinner fa-spin mr-2"></i> Creating virtual account...</div>';

    $.ajax({
        url: 'create_virtual_account.php',
        method: 'POST',
        data: { customer_code: customerCode, preferred_bank: preferredBank },
        dataType: 'json',
        success: function(res) {
            if (res.status === 'success') {
                msgEl.innerHTML = '<div class="alert alert-success"><i class="fas fa-check-circle mr-2"></i> Virtual account created successfully. Reloading...</div>';
                setTimeout(function() { location.reload(); }, 1500);
            } else {
                msgEl.innerHTML = '<div class="alert alert-danger"><i class="fas fa-exclamation-circle mr-2"></i> ' + (res.message || 'Unknown error') + '</div>';
            }
        },
        error: function() {
            msgEl.innerHTML = '<div class="alert alert-danger">Request failed. Please try again.</div>';
        }
    });
}

function deactivateDVA(id) {
    if (!confirm('Are you sure you want to deactivate this virtual account? Students will no longer see the bank transfer option.')) return;

    var msgEl = document.getElementById('dva-deactivate-msg');
    msgEl.style.display = 'block';
    msgEl.innerHTML = '<div class="alert alert-info"><i class="fas fa-spinner fa-spin mr-2"></i> Deactivating...</div>';

    $.ajax({
        url: 'delete_virtual_account.php',
        method: 'POST',
        data: { id: id },
        dataType: 'json',
        success: function(res) {
            if (res.status === 'success') {
                msgEl.innerHTML = '<div class="alert alert-success"><i class="fas fa-check-circle mr-2"></i> Account deactivated. Reloading...</div>';
                setTimeout(function() { location.reload(); }, 1500);
            } else {
                msgEl.innerHTML = '<div class="alert alert-danger"><i class="fas fa-exclamation-circle mr-2"></i> ' + (res.message || 'Unknown error') + '</div>';
            }
        },
        error: function() {
            msgEl.innerHTML = '<div class="alert alert-danger">Request failed. Please try again.</div>';
        }
    });
}
</script>
    <script>
        $(document).ready(function () {
            $('#student_select').select2({
                placeholder: "Search account byname or ADM number",
                allowClear: true
            });
        });
    </script>

</body>

</html>