<?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'];
require_once 'includes/wallet_helpers.php';

// Include PHPMailer and QR code libraries
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use Dotenv\Dotenv;

require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';


// Load Composer dependencies
require_once 'vendor/autoload.php';
// Load environment variables
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();

if (strlen($_SESSION['sid'] == 0)) {
    header('location:logout.php');
    exit;
}

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

// Handle Form Submission
if (isset($_POST['submit'])) {
    $target_id = ($student_id > 0) ? $student_id : intval($_POST['student_select']);
    $amount = filter_var($_POST['amount'], FILTER_VALIDATE_FLOAT);
    $notes = mysqli_real_escape_string($con, $_POST['notes']);

    $reference = "ADM-" . strtoupper(dechex(time())) . rand(100, 999);
    $type = "deposit";

    if ($target_id > 0 && $amount > 0) {
        // --- SETTINGS ENFORCEMENT ---
        $funding_enabled = getWalletSetting($con, 'funding_enabled', '1');
        if ($funding_enabled == '0') {
            $msg = "danger|Wallet funding is currently disabled by the system administrator.";
        } else {
            $max_balance = (float) getWalletSetting($con, 'max_balance', 100000);
            // Fetch current balance
            $bal_stmt = $con->prepare("SELECT balance FROM wallets WHERE student_id = ?");
            $bal_stmt->bind_param("i", $target_id);
            $bal_stmt->execute();
            $bal_row = $bal_stmt->get_result()->fetch_assoc();
            $bal_stmt->close();
            $current_balance = (float) ($bal_row['balance'] ?? 0);

            if ($current_balance + $amount > $max_balance) {
                $msg = "danger|This deposit would exceed the maximum wallet balance of ₦" . number_format($max_balance, 2) . ".";
            } else {
                mysqli_begin_transaction($con);
                try {
                    // 1. Update wallet balance with row-level locking for concurrency safety
                    $stmt1 = $con->prepare("UPDATE wallets SET balance = balance + ? WHERE student_id = ?");
                    $stmt1->bind_param("di", $amount, $target_id);
                    $stmt1->execute();

                    // 2. Log Transaction
                    $stmt2 = $con->prepare("INSERT INTO wallet_transactions (student_id, amount, reference, type, status, notes, created_at) VALUES (?, ?, ?, ?, 'success', ?, NOW())");
                    $stmt2->bind_param("idsss", $target_id, $amount, $reference, $type, $notes);
                    $stmt2->execute();

                    mysqli_commit($con);
                    $msg = "success|₦" . number_format($amount, 2) . " credited successfully.";

                    // --- SEND CREDIT NOTIFICATION EMAIL ---
                    $email_stmt = $con->prepare("SELECT s.studentName, s.email FROM students s WHERE s.id = ?");
                    $email_stmt->bind_param("i", $target_id);
                    $email_stmt->execute();
                    $email_row = $email_stmt->get_result()->fetch_assoc();
                    $email_stmt->close();

                    if (!empty($email_row['email'])) {
                        try {
                            $mail = new PHPMailer(true);
                            $mail->isSMTP();
                            $mail->Host = $_ENV['SMTP_HOST'];
                            $mail->SMTPAuth = true;
                            $mail->Username = $_ENV['SMTP_USERNAME'];
                            $mail->Password = $_ENV['SMTP_PASSWORD'];
                            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
                            $mail->Port = $_ENV['SMTP_PORT'];
                            $mail->Timeout = 10;
                            $mail->setFrom($_ENV['SMTP_USERNAME'], $_ENV['SCHOOL_NAME'] . ' Wallet');
                            $mail->addAddress($email_row['email'], $email_row['studentName']);
                            $mail->isHTML(true);
                            $mail->CharSet = 'UTF-8';
                            $mail->Encoding = 'base64';
                            $mail->Subject = 'Wallet Credit Alert - ' . $_ENV['SCHOOL_NAME'];
                            $new_balance = $current_balance + $amount;
                            $mail->Body = '
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"></head>
<body style="margin:0;padding:0;background:#f4f6f9;font-family:Arial,sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0" style="background:#f4f6f9;padding:20px;">
<tr><td align="center">
<table width="100%" style="max-width:500px;background:#ffffff;border-radius:16px;overflow:hidden;box-shadow:0 10px 30px rgba(0,0,0,0.05);">
    <tr><td style="background:#0f172a;padding:20px;text-align:center;">
        <h2 style="color:#ffffff;margin:0;font-size:18px;letter-spacing:1px;">' . htmlspecialchars($_ENV['SCHOOL_NAME']) . ' Wallet</h2>
    </td></tr>
    <tr><td style="padding:30px;text-align:center;">
        <div style="width:60px;height:60px;background:#dcfce7;border-radius:50%;margin:0 auto 16px;line-height:60px;">
            <span style="font-size:28px;color:#16a34a;">&#10003;</span>
        </div>
        <h3 style="margin:0 0 8px;color:#0f172a;">Wallet Credited</h3>
        <p style="color:#64748b;font-size:14px;margin-bottom:20px;">Dear ' . htmlspecialchars($email_row['studentName']) . ', your wallet has been funded.</p>
        <div style="font-size:32px;font-weight:bold;color:#16a34a;margin-bottom:6px;">+&#8358;' . number_format($amount, 2) . '</div>
        <p style="color:#94a3b8;font-size:12px;margin-bottom:20px;">Reference: ' . htmlspecialchars($reference) . '</p>
        <table width="100%" cellpadding="0" cellspacing="0" style="background:#f8fafc;border-radius:12px;">
            <tr>
                <td style="font-size:13px;color:#64748b;padding:8px 16px;">New Balance</td>
                <td style="font-size:13px;font-weight:bold;color:#0f172a;text-align:right;padding:8px 16px;">&#8358;' . number_format($new_balance, 2) . '</td>
            </tr>
            ' . (!empty($notes) ? '<tr><td style="font-size:13px;color:#64748b;padding:8px 16px;">Note</td><td style="font-size:13px;color:#0f172a;text-align:right;padding:8px 16px;">' . htmlspecialchars($notes) . '</td></tr>' : '') . '
        </table>
    </td></tr>
    <tr><td style="padding:0 30px;"><hr style="border:none;border-top:1px solid #e2e8f0;"></td></tr>
    <tr><td style="padding:16px 30px;text-align:center;">
        <p style="font-size:12px;color:#94a3b8;line-height:1.6;">If you did not expect this credit, please contact the school administration immediately.</p>
    </td></tr>
    <tr><td style="background:#f8fafc;padding:14px;text-align:center;">
        <p style="font-size:11px;color:#94a3b8;margin:0;">&#169; ' . date("Y") . ' ' . htmlspecialchars($_ENV['SCHOOL_NAME']) . ' &bull; Secure Wallet System</p>
    </td></tr>
</table>
</td></tr>
</table>
</body>
</html>';
                            $mail->send();
                        } catch (Exception $e) {
                            // Email failure is non-fatal — transaction already committed
                        }
                    }
                } catch (Exception $e) {
                    mysqli_rollback($con);
                    $msg = "danger|System Error: Could not process transaction.";
                }
            } // end max_balance check
        } // end funding_enabled check
    } else {
        $msg = "warning|Please provide a valid amount and recipient.";
    }
}

