<?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 'includes/session_term_helper.php';
$stResult = resolveCurrentSessionTerm($con);
$currentSessionName = $stResult['session_name'];
$currentTermName    = $stResult['term_name'];


require_once 'includes/wallet_helpers.php';



if (empty($_SESSION['sid'])) {

    header('location:logoutsmall.php');

    exit;

}



// AJAX balance endpoint

if (isset($_GET['get_balance'])) {

    $sid = (int)$_GET['get_balance'];

    $res = $con->prepare("SELECT balance FROM wallets WHERE student_id = ?");

    $res->bind_param("i", $sid);

    $res->execute();

    $row = $res->get_result()->fetch_assoc();

    echo number_format($row['balance'] ?? 0, 2);

    exit;

}



$msg = "";

$msg_type = "";



// Handle status redirect messages

if (isset($_GET['status'])) {

    if ($_GET['status'] === 'success') {

        $msg = "Transfer successful! Reference: " . htmlspecialchars($_GET['ref'] ?? '');

        $msg_type = "success";

    } elseif ($_GET['status'] === 'error') {

        $msg = htmlspecialchars($_GET['message'] ?? 'An error occurred.');

        $msg_type = "danger";

    }

}

?>

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

    <style>

        .select2-container--default .select2-selection--single { height:50px; border-radius:15px; border-color:#f1f5f9; padding-top:10px; background:#f8fafc; }

        .balance-badge { font-size:10px; font-weight:700; padding:2px 8px; border-radius:6px; margin-top:4px; display:inline-block; }

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

<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">Transfer Funds</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">Transfer Funds</li>

                        </ol>

                    </nav>

                </div>

            </div>

        </div>

    </div>

</section>



        <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-exchange-alt"></i> Inter-Wallet Fund Transfer

                                </h5>

                            </div>

                            <div class="card-body">

                                <div class="max-w-4xl mx-auto">



                                    <?php if ($msg): ?>

                                    <div class="alert alert-<?= $msg_type ?> alert-dismissible rounded-xl">

                                        <button type="button" class="close" data-dismiss="alert">&times;</button>

                                        <?= $msg ?>

                                    </div>

                                    <?php endif; ?>



                                    <div class="bg-white rounded-[2.5rem] border border-slate-100 shadow-2xl overflow-hidden">

                                        <div class="bg-slate-900 p-8 text-white flex justify-between items-center">

                                            <div>

                                                <h2 class="text-2xl font-black tracking-tight">Wallet Transfer</h2>

                                                <p class="text-slate-400 text-xs uppercase font-bold tracking-widest mt-1">OTP-Secured Inter-Account Transfer</p>

                                            </div>

                                            <i class="fas fa-exchange-alt text-4xl text-blue-500 opacity-30"></i>

                                        </div>



                                        <form method="POST" action="small_process_transfer_otp.php" class="p-8">

                                            <div class="grid grid-cols-1 md:grid-cols-2 gap-8">

                                                <div>

                                                    <label class="text-xs font-black text-slate-400 uppercase mb-2 block">Source (From)</label>

                                                    <select name="from_student_id" id="sender_select" class="select2 w-full" required>

                                                        <option value=""></option>

                                                        <?php

                                                        $allStudents = $con->query("SELECT s.id, s.studentName, s.studentno FROM students s JOIN wallets w ON s.id=w.student_id ORDER BY s.studentName ASC");

                                                        while ($s = $allStudents->fetch_assoc()):

                                                        ?>

                                                        <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['studentName']) ?> (<?= htmlspecialchars($s['studentno']) ?>)</option>

                                                        <?php endwhile; ?>

                                                    </select>

                                                    <div id="sender_bal_display" class="balance-badge bg-rose-50 text-rose-600" style="display:none;">

                                                        Balance: ₦<span class="bal-val">0.00</span>

                                                    </div>

                                                </div>



                                                <div>

                                                    <label class="text-xs font-black text-slate-400 uppercase mb-2 block">Destination (To)</label>

                                                    <select name="to_student_id" id="receiver_select" class="select2 w-full" required>

                                                        <option value=""></option>

                                                        <?php

                                                        $allStudents->data_seek(0);

                                                        while ($s = $allStudents->fetch_assoc()):

                                                        ?>

                                                        <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['studentName']) ?> (<?= htmlspecialchars($s['studentno']) ?>)</option>

                                                        <?php endwhile; ?>

                                                    </select>

                                                    <div id="receiver_bal_display" class="balance-badge bg-emerald-50 text-emerald-600" style="display:none;">

                                                        Balance: ₦<span class="bal-val">0.00</span>

                                                    </div>

                                                </div>

                                            </div>



                                            <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mt-8">

                                                <div class="md:col-span-1">

                                                    <label class="text-xs font-black text-slate-400 uppercase mb-2 block">Amount (₦)</label>

                                                    <input type="number" step="0.01" min="0.01" name="amount"

                                                           class="w-full bg-slate-50 border-0 rounded-2xl p-4 font-bold text-xl focus:ring-2 focus:ring-blue-500 outline-none"

                                                           placeholder="0.00" required>

                                                </div>

                                                <div class="md:col-span-2">

                                                    <label class="text-xs font-black text-slate-400 uppercase mb-2 block">Remark / Reason</label>

                                                    <input type="text" name="remark"

                                                           class="w-full bg-slate-50 border-0 rounded-2xl p-4 focus:ring-2 focus:ring-blue-500 outline-none"

                                                           placeholder="Purpose of transfer" required>

                                                </div>

                                            </div>



                                            <div class="mt-4 p-4 bg-amber-50 border border-amber-200 rounded-2xl text-sm text-amber-800">

                                                <i class="fas fa-shield-alt mr-2 text-amber-500"></i>

                                                An OTP will be sent to the <strong>sender student's email</strong> to confirm this transfer.

                                            </div>



                                            <div class="pt-6">

                                                <button type="submit" class="w-full bg-slate-900 text-white py-5 rounded-2xl font-black text-sm uppercase tracking-widest hover:bg-blue-600 transition-all shadow-xl flex items-center justify-center gap-2">

                                                    <i class="fas fa-paper-plane text-blue-400"></i> Send OTP & Proceed

                                                </button>

                                            </div>

                                        </form>



                                        <div class="flex items-center justify-center gap-6 pb-6">

                                            <a href="dashboard2.php" class="text-xs font-bold text-slate-400 hover:text-rose-500 uppercase tracking-widest transition-colors">Back to Dashboard</a>

                                        </div>

                                    </div>



                                </div>

                            </div>

                        </div>

                    </div>

                </div>

            </div>

        </section>

    </div>



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

</div>

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

<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>

$(document).ready(function () {

    $('.select2').select2({ placeholder: "Search student name or ID..." });



    function fetchBal(studentId, displayId) {

        if (!studentId) { $(displayId).hide(); return; }

        $.ajax({

            url: 'small_transfer_funds.php',

            type: 'GET',

            data: { get_balance: studentId },

            success: function (data) {

                $(displayId).find('.bal-val').text(data);

                $(displayId).fadeIn();

            }

        });

    }



    $('#sender_select').on('change', function () { fetchBal($(this).val(), '#sender_bal_display'); });

    $('#receiver_select').on('change', function () { fetchBal($(this).val(), '#receiver_bal_display'); });

});

</script>

</body>

</html>

