<?php
require_once __DIR__ . '/auth.php';
$tab  = $_GET['tab'] ?? 'pending';
$tabs = ['pending','approved','rejected'];
if(!in_array($tab,$tabs)) $tab='pending';
$st = $pdo->prepare("SELECT w.*,u.number,u.member_name FROM withdrawals w JOIN users u ON w.user_id=u.id WHERE w.status=? ORDER BY w.id DESC");
$st->execute([$tab]); $withdrawals=$st->fetchAll();

$WD_REASONS=['Account not found','Account number mismatch','Wager requirement not met','Daily limit exceeded','Suspicious activity','Please recharge and then withdraw','Other'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Withdrawals - PakClub Admin</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{background:#0b0e18;color:#e8eaf0;font-family:'Segoe UI',sans-serif;display:flex;min-height:100vh}
.main{flex:1;overflow-x:hidden}
.topbar{background:#111827;border-bottom:1px solid rgba(255,255,255,.07);padding:16px 28px;display:flex;align-items:center;justify-content:space-between}
.topbar h2{font-size:20px;font-weight:700;color:#fff}
.content{padding:24px 28px}
.tabs{display:flex;gap:4px;background:#111827;padding:6px;border-radius:12px;width:fit-content;margin-bottom:22px}
.tab-btn{padding:9px 22px;border-radius:9px;border:none;cursor:pointer;font-size:13px;font-weight:600;color:#9ca3af;background:transparent;transition:all .2s}
.tab-btn.active{background:#f26d0f;color:#fff;box-shadow:0 4px 12px rgba(242,109,15,.3)}
.card{background:#1e2130;border:1px solid rgba(255,255,255,.07);border-radius:14px;overflow:hidden}
table{width:100%;border-collapse:collapse;font-size:13px}
th{padding:11px 16px;color:#4b5563;font-size:11px;text-transform:uppercase;letter-spacing:.7px;border-bottom:1px solid rgba(255,255,255,.06);text-align:left;font-weight:600}
td{padding:12px 16px;border-bottom:1px solid rgba(255,255,255,.04);color:#c9ccd6;vertical-align:middle}
tr:last-child td{border-bottom:none}
tr:hover td{background:rgba(255,255,255,.02)}
.pill{padding:3px 10px;border-radius:20px;font-size:11px;font-weight:600}
.pill-pending{background:rgba(245,158,11,.15);color:#f59e0b}
.pill-approved{background:rgba(34,197,94,.15);color:#22c55e}
.pill-rejected{background:rgba(239,68,68,.15);color:#ef4444}
.payout-none{color:#4b5563}
.payout-processing{color:#f59e0b}
.payout-sent{color:#22c55e}
.payout-failed{color:#ef4444}
.btn{padding:7px 14px;border-radius:8px;border:none;cursor:pointer;font-size:12px;font-weight:600;display:inline-flex;align-items:center;gap:6px;transition:opacity .2s;text-decoration:none}
.btn:hover{opacity:.85}
.btn-green{background:#22c55e;color:#000}
.btn-red{background:#ef4444;color:#fff}
.btn-gray{background:#374151;color:#e5e7eb}
.actions{display:flex;gap:6px}
.modal-bg{position:fixed;inset:0;background:rgba(0,0,0,.8);z-index:999;display:none;align-items:center;justify-content:center;padding:20px}
.modal-bg.open{display:flex}
.modal{background:#1a1f2e;border:1px solid rgba(255,255,255,.1);border-radius:16px;width:100%;max-width:480px}
.modal-head{padding:20px 24px;border-bottom:1px solid rgba(255,255,255,.08);display:flex;align-items:center;justify-content:space-between}
.modal-head h3{font-size:17px;font-weight:700;color:#fff}
.modal-close{background:none;border:none;color:#9ca3af;font-size:20px;cursor:pointer}
.modal-body{padding:24px}
.field{margin-bottom:16px}
.field label{display:block;font-size:12px;color:#6b7280;text-transform:uppercase;letter-spacing:.6px;margin-bottom:8px;font-weight:600}
select,textarea{width:100%;background:#0f1117;border:1px solid rgba(255,255,255,.1);border-radius:8px;padding:10px 14px;color:#fff;font-size:14px;outline:none}
select:focus,textarea:focus{border-color:#f26d0f}
.info-box{background:rgba(255,255,255,.04);border-radius:10px;padding:14px 16px;margin-bottom:16px}
.info-row{display:flex;justify-content:space-between;padding:6px 0;border-bottom:1px solid rgba(255,255,255,.05);font-size:13px}
.info-row:last-child{border-bottom:none}
.info-row .lbl{color:#6b7280} .info-row .val{color:#fff;font-weight:600}
.reject-reason{font-size:12px;color:#f87171;font-style:italic;margin-top:4px}
</style>
</head>
<body>

<?php include 'sidebar.php'; ?>

<div class="main">
    <div class="topbar">
        <h2><i class="fa-solid fa-money-bill-transfer" style="color:#f26d0f;margin-right:10px"></i>Withdrawals</h2>
    </div>
    <div class="content">
        <div class="tabs">
            <?php foreach($tabs as $t): ?>
            <a href="?tab=<?= $t ?>"><button class="tab-btn <?= $t===$tab?'active':'' ?>"><?= ucfirst($t) ?></button></a>
            <?php endforeach; ?>
        </div>
        <div class="card">
            <table>
                <tr><th>ID</th><th>User</th><th>Amount</th><th>Method</th><th>Account</th><th>Payout</th><th>Date</th><th>Status</th><th>Actions</th></tr>
                <?php foreach($withdrawals as $w): ?>
                <tr>
                    <td>#<?= $w['id'] ?></td>
                    <td><?= htmlspecialchars($w['number']) ?><br><small style="color:#6b7280"><?= htmlspecialchars($w['member_name']??'') ?></small></td>
                    <td style="color:#f26d0f;font-weight:700">Rs<?= number_format($w['amount'],2) ?></td>
                    <td><?= $w['method'] ?></td>
                    <td style="font-size:12px"><?= htmlspecialchars($w['account_name']) ?><br><?= htmlspecialchars($w['account_number']) ?></td>
                    <td class="payout-<?= $w['payout_status'] ?>" style="font-size:12px"><?= ucfirst($w['payout_status']) ?></td>
                    <td style="font-size:12px"><?= date('M d H:i',strtotime($w['created_at'])) ?></td>
                    <td>
                        <span class="pill pill-<?= $w['status'] ?>"><?= ucfirst($w['status']) ?></span>
                        <?php if($w['reject_reason']): ?><div class="reject-reason"><?= htmlspecialchars($w['reject_reason']) ?></div><?php endif; ?>
                    </td>
                    <td>
                        <?php if($w['status']==='pending'): ?>
                        <div class="actions">
                            <button class="btn btn-green" onclick="approveWD(<?= $w['id'] ?>,<?= $w['amount'] ?>)"><i class="fa-solid fa-check"></i> Approve</button>
                            <button class="btn btn-red" onclick="openReject(<?= $w['id'] ?>,<?= $w['amount'] ?>)"><i class="fa-solid fa-xmark"></i> Reject</button>
                        </div>
                        <?php else: ?><span style="color:#4b5563;font-size:12px">-</span><?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php if(!$withdrawals): ?><tr><td colspan="9" style="text-align:center;padding:30px;color:#4b5563">No <?= $tab ?> withdrawals</td></tr><?php endif; ?>
            </table>
        </div>
    </div>
</div>

<!-- Reject Modal -->
<div class="modal-bg" id="rejectModal">
    <div class="modal">
        <div class="modal-head">
            <h3><i class="fa-solid fa-xmark-circle" style="color:#ef4444"></i> &nbsp;Reject Withdrawal</h3>
            <button class="modal-close" onclick="closeReject()"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <div class="modal-body">
            <div class="info-box">
                <div class="info-row"><span class="lbl">Withdrawal ID</span><span class="val" id="rWdId">-</span></div>
                <div class="info-row"><span class="lbl">Amount</span><span class="val" id="rWdAmt">-</span></div>
            </div>
            <div class="field">
                <label>Rejection Reason *</label>
                <select id="rReason" onchange="document.getElementById('rReasonCustom').value=this.value">
                    <?php foreach($WD_REASONS as $r): ?><option value="<?= htmlspecialchars($r) ?>"><?= htmlspecialchars($r) ?></option><?php endforeach; ?>
                </select>
                <textarea id="rReasonCustom" style="margin-top:8px;resize:none;height:70px" placeholder="Or type a custom reason..."></textarea>
            </div>
            <div style="display:flex;gap:10px;margin-top:4px">
                <button class="btn btn-red" style="flex:1;justify-content:center;padding:12px" onclick="submitReject()"><i class="fa-solid fa-xmark-circle"></i> Confirm Rejection</button>
                <button class="btn btn-gray" onclick="closeReject()">Cancel</button>
            </div>
        </div>
    </div>
</div>

<div id="toast" style="position:fixed;bottom:30px;left:50%;transform:translateX(-50%);background:rgba(20,20,20,.9);backdrop-filter:blur(10px);color:#fff;padding:12px 24px;border-radius:30px;font-size:13px;display:none;z-index:9999;white-space:nowrap"></div>

<script>
let rejectId = null;

function toast(m, ok=true) {
    const t = document.getElementById('toast');
    t.style.display = 'block';
    t.style.borderLeft = '3px solid ' + (ok ? '#22c55e' : '#ef4444');
    t.innerText = m;
    setTimeout(() => t.style.display = 'none', 2800);
}

function api(data, cb) {
    const fd = new FormData();
    for(const[k,v] of Object.entries(data)) fd.append(k,v);
    
    fetch('actions.php', { method: 'POST', body: fd })
        .then(r => r.json())
        .then(cb)
        .catch(() => toast('Network error', false));
}

function approveWD(id, amt) {
    if(!confirm(`Approve withdrawal of Rs${parseFloat(amt).toFixed(2)} and send via LG Pay?`)) return;
    api({action: 'approve_withdrawal', id: id}, r => {
        toast(r.ok ? r.msg : r.msg, r.ok);
        if(r.ok) setTimeout(() => location.reload(), 1400);
    });
}

function openReject(id, amt) {
    rejectId = id;
    document.getElementById('rWdId').innerText = '#' + id;
    document.getElementById('rWdAmt').innerText = 'Rs' + parseFloat(amt).toFixed(2);
    document.getElementById('rejectModal').classList.add('open');
}

function closeReject() {
    document.getElementById('rejectModal').classList.remove('open');
    rejectId = null;
}

function submitReject() {
    const reason = document.getElementById('rReasonCustom').value.trim() || document.getElementById('rReason').value;
    if(!reason) { toast('Reason required', false); return; }
    
    api({action: 'reject_withdrawal', id: rejectId, reason: reason}, r => {
        toast(r.ok ? 'Withdrawal rejected' : r.msg, r.ok);
        if(r.ok) {
            closeReject();
            setTimeout(() => location.reload(), 1200);
        }
    });
}
</script>
</body>
</html>