<?php
// Includes
include('includes/session.php');
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'];

$student_id = $_SESSION['student_id'];

// 3. SECURE FETCH: Wallet & Student Details (Using Prepared Statements)
$stmt = $con->prepare("SELECT * FROM wallets WHERE student_id = ?");
$stmt->bind_param("i", $student_id);
$stmt->execute();
$wallet = $stmt->get_result()->fetch_assoc();
$stmt->close();

$stmt = $con->prepare("SELECT studentName, email FROM students WHERE id = ?");
$stmt->bind_param("i", $student_id);
$stmt->execute();
$student = $stmt->get_result()->fetch_assoc();
$stmt->close();

// 4. Fetch History
$history_stmt = $con->prepare("SELECT * FROM wallet_transactions WHERE student_id = ? ORDER BY created_at DESC LIMIT 10");
$history_stmt->bind_param("i", $student_id);
$history_stmt->execute();
$history_query = $history_stmt->get_result();

// Fintech Check: Is PIN set?
$isPinSet = $wallet['is_pin_set'] ?? 0;

// Settings: transfers enabled?
require_once 'includes/wallet_helpers.php';
$transfersEnabled = (int) getWalletSetting($con, 'transfers_enabled', 1);
?>

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


<body class="hold-transition sidebar-mini layout-fixed bg-slate-50">
    <div class="wrapper">

        <?php @include("includes/headerstd.php"); ?>
        <?php @include("includes/sidebaroldstd.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">Wallet & History</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="oldstdday.php"
                                                class="text-primary">Home</a></li>
                                        <li class="breadcrumb-item active" aria-current="page">Wallet History</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">

                                    <?php if (isset($_GET['status'])): ?>
                                        <div
                                            class="<?php echo $_GET['status'] == 'success' ? 'bg-green-100 border-green-400 text-green-700' : 'bg-red-100 border-red-400 text-red-700'; ?> px-4 py-3 rounded-xl border mb-4 relative shadow-sm">
                                            <strong class="font-bold"><?php echo ucfirst($_GET['status']); ?>!</strong>
                                            <span><?php echo htmlspecialchars($_GET['message'] ?? ''); ?></span>
                                        </div>
                                    <?php endif; ?>

                                    <?php if (!$wallet || empty($wallet['account_number'])): ?>
                                        <div
                                            class="bg-white rounded-3xl p-10 text-center shadow-lg border border-slate-100">
                                            <div
                                                class="w-16 h-16 bg-blue-50 text-blue-600 rounded-full flex items-center justify-center mx-auto mb-4">
                                                <i class="fas fa-university text-2xl"></i>
                                            </div>
                                            <h2 class="text-2xl font-bold text-slate-800">Activate Your Wallet</h2>
                                            <p class="text-slate-500 mb-6">Generate a virtual account to fund your wallet
                                                instantly.</p>
                                            <form action="generate_wallet.php" method="POST">
                                                <button type="submit" name="activate"
                                                    class="bg-blue-600 text-white px-8 py-3 rounded-xl font-bold hover:bg-blue-700 shadow-md transition-all">
                                                    Generate Virtual Account
                                                </button>
                                            </form>
                                        </div>
                                    <?php else: ?>
                                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
                                            <div
                                                class="bg-slate-900 rounded-3xl p-8 text-white shadow-xl relative overflow-hidden flex flex-col justify-between">
                                                <div>
                                                    <p class="text-slate-400 text-xs font-bold uppercase tracking-widest">
                                                        Available Balance</p>
                                                    <div class="flex items-center gap-4 mt-2">
                                                        <h1 id="balanceText" class="text-4xl font-black tracking-tight">
                                                            ₦<?php echo number_format($wallet['balance'], 2); ?></h1>
                                                        <h1 id="balanceHidden" class="text-4xl font-black hidden">******
                                                        </h1>
                                                        <button onclick="toggleBalance()"
                                                            class="text-slate-400 hover:text-white accNum"><i id="eyeIcon"
                                                                class="fas fa-eye"></i></button>
                                                    </div>
                                                </div>

                                                <?php if ($transfersEnabled): ?>
                                                    <button onclick="handleTransfer()"
                                                        class="mt-6 bg-blue-600 hover:bg-blue-500 text-white py-3 rounded-2xl font-bold transition-all flex items-center justify-center gap-2 shadow-lg accNum">
                                                        <i class="fas fa-paper-plane"></i> Send Money (Wallet to Wallet)
                                                    </button>
                                                <?php else: ?>
                                                    <div class="mt-6 bg-slate-700 text-slate-400 py-3 rounded-2xl font-bold flex items-center justify-center gap-2 cursor-not-allowed select-none"
                                                        title="Transfers are currently disabled by the administrator">
                                                        <i class="fas fa-ban"></i> Transfers Disabled
                                                    </div>
                                                <?php endif; ?>

                                                <i
                                                    class="fas fa-wallet absolute right-[-20px] bottom-[-20px] text-white opacity-5 text-9xl rotate-12"></i>
                                            </div>

                                            <div class="bg-white rounded-3xl p-8 border border-slate-200 shadow-sm">
                                                <p class="text-slate-400 text-xs font-bold uppercase mb-4">Inbound Bank
                                                    Transfer</p>
                                                <div class="space-y-3">
                                                    <div>
                                                        <p class="text-slate-500 text-[10px] uppercase font-bold">Bank Name
                                                        </p>
                                                        <p class="font-bold text-slate-800">
                                                            <?php echo strtoupper($wallet['bank_name']); ?></p>
                                                    </div>
                                                    <div>
                                                        <p class="text-slate-500 text-[10px] uppercase font-bold">Account
                                                            Name</p>
                                                        <p class="font-bold text-slate-800">
                                                            <?php echo strtoupper($wallet['account_name']); ?></p>
                                                    </div>
                                                    <div class="relative">
                                                        <p class="text-slate-500 text-[10px] uppercase font-bold">Account
                                                            Number</p>
                                                        <div class="flex items-center gap-2">
                                                            <p id="accNum"
                                                                class="text-2xl font-black text-blue-600 tracking-tighter">
                                                                <?php echo $wallet['account_number']; ?></p>
                                                            <button onclick="copyAccountNumber()"
                                                                class="text-slate-400 hover:text-blue-600 accNum"><i
                                                                    class="fas fa-copy"></i></button>
                                                        </div>
                                                        <span id="copyToast"
                                                            class="absolute left-0 -bottom-4 text-[10px] text-green-600 font-bold opacity-0 transition-opacity">Copied!</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="bg-white rounded-3xl p-6 shadow-sm border border-slate-100">
                                            <div class="flex justify-between items-center mb-6">
                                                <h3 class="font-bold text-slate-800">Transaction History</h3>
                                                <i class="fas fa-sliders-h text-slate-400"></i>
                                            </div>
                                            <div class="overflow-x-auto">
                                                <table class="w-full text-left text-sm">
                                                    <thead class="text-slate-400 border-b">
                                                        <tr>
                                                            <th class="pb-3">Date</th>
                                                            <th class="pb-3">Type</th>
                                                            <th class="pb-3 text-right">Amount</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody class="divide-y divide-slate-50">
                                                        <?php while ($row = $history_query->fetch_assoc()): ?>
                                                            <tr>
                                                                <td class="py-4 text-slate-600 text-xs">
                                                                    <?php echo date('d M, Y', strtotime($row['created_at'])); ?><br>
                                                                    <span
                                                                        class="text-[10px] font-mono text-slate-400"><?php echo $row['reference']; ?></span>
                                                                </td>
                                                                <td class="py-4">
                                                                    <span
                                                                        class="px-2 py-1 rounded-lg text-[9px] font-bold uppercase <?php echo ($row['type'] == 'deposit') ? 'bg-green-50 text-green-600' : 'bg-red-50 text-red-600'; ?>">
                                                                        <?php echo $row['type']; ?>
                                                                    </span>
                                                                </td>
                                                                <td
                                                                    class="py-4 text-right font-bold <?php echo ($row['type'] == 'deposit') ? 'text-green-600' : 'text-slate-800'; ?>">
                                                                    <?php echo ($row['type'] == 'deposit') ? '+' : '-'; ?>₦<?php echo number_format($row['amount'], 2); ?>
                                                                </td>
                                                            </tr>
                                                        <?php endwhile; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
            </section>
        </div>

        <div id="pinSetupModal"
            class="fixed inset-0 bg-slate-900/60 backdrop-blur-sm hidden items-center justify-center z-[1000] p-4">
            <div class="bg-white rounded-3xl max-w-sm w-full p-8 shadow-2xl">
                <div class="text-center mb-6">
                    <div
                        class="w-16 h-16 bg-orange-50 text-orange-500 rounded-full flex items-center justify-center mx-auto mb-4">
                        <i class="fas fa-lock text-2xl"></i>
                    </div>
                    <h3 class="text-xl font-bold text-slate-800">Set Transaction PIN</h3>
                    <p class="text-slate-500 text-sm">This PIN will be required for all transfers.</p>
                </div>
                <form action="process_pin_setup.php" method="POST" class="space-y-4">
                    <input type="password" name="new_pin" maxlength="4" pattern="\d{4}" required
                        class="w-full border-2 border-slate-100 p-4 rounded-2xl text-center text-3xl tracking-[1em] focus:border-blue-500 outline-none"
                        placeholder="****">
                    <button type="submit"
                        class="w-full bg-slate-900 text-white py-4 rounded-2xl font-bold hover:bg-black transition-all accNum">Create
                        My PIN</button>
                    <button type="button" onclick="closeModals()"
                        class="w-full text-slate-400 text-sm font-bold accNum">Cancel</button>
                </form>
            </div>
        </div>

        <div id="transferModal"
            class="fixed inset-0 bg-slate-900/60 backdrop-blur-sm hidden items-center justify-center z-[1000] p-4">
            <div class="bg-white rounded-3xl max-w-md w-full p-8 shadow-2xl">
                <h3 class="text-xl font-bold text-slate-800 mb-6 flex items-center gap-2">
                    <i class="fas fa-paper-plane text-blue-600"></i> Transfer Funds
                </h3>
                <form action="process_transfer_init.php" method="POST" class="space-y-4" id="transferForm">
                    <div>
                        <label class="text-[10px] font-bold text-slate-400 uppercase ml-1">Recipient Account
                            Number</label>
                        <input type="text" id="recipient_acc" name="recipient_acc" required autocomplete="off"
                            class="w-full border border-slate-200 p-4 rounded-2xl focus:ring-2 focus:ring-blue-500 outline-none transition-all"
                            placeholder="Enter Account Number">

                        <div id="account_verify_display" class="mt-2 px-1 hidden">
                            <div class="flex items-center gap-2">
                                <div id="verify_loader"
                                    class="hidden animate-spin h-3 w-3 border-2 border-blue-600 border-t-transparent rounded-full">
                                </div>
                                <p id="recipient_name" class="text-xs font-bold text-blue-600 italic"></p>
                            </div>
                        </div>
                    </div>

                    <div>
                        <label class="text-[10px] font-bold text-slate-400 uppercase ml-1">Amount (₦)</label>
                        <input type="number" name="amount" id="transfer_amount" required min="100"
                            class="w-full border border-slate-200 p-4 rounded-2xl focus:ring-2 focus:ring-blue-500 outline-none"
                            placeholder="0.00">
                    </div>

                    <p class="text-[10px] text-slate-400 italic">Next step: 2FA Verification (OTP & PIN)</p>

                    <button type="submit" id="btn_continue_transfer" disabled
                        class="w-full bg-slate-200 text-slate-400 py-4 rounded-2xl font-bold cursor-not-allowed transition-all shadow-lg accNum">
                        Continue
                    </button>
                    <button type="button" onclick="closeModals()"
                        class="w-full text-slate-400 text-sm font-bold mt-2 accNum">Cancel</button>
                </form>
            </div>
        </div>

        <script>
            const isPinSet = <?php echo $isPinSet; ?>;

            function handleTransfer() {
                if (isPinSet == 0) {
                    document.getElementById('pinSetupModal').classList.remove('hidden');
                    document.getElementById('pinSetupModal').classList.add('flex');
                } else {
                    document.getElementById('transferModal').classList.remove('hidden');
                    document.getElementById('transferModal').classList.add('flex');
                }
            }

            function closeModals() {
                document.getElementById('pinSetupModal').classList.add('hidden');
                document.getElementById('transferModal').classList.add('hidden');
                document.getElementById('transferForm').reset();
                resetVerifyUI();
                if (currentController) { currentController.abort(); currentController = null; }
                clearTimeout(debounceTimer);
            }

            function toggleBalance() {
                const txt = document.getElementById('balanceText');
                const hid = document.getElementById('balanceHidden');
                const icon = document.getElementById('eyeIcon');
                txt.classList.toggle('hidden');
                hid.classList.toggle('hidden');
                icon.classList.toggle('fa-eye');
                icon.classList.toggle('fa-eye-slash');
            }

            function copyAccountNumber() {
                const num = document.getElementById('accNum').innerText;
                navigator.clipboard.writeText(num).then(() => {
                    const toast = document.getElementById('copyToast');
                    toast.style.opacity = '1';
                    setTimeout(() => toast.style.opacity = '0', 2000);
                });
            }
            // Verification Logic
            const accInput = document.getElementById('recipient_acc');
            const nameDisplay = document.getElementById('account_verify_display');
            const nameText = document.getElementById('recipient_name');
            const loader = document.getElementById('verify_loader');
            const submitBtn = document.getElementById('btn_continue_transfer');

            let debounceTimer = null;
            let currentController = null;

            function resetVerifyUI() {
                nameDisplay.classList.add('hidden');
                submitBtn.disabled = true;
                submitBtn.className = "w-full bg-slate-200 text-slate-400 py-4 rounded-2xl font-bold cursor-not-allowed transition-all";
            }

            accInput.addEventListener('input', function () {
                const accNum = this.value.trim();

                // Cancel any in-flight request
                if (currentController) {
                    currentController.abort();
                    currentController = null;
                }

                // Clear pending debounce
                clearTimeout(debounceTimer);

                if (accNum.length < 5) {
                    resetVerifyUI();
                    return;
                }

                // Show loading state immediately
                nameDisplay.classList.remove('hidden');
                loader.classList.remove('hidden');
                nameText.innerText = "Verifying account...";
                nameText.className = "text-xs font-bold text-slate-400 italic";

                // Debounce: wait 500ms after user stops typing
                debounceTimer = setTimeout(() => {
                    currentController = new AbortController();

                    fetch(`verify_account_api.php?account_number=${encodeURIComponent(accNum)}&own_account=<?php echo $wallet['account_number']; ?>`, {
                        signal: currentController.signal
                    })
                        .then(response => response.json())
                        .then(data => {
                            loader.classList.add('hidden');
                            currentController = null;
                            if (data.success) {
                                nameText.innerText = `Recipient: ${data.name}`;
                                nameText.className = "text-xs font-bold text-green-600 italic";
                                submitBtn.disabled = false;
                                submitBtn.className = "w-full bg-blue-600 text-white py-4 rounded-2xl font-bold hover:bg-blue-700 shadow-lg transition-all";
                            } else {
                                nameText.innerText = "Account not found";
                                nameText.className = "text-xs font-bold text-red-500 italic";
                                submitBtn.disabled = true;
                                submitBtn.className = "w-full bg-slate-200 text-slate-400 py-4 rounded-2xl font-bold cursor-not-allowed transition-all";
                            }
                        })
                        .catch(error => {
                            if (error.name === 'AbortError') return; // Ignore cancelled requests
                            console.error('Error:', error);
                            loader.classList.add('hidden');
                            nameText.innerText = "Verification failed. Try again.";
                            nameText.className = "text-xs font-bold text-red-500 italic";
                        });
                }, 300);
            });

            const transferForm = document.getElementById('transferForm');

            transferForm.addEventListener('submit', function () {
                // Disable button to prevent double-clicks
                submitBtn.disabled = true;
                submitBtn.innerHTML = '<i class="fas fa-spinner animate-spin"></i> Processing...';
                submitBtn.className = "w-full bg-blue-400 text-white py-4 rounded-2xl font-bold cursor-not-allowed transition-all shadow-lg";
            });
        </script>

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

</html>