<?php include "header.php"; ?>
<?php
include_once __DIR__ . '/../includes/wallet_lib.php';

$uid = (int)($userdata['id'] ?? 0);
$balance = get_wallet_balance($conn, $uid);
$commission = get_commission_settings($conn);
$history = get_wallet_history($conn, $uid, 100);

$commissionLabel = $commission['type'] === 'fixed'
    ? '₹' . number_format($commission['value'], 2) . ' flat per successful transaction'
    : $commission['value'] . '% per successful transaction';

$limitsResult = $conn->query("SELECT wallet_topup_min, wallet_topup_max FROM site_settings LIMIT 1");
$limitsRow = $limitsResult ? $limitsResult->fetch_assoc() : null;
$topupMin = (float)($limitsRow['wallet_topup_min'] ?? 10);
$topupMax = (float)($limitsRow['wallet_topup_max'] ?? 50000);
?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">

<style>
    :root{
        --p:#6c63ff; --p2:#e040fb;
        --g: linear-gradient(135deg,#6c63ff,#e040fb);
        --success:#43e97b; --danger:#ff6584; --warning:#f5b93b; --info:#3ea6ff;
    }
    *{box-sizing:border-box}
    html, body, .content-wrapper{ background:#0a0a12 !important; }
    body{ font-family:'Inter',sans-serif; color:#fff; }
    .content-wrapper{min-height:100vh}

    .wl-wrap{padding:20px;max-width:1100px;margin:0 auto;animation:pageIn .4s ease both}
    @keyframes pageIn{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}

    .wl-head h1{font-size:1.5rem;font-weight:800;margin:0 0 4px;display:flex;align-items:center;gap:10px}
    .wl-head h1 .icn{
        width:36px;height:36px;border-radius:11px;background:var(--g);display:inline-flex;
        align-items:center;justify-content:center;font-size:15px;box-shadow:0 6px 18px rgba(108,99,255,.35);
    }
    .wl-head p{color:rgba(255,255,255,.45);font-size:.85rem;margin:0 0 20px}

    .wl-grid{display:grid;grid-template-columns:1.1fr 1fr;gap:18px;margin-bottom:22px}
    @media(max-width:760px){ .wl-grid{grid-template-columns:1fr} }

    .balance-card{
        background:var(--g);border-radius:20px;padding:26px;position:relative;overflow:hidden;
        box-shadow:0 20px 45px rgba(108,99,255,.25);
    }
    .balance-card::after{
        content:'';position:absolute;inset:0;background:radial-gradient(circle at 85% 15%, rgba(255,255,255,.18), transparent 55%);
        pointer-events:none;
    }
    .balance-card .lbl{font-size:.78rem;font-weight:700;text-transform:uppercase;letter-spacing:.6px;opacity:.85;position:relative}
    .balance-card .amt{font-size:2.6rem;font-weight:800;margin:6px 0 18px;position:relative}
    .balance-card .amt.negative{color:#fff2f2}
    .balance-card .amt small{font-size:1.2rem;font-weight:700;opacity:.85}
    .btn-addfund{
        background:#fff;color:var(--p);border:none;padding:11px 22px;border-radius:11px;
        font-weight:800;font-size:.85rem;cursor:pointer;position:relative;display:inline-flex;
        align-items:center;gap:8px;transition:.2s;
    }
    .btn-addfund:hover{transform:translateY(-2px);box-shadow:0 8px 20px rgba(0,0,0,.25)}

    .info-card{
        background:rgba(255,255,255,.04);backdrop-filter:blur(20px);border:1px solid rgba(255,255,255,.08);
        border-radius:20px;padding:22px 24px;
    }
    .info-card .lbl{font-size:.72rem;font-weight:800;text-transform:uppercase;letter-spacing:.6px;color:rgba(255,255,255,.4);margin-bottom:8px}
    .info-card .val{font-size:1.15rem;font-weight:700;color:#fff;display:flex;align-items:center;gap:9px}
    .info-card .val i{color:var(--warning)}
    .info-card p{font-size:.8rem;color:rgba(255,255,255,.4);margin:10px 0 0}

    .hist-card{
        background:rgba(255,255,255,.04);backdrop-filter:blur(20px);border:1px solid rgba(255,255,255,.08);
        border-radius:20px;overflow:hidden;
    }
    .hist-head{padding:18px 22px;border-bottom:1px solid rgba(255,255,255,.07);display:flex;align-items:center;gap:10px}
    .hist-head h3{font-size:.95rem;font-weight:700;margin:0}
    .hist-head .dot{width:7px;height:7px;border-radius:50%;background:var(--success)}

    table.wl-table{width:100%;border-collapse:collapse}
    table.wl-table th{
        text-align:left;font-size:.7rem;text-transform:uppercase;letter-spacing:.5px;
        color:rgba(255,255,255,.35);padding:12px 22px;font-weight:700;
    }
    table.wl-table td{padding:13px 22px;font-size:.85rem;border-top:1px solid rgba(255,255,255,.05)}
    .wl-amt-credit{color:var(--success);font-weight:700}
    .wl-amt-debit{color:var(--danger);font-weight:700}
    .wl-type-pill{
        display:inline-flex;padding:3px 10px;border-radius:20px;font-size:.7rem;font-weight:700;
        background:rgba(255,255,255,.06);color:rgba(255,255,255,.6);
    }
    .wl-empty{text-align:center;padding:50px 20px;color:rgba(255,255,255,.3)}
    .wl-empty i{font-size:2rem;margin-bottom:10px;display:block}

    @media(max-width:640px){
        table.wl-table thead{display:none}
        table.wl-table, table.wl-table tbody, table.wl-table tr, table.wl-table td{display:block;width:100%}
        table.wl-table tr{padding:14px 18px;border-top:1px solid rgba(255,255,255,.06)}
        table.wl-table td{padding:3px 0;border:none;display:flex;justify-content:space-between}
        table.wl-table td::before{content:attr(data-label);color:rgba(255,255,255,.4);font-size:.72rem}
    }

    /* Add Funds modal - same glass style as the transactions page dialogs */
    .swal-glass-popup{
        background:rgba(24,22,38,.68) !important;backdrop-filter:blur(28px) saturate(180%);
        border:1px solid rgba(255,255,255,.14) !important;border-radius:22px !important;
        box-shadow:0 24px 70px rgba(0,0,0,.55) !important;color:#fff !important;
    }
    .swal-glass-popup .swal2-title{color:#fff !important}
    .swal-glass-popup input.swal2-input{
        background:rgba(255,255,255,.06) !important;border:1px solid rgba(255,255,255,.14) !important;
        color:#fff !important;border-radius:10px !important;
    }
    .swal-glass-confirm{
        padding:10px 22px;border-radius:10px;font-size:.85rem;font-weight:700;cursor:pointer;
        background:var(--g) !important;color:#fff !important;border:none;box-shadow:0 6px 18px rgba(108,99,255,.35);
    }
    .swal-glass-cancel{
        padding:10px 22px;border-radius:10px;font-size:.85rem;font-weight:700;cursor:pointer;
        background:rgba(255,255,255,.07) !important;color:#fff !important;border:1px solid rgba(255,255,255,.14) !important;
    }
</style>

<div class="wl-wrap">
    <div class="wl-head">
        <h1><span class="icn"><i class="fas fa-wallet"></i></span>Wallet</h1>
        <p>Your balance, commission rate, and full transaction history</p>
    </div>

    <div class="wl-grid">
        <div class="balance-card">
            <div class="lbl">Current Balance</div>
            <div class="amt <?php echo $balance < 0 ? 'negative' : ''; ?>"><small>₹</small><?php echo number_format($balance, 2); ?></div>
            <button type="button" class="btn-addfund" id="addFundBtn"><i class="fas fa-plus"></i> Add Funds</button>
            <div style="position:relative;margin-top:10px;font-size:.72rem;opacity:.8">Min ₹<?php echo number_format($topupMin, 0); ?> · Max ₹<?php echo number_format($topupMax, 0); ?> per top-up</div>
        </div>
        <div class="info-card">
            <div class="lbl">Commission Rate</div>
            <div class="val"><i class="fas fa-percent"></i> <?php echo htmlspecialchars($commissionLabel); ?></div>
            <p>Deducted from your wallet automatically on every <b>successful</b> transaction only — never on Pending or Failed.</p>
        </div>
    </div>

    <div class="hist-card">
        <div class="hist-head"><span class="dot"></span><h3>Transaction History</h3></div>
        <?php if (empty($history)): ?>
            <div class="wl-empty"><i class="fas fa-inbox"></i>No wallet activity yet</div>
        <?php else: ?>
        <table class="wl-table">
            <thead><tr><th>Date</th><th>Type</th><th>Order ID</th><th>Amount</th><th>Balance After</th></tr></thead>
            <tbody>
                <?php foreach ($history as $h):
                    $isCredit = ($h['operation_type'] ?? '') === 'credit';
                ?>
                <tr>
                    <td data-label="Date"><?php echo htmlspecialchars($h['date']); ?></td>
                    <td data-label="Type"><span class="wl-type-pill"><?php echo htmlspecialchars($h['type']); ?></span></td>
                    <td data-label="Order ID"><?php echo htmlspecialchars($h['order_id'] ?? '—'); ?></td>
                    <td data-label="Amount" class="<?php echo $isCredit ? 'wl-amt-credit' : 'wl-amt-debit'; ?>">
                        <?php echo $isCredit ? '+' : '−'; ?>₹<?php echo number_format((float)$h['amount'], 2); ?>
                    </td>
                    <td data-label="Balance After">₹<?php echo isset($h['balance_after']) ? number_format((float)$h['balance_after'], 2) : '—'; ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php endif; ?>
    </div>
</div>

<script src="./assets/vendors/jquery/dist/jquery.min.js"></script>
<script src="./assets/vendors/popper.js/dist/umd/popper.min.js"></script>
<script src="./assets/vendors/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="./assets/vendors/metisMenu/dist/metisMenu.min.js"></script>
<script src="./assets/vendors/jquery-slimscroll/jquery.slimscroll.min.js"></script>
<script src="assets/js/app.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
(function () {
    var params = new URLSearchParams(window.location.search);
    var glass = { popup: 'swal-glass-popup', confirmButton: 'swal-glass-confirm' };
    if (params.get('topup_success') === '1') {
        Swal.fire({ icon: 'success', title: 'Funds Added', text: 'Your wallet has been credited.', buttonsStyling: false, customClass: glass, background: 'transparent', backdrop: 'rgba(6,6,14,.65)' });
    } else if (params.get('topup_failed') === '1') {
        var reason = params.get('reason');
        var apiMsg = params.get('api_msg');
        var msgByReason = {
            out_of_range: 'Amount must be between the allowed min/max add-funds limit. Nothing was deducted.',
            invalid_amount: 'That amount was not valid. Nothing was deducted.',
            network: 'Could not reach the payment server. Nothing was deducted.',
            missing_order: 'Could not find your top-up order. Nothing was deducted.',
            lookup: 'Could not verify the payment status. If you did pay, contact support with your order ID.',
            payment_failed: 'The payment was declined. Nothing was deducted.',
            unresolved_owner: 'Could not match this payment to your account. Contact support with your order ID.',
            create_order: apiMsg ? ('Could not start the payment: ' + apiMsg) : 'Could not start the payment. Nothing was deducted.',
        };
        var msg = msgByReason[reason] || 'Your wallet top-up could not be completed. Nothing was deducted.';
        Swal.fire({ icon: 'error', title: 'Payment Failed', text: msg, buttonsStyling: false, customClass: glass, background: 'transparent', backdrop: 'rgba(6,6,14,.65)' });
    } else if (params.get('topup_pending') === '1') {
        Swal.fire({ icon: 'info', title: 'Payment Processing', text: "We haven't received confirmation yet. Check back shortly.", buttonsStyling: false, customClass: glass, background: 'transparent', backdrop: 'rgba(6,6,14,.65)' });
    }
    if (params.get('topup_success') || params.get('topup_failed') || params.get('topup_pending')) {
        var url = new URL(window.location.href);
        ['topup_success', 'topup_failed', 'topup_pending', 'reason', 'api_msg'].forEach(k => url.searchParams.delete(k));
        window.history.replaceState({}, document.title, url.toString());
    }
})();

document.getElementById('addFundBtn').addEventListener('click', function () {
    var TOPUP_MIN = <?php echo json_encode($topupMin); ?>;
    var TOPUP_MAX = <?php echo json_encode($topupMax); ?>;
    Swal.fire({
        title: 'Add Funds to Wallet',
        html: '<p style="color:rgba(255,255,255,.5);font-size:13px;margin-bottom:10px;">Amount between ₹' + TOPUP_MIN + ' and ₹' + TOPUP_MAX + '. You\'ll be redirected to complete the payment.</p>',
        input: 'number',
        inputAttributes: { min: TOPUP_MIN, max: TOPUP_MAX, step: '0.01', placeholder: 'Enter amount (₹)' },
        showCancelButton: true,
        confirmButtonText: 'Continue to Pay',
        cancelButtonText: 'Cancel',
        buttonsStyling: false,
        customClass: { popup: 'swal-glass-popup', confirmButton: 'swal-glass-confirm', cancelButton: 'swal-glass-cancel' },
        background: 'transparent',
        backdrop: 'rgba(6,6,14,.65)',
        preConfirm: (value) => {
            const amt = parseFloat(value);
            if (!amt || amt <= 0) {
                Swal.showValidationMessage('Enter a valid amount greater than 0');
                return false;
            }
            if (amt < TOPUP_MIN) {
                Swal.showValidationMessage('Minimum add funds amount is ₹' + TOPUP_MIN);
                return false;
            }
            if (amt > TOPUP_MAX) {
                Swal.showValidationMessage('Maximum add funds amount is ₹' + TOPUP_MAX);
                return false;
            }
            return amt;
        }
    }).then((res) => {
        if (!res.isConfirmed) return;
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = 'lib/wallet_pay';
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'amount';
        input.value = res.value;
        form.appendChild(input);
        const input2 = document.createElement('input');
        input2.type = 'hidden';
        input2.name = 'addfund';
        input2.value = '1';
        form.appendChild(input2);
        document.body.appendChild(form);
        form.submit();
    });
});
</script>
</body>
</html>