// Pre-fetch specific student
$student = null;
if ($student_id > 0) {
    $stmt = $con->prepare("SELECT s.studentName, s.studentno FROM students s INNER JOIN wallets w ON s.id = w.student_id WHERE s.id = ?");
    $stmt->bind_param("i", $student_id);
    $stmt->execute();
    $student = $stmt->get_result()->fetch_assoc();
}
?>

<!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>
        @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;800&display=swap');

        body {
            font-family: 'Plus Jakarta Sans', sans-serif;
        }

        .glass-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
        }

        .input-focus-effect:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.1);
        }

        .select2-container--default .select2-selection--single {
            height: 64px !important;
            border: 2px solid #f1f5f9 !important;
            border-radius: 1rem !important;
            display: flex;
            align-items: center;
            padding: 0 1rem;
            transition: all 0.3s;
        }

        .select2-container--focus .select2-selection--single {
            border-color: #3b82f6 !important;
        }
    </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">
            <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">Approve Document Fee
                                                (Graduated Students)</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">Certificate/Testimonial
                                        </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 Funding
                                    </h5>
                                </div>
                                <div class="card-body">

                                    <?php if ($msg):
                                        list($type, $text) = explode('|', $msg); ?>
                                        <div
                                            class="mb-6 p-4 rounded-2xl flex items-center gap-3 animate-bounce-in <?php echo $type == 'success' ? 'bg-emerald-50 text-emerald-700' : 'bg-rose-50 text-rose-700'; ?>">
                                            <i
                                                class="fas <?php echo $type == 'success' ? 'fa-check-circle' : 'fa-exclamation-triangle'; ?> text-xl"></i>
                                            <span class="font-bold"><?php echo $text; ?></span>
                                        </div>
                                    <?php endif; ?>

                                    <div
                                        class="bg-indigo-900 rounded-3xl p-6 mb-8 text-white shadow-xl shadow-indigo-100 relative overflow-hidden">
                                        <div class="relative z-10">
                                            <div class="flex items-center gap-2 mb-2">
                                                <span
                                                    class="bg-indigo-400/30 px-2 py-1 rounded text-[10px] font-bold uppercase tracking-widest">Internal
                                                    Security</span>
                                            </div>
                                            <h4 class="text-lg font-bold">Manual Credit Protocol</h4>
                                            <p class="text-indigo-200 text-xs mt-1 max-w-md">By proceeding, you
                                                acknowledge that this credit is backed by verified assets. This
                                                transaction will be permanently logged under your admin session.</p>
                                        </div>
                                        <i
                                            class="fas fa-shield-halved absolute -right-4 -bottom-4 text-8xl opacity-10 rotate-12"></i>
                                    </div>

                                    <div
                                        class="glass-card rounded-[2.5rem] border border-slate-200 shadow-2xl shadow-slate-200/50 overflow-hidden">
                                        <form method="POST" class="p-8 md:p-12 space-y-8">

                                            <div class="space-y-3">
                                                <label
                                                    class="text-xs font-black text-slate-400 uppercase tracking-[0.2em] ml-1">Account
                                                    Recipient</label>
                                                <?php if (!$student): ?>
                                                    <select name="student_select" id="student_select" class="w-full"
                                                        required>
                                                        <option value=""></option>
                                                        <?php
                                                        $allStudents = mysqli_query($con, "SELECT s.id, s.studentName, s.studentno FROM students s INNER 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'] . " — ADM NO: " . $s['studentno'] . "</option>";
                                                        }
                                                        ?>
                                                    </select>
                                                <?php else: ?>
                                                    <div
                                                        class="flex items-center gap-4 p-5 bg-blue-50 border-2 border-blue-100 rounded-2xl">
                                                        <div
                                                            class="w-12 h-12 bg-blue-600 rounded-full flex items-center justify-center text-white text-xl font-bold">
                                                            <?php echo substr($student['studentName'], 0, 1); ?>
                                                        </div>
                                                        <div>
                                                            <h4 class="font-extrabold text-slate-900">
                                                                <?php echo htmlspecialchars($student['studentName']); ?>
                                                            </h4>
                                                            <span class="text-blue-600 font-bold text-xs">ADM NO:
                                                                <?php echo htmlspecialchars($student['studentno']); ?></span>
                                                        </div>
                                                    </div>
                                                <?php endif; ?>
                                            </div>

                                            <div class="space-y-3">
                                                <label
                                                    class="text-xs font-black text-slate-400 uppercase tracking-[0.2em] ml-1">Credit
                                                    Amount</label>
                                                <div class="relative">
                                                    <div
                                                        class="absolute inset-y-0 left-6 flex items-center pointer-events-none">
                                                        <span class="text-2xl font-extrabold text-slate-300">₦</span>
                                                    </div>
                                                    <input type="number" step="0.01" name="amount" required
                                                        class="w-full pl-14 pr-8 py-6 bg-slate-50 border-2 border-slate-100 rounded-2xl outline-none text-3xl font-black text-slate-800 focus:bg-white focus:border-blue-500 transition-all placeholder:text-slate-200"
                                                        placeholder="0.00">
                                                </div>
                                            </div>

                                            <div class="space-y-3">
                                                <label
                                                    class="text-xs font-black text-slate-400 uppercase tracking-[0.2em] ml-1">Justification
                                                    / Transaction Note</label>
                                                <textarea name="notes" rows="3" required
                                                    class="w-full p-5 bg-slate-50 border-2 border-slate-100 rounded-2xl outline-none text-sm font-semibold text-slate-600 focus:bg-white focus:border-blue-500 transition-all"
                                                    placeholder="Provide a reason for this manual credit (e.g. Cash payment received)"></textarea>
                                            </div>

                                            <div class="pt-4 space-y-4">
                                                <button type="submit" name="submit"
                                                    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> Authorize Deposit
                                                </button>
                                                <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>
                                        </form>
                                    </div>
                                </div>
            </section>
        </div>
        <?php @include("includes/footer.php"); ?>
    </div>

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

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script>
        $(document).ready(function () {
            $('#student_select').select2({
                placeholder: "Search account byname or ADM number",
                allowClear: true
            });
        });
    </script>
</body>

</html>