<?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();

include('includes/dbconnection.php');
require_once 'includes/session_term_helper.php';
$stResult = resolveCurrentSessionTerm($con);
$currentSessionName = $stResult['session_name'];
$currentTermName    = $stResult['term_name'];




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

    header('location:logout.php');

    exit;

}



// --- AJAX ENDPOINT FOR BALANCE CHECK ---

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

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

    $res = mysqli_query($con, "SELECT balance FROM wallets WHERE student_id = $sid");

    $row = mysqli_fetch_assoc($res);

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

    exit;

}



$msg = "";

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

    $from_id = filter_var($_POST['from_student_id'], FILTER_VALIDATE_INT);

    $to_id = filter_var($_POST['to_student_id'], FILTER_VALIDATE_INT);

    $amount = filter_var($_POST['amount'], FILTER_VALIDATE_FLOAT);

    $remark = htmlspecialchars(trim($_POST['remark']));

    $admin_id = $_SESSION['sid']; 

    $base_ref = "TRF-ADM-" . strtoupper(bin2hex(random_bytes(4)));



    if (!$from_id || !$to_id || $from_id === $to_id) {

        $msg = "<div class='alert alert-danger'>Invalid transfer participants.</div>";

    } elseif ($amount <= 0) {

        $msg = "<div class='alert alert-danger'>Amount must be positive.</div>";

    } else {

        $con->begin_transaction();

        try {

            // A. Lock Sender

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

            $stmt->bind_param("i", $from_id);

            $stmt->execute();

            $sender_bal = $stmt->get_result()->fetch_assoc()['balance'] ?? 0;



            if ($sender_bal < $amount) {

                throw new Exception("Insufficient Funds. Current: ₦" . number_format($sender_bal, 2));

            }



            // B. Updates

            $con->query("UPDATE wallets SET balance = balance - $amount WHERE student_id = $from_id");

            $con->query("UPDATE wallets SET balance = balance + $amount WHERE student_id = $to_id");



            // C. LOGS (Fixed Duplicate Reference Error by adding suffixes)

            $log = $con->prepare("INSERT INTO wallet_transactions (student_id, amount, type, status, reference, notes) VALUES (?, ?, ?, 'success', ?, ?)");

            

            // Log Debit

            $type_out = "Transfer Out";

            $ref_out = $base_ref . "-DR"; 

            $note_out = "Sent to ID: $to_id. $remark";

            $log->bind_param("idsss", $from_id, $amount, $type_out, $ref_out, $note_out);

            $log->execute();



            // Log Credit

            $type_in = "Transfer In";

            $ref_in = $base_ref . "-CR";

            $note_in = "Received from ID: $from_id. $remark";

            $log->bind_param("idsss", $to_id, $amount, $type_in, $ref_in, $note_in);

            $log->execute();



            $con->commit();

            $msg = "<div class='alert alert-success bg-emerald-600 text-white border-0 shadow-lg'>Transfer Successful! Ref: $base_ref</div>";

        } catch (Exception $e) {

            $con->rollback();

            $msg = "<div class='alert alert-danger'>Transaction Failed: " . $e->getMessage() . "</div>";

        }

    }

}

?>



<!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 { @apply text-[10px] font-bold px-2 py-0.5 rounded-md mt-1 inline-block; }

    </style>

</head>

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

    <div class="wrapper">

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

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



        <div class="content-wrapper">

            <!-- Content Header (Page header) -->

<section class="content-header premium-header">

    <div class="container-fluid">

        <div class="header-glass-card">

            <div class="row align-items-center">

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

                    <div class="title-section">

                        <div class="icon-box bg-primary-gradient shadow-sm">

                            <i class="fas fa-wallet"></i>

                        </div>

                        <div>

                            <h1 class="premium-title text-primary">

                                Wallet Management

                                <span class="premium-subtitle text-secondary">Transfer Fund</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"><a href="manage_wallet.php" class="text-primary">Wallet Manager</a></li>

                            <li class="breadcrumb-item active" aria-current="page">Transfer</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> Inter Wallet Transfer

                    </h5>

                  </div>

                  <div class="card-body">

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

                <?php echo $msg; ?>

                

                <div class="bg-white rounded-[2.5rem] border border-slate-100 shadow-2xl shadow-blue-100/40 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">Inter-Account Secure Protocol</p>

                        </div>

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

                    </div>



                    <form method="POST" class="p-10">

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

                            <div class="relative">

                                <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 = mysqli_query($con, "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 = mysqli_fetch_assoc($allStudents)) {

                                        echo "<option value='".$s['id']."'>".$s['studentName']." (".$s['studentno'].")</option>";

                                    }

                                    ?>

                                </select>

                                <div id="sender_bal_display" class="balance-badge bg-rose-50 text-rose-600 hidden">

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

                                </div>

                            </div>



                            <div class="relative">

                                <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 mysqli_data_seek($allStudents, 0); 

                                    while($s = mysqli_fetch_assoc($allStudents)) {

                                        echo "<option value='".$s['id']."'>".$s['studentName']." (".$s['studentno'].")</option>";

                                    } ?>

                                </select>

                                <div id="receiver_bal_display" class="balance-badge bg-emerald-50 text-emerald-600 hidden">

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

                                </div>

                            </div>

                        </div>



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

                            <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" 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="pt-4 space-y-4">

                                <button type="submit" name="transfer_btn" class="w-full bg-slate-900 text-white py-6 rounded-2xl font-black text-sm uppercase tracking-widest hover:bg-blue-600 transition-all shadow-xl shadow-blue-100 active:scale-[0.97] flex items-center justify-center gap-2">

                                    <i class="fas fa-lock text-blue-400"></i> Confirm & Authorize Transfer

                                </button>

                            </div>

                        </div>

                    </form>

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

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

                                    <span class="text-slate-200">|</span>

                                    <a href="wallet_logs.php" class="text-xs font-bold text-slate-400 hover:text-blue-500 uppercase tracking-widest transition-colors">View Recent Logs</a>

                                </div>                </div>

            </div>

        </section>

    </div>

</div>

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



<?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: '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>