<?php
require_once '../../config.php';
requireLogin('sub_admin');
$sa = $conn->query("SELECT * FROM sub_admins WHERE id=" . (int)$_SESSION['user_id'])->fetch_assoc();
$success = $error = '';
$sa_id = (int)$_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    // Approve user deposit
    if ($action === 'approve_deposit') {
        $req_id = (int)$_POST['req_id'];
        $req = $conn->query("SELECT * FROM user_deposit_requests WHERE id=$req_id AND sub_admin_id=$sa_id AND status='pending'")->fetch_assoc();
        if ($req) {
            $amount = $req['amount'];
            $user_id = $req['user_id'];
            $user = $conn->query("SELECT * FROM users WHERE id=$user_id")->fetch_assoc();
            $new_user_bal = $user['wallet_balance'] + $amount;
            $conn->query("UPDATE users SET wallet_balance=$new_user_bal, total_received=total_received+$amount WHERE id=$user_id");
            $conn->query("UPDATE user_deposit_requests SET status='approved', approved_at=NOW() WHERE id=$req_id");
            $conn->query("INSERT INTO user_wallet_transactions (user_id, transaction_type, amount, description, balance_after, reference_id) VALUES ($user_id, 'credit', $amount, 'Deposit approved by Sub Admin', $new_user_bal, $req_id)");
            $success = "Deposit of " . formatINR($amount) . " approved for " . htmlspecialchars($user['full_name']) . "!";
        }
    }

    if ($action === 'reject_deposit') {
        $req_id = (int)$_POST['req_id'];
        $note = sanitize($_POST['subadmin_note'] ?? 'Rejected');
        $conn->query("UPDATE user_deposit_requests SET status='rejected', subadmin_note='$note', approved_at=NOW() WHERE id=$req_id AND sub_admin_id=$sa_id");
        $success = "Deposit request rejected.";
    }

    // Approve user withdrawal
    if ($action === 'approve_withdrawal') {
        $req_id = (int)$_POST['req_id'];
        $req = $conn->query("SELECT * FROM user_withdrawal_requests WHERE id=$req_id AND sub_admin_id=$sa_id AND status='pending'")->fetch_assoc();
        if ($req) {
            $amount = $req['amount'];
            $user_id = $req['user_id'];
            $user = $conn->query("SELECT * FROM users WHERE id=$user_id")->fetch_assoc();
            if ($user['wallet_balance'] < $amount) {
                $error = "User's wallet balance is insufficient.";
            } else {
                $new_user_bal = $user['wallet_balance'] - $amount;
                $conn->query("UPDATE users SET wallet_balance=$new_user_bal WHERE id=$user_id");
                $conn->query("UPDATE user_withdrawal_requests SET status='approved', approved_at=NOW() WHERE id=$req_id");
                $conn->query("INSERT INTO user_wallet_transactions (user_id, transaction_type, amount, description, balance_after, reference_id) VALUES ($user_id, 'debit', $amount, 'Withdrawal approved', $new_user_bal, $req_id)");
                $success = "Withdrawal of " . formatINR($amount) . " approved!";
            }
        }
    }

    if ($action === 'reject_withdrawal') {
        $req_id = (int)$_POST['req_id'];
        $note = sanitize($_POST['subadmin_note'] ?? 'Rejected');
        $conn->query("UPDATE user_withdrawal_requests SET status='rejected', subadmin_note='$note', approved_at=NOW() WHERE id=$req_id AND sub_admin_id=$sa_id");
        $success = "Withdrawal rejected.";
    }
}

$tab = $_GET['tab'] ?? 'deposits';
$deposits = $conn->query("SELECT dr.*, u.full_name as user_name, u.username FROM user_deposit_requests dr JOIN users u ON u.id=dr.user_id WHERE dr.sub_admin_id=$sa_id ORDER BY dr.created_at DESC")->fetch_all(MYSQLI_ASSOC);
$withdrawals = $conn->query("SELECT wr.*, u.full_name as user_name FROM user_withdrawal_requests wr JOIN users u ON u.id=wr.user_id WHERE wr.sub_admin_id=$sa_id ORDER BY wr.created_at DESC")->fetch_all(MYSQLI_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Requests - Sub Admin | Cricket Exchange</title>
    <link rel="stylesheet" href="../../assets/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>.btn-primary{background:linear-gradient(135deg,var(--subadmin-accent),#0369a1)}</style>
</head>
<body>
<div class="dashboard-wrapper">
    <?php include 'partials/sidebar.php'; ?>
    <div class="main-content">
        <div class="topbar">
            <div class="topbar-title"><h1>User Requests</h1><p>Approve or reject user deposit and withdrawal requests</p></div>
            <div class="topbar-actions">
                <div class="wallet-display">
                    <span>💰</span>
                    <div><div class="label">My Wallet</div><div class="amount"><?= formatINR($sa['wallet_balance']) ?></div></div>
                </div>
            </div>
        </div>
        <div class="page-content">
            <?php if ($success): ?><div class="alert alert-success"><i class="fas fa-check-circle"></i> <?= $success ?></div><?php endif; ?>
            <?php if ($error): ?><div class="alert alert-error"><i class="fas fa-times-circle"></i> <?= $error ?></div><?php endif; ?>

            <?php 
            $pending_dep = count(array_filter($deposits, fn($d) => $d['status']==='pending'));
            $pending_wit = count(array_filter($withdrawals, fn($w) => $w['status']==='pending'));
            ?>

            <div class="tabs">
                <button class="tab-btn <?= $tab==='deposits'?'active':'' ?>" onclick="switchTab('deposits')">
                    📥 Deposit Requests
                    <?php if ($pending_dep > 0): ?><span class="nav-badge" style="margin-left:6px"><?= $pending_dep ?></span><?php endif; ?>
                </button>
                <button class="tab-btn <?= $tab==='withdrawals'?'active':'' ?>" onclick="switchTab('withdrawals')">
                    📤 Withdrawal Requests
                    <?php if ($pending_wit > 0): ?><span class="nav-badge" style="margin-left:6px"><?= $pending_wit ?></span><?php endif; ?>
                </button>
            </div>

            <div id="tab-deposits" class="<?= $tab!=='deposits'?'hidden':'' ?>">
                <div class="card">
                    <div class="card-header"><h3>📥 User Deposit Requests</h3></div>
                    <div class="table-wrapper">
                        <table>
                            <thead><tr><th>#</th><th>User</th><th>Amount</th><th>Transaction ID</th><th>Screenshot</th><th>Status</th><th>Date</th><th>Actions</th></tr></thead>
                            <tbody>
                                <?php foreach ($deposits as $i => $dep): ?>
                                <tr>
                                    <td><?= $i+1 ?></td>
                                    <td>
                                        <div style="font-weight:600"><?= htmlspecialchars($dep['user_name']) ?></div>
                                        <div style="font-size:12px;color:var(--text-muted)">@<?= $dep['username'] ?></div>
                                    </td>
                                    <td><span class="text-primary fw-700" style="font-size:16px"><?= formatINR($dep['amount']) ?></span></td>
                                    <td><code style="font-size:12px;color:var(--info)"><?= htmlspecialchars($dep['transaction_id']) ?></code></td>
                                    <td>
                                        <?php if ($dep['screenshot_path']): ?>
                                        <a href="<?= $dep['screenshot_path'] ?>" target="_blank" class="btn btn-secondary btn-xs">📷 View</a>
                                        <?php else: ?><span class="text-muted" style="font-size:12px">No image</span><?php endif; ?>
                                    </td>
                                    <td><span class="badge badge-<?= $dep['status'] ?>"><?= ucfirst($dep['status']) ?></span></td>
                                    <td style="font-size:12px;color:var(--text-muted)"><?= date('d M Y H:i', strtotime($dep['created_at'])) ?></td>
                                    <td>
                                        <?php if ($dep['status'] === 'pending'): ?>
                                        <div style="display:flex;gap:6px;">
                                            <form method="POST" style="display:inline">
                                                <input type="hidden" name="action" value="approve_deposit">
                                                <input type="hidden" name="req_id" value="<?= $dep['id'] ?>">
                                                <button type="submit" class="btn btn-success btn-xs" onclick="return confirm('Approve this deposit?')">✅ Approve</button>
                                            </form>
                                            <button class="btn btn-danger btn-xs" onclick="openRejectModal('deposit', <?= $dep['id'] ?>)">❌ Reject</button>
                                        </div>
                                        <?php elseif ($dep['status'] === 'approved'): ?>
                                        <span style="font-size:12px;color:var(--success)">✅ Approved</span>
                                        <?php else: ?>
                                        <span style="font-size:12px;color:var(--danger)">❌ Rejected</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                <?php if (empty($deposits)): ?><tr><td colspan="8"><div class="empty-state"><div class="empty-icon">📥</div><p>No deposit requests</p></div></td></tr><?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <div id="tab-withdrawals" class="<?= $tab!=='withdrawals'?'hidden':'' ?>">
                <div class="card">
                    <div class="card-header"><h3>📤 User Withdrawal Requests</h3></div>
                    <div class="table-wrapper">
                        <table>
                            <thead><tr><th>#</th><th>User</th><th>Amount</th><th>Payment Details</th><th>Status</th><th>Date</th><th>Actions</th></tr></thead>
                            <tbody>
                                <?php foreach ($withdrawals as $i => $wr): ?>
                                <tr>
                                    <td><?= $i+1 ?></td>
                                    <td><div style="font-weight:600"><?= htmlspecialchars($wr['user_name']) ?></div></td>
                                    <td><span class="text-danger fw-700" style="font-size:16px"><?= formatINR($wr['amount']) ?></span></td>
                                    <td>
                                        <div style="font-size:13px">
                                            <strong><?= htmlspecialchars($wr['holder_name']) ?></strong><br>
                                            📱 <?= $wr['mobile'] ?><br>
                                            <?= $wr['payment_method']==='upi' ? '🏦 UPI: '.htmlspecialchars($wr['upi_id']) : '🏦 A/C: '.htmlspecialchars($wr['bank_account']) ?>
                                        </div>
                                    </td>
                                    <td><span class="badge badge-<?= $wr['status'] ?>"><?= ucfirst($wr['status']) ?></span></td>
                                    <td style="font-size:12px;color:var(--text-muted)"><?= date('d M Y H:i', strtotime($wr['created_at'])) ?></td>
                                    <td>
                                        <?php if ($wr['status'] === 'pending'): ?>
                                        <div style="display:flex;gap:6px;">
                                            <form method="POST" style="display:inline">
                                                <input type="hidden" name="action" value="approve_withdrawal">
                                                <input type="hidden" name="req_id" value="<?= $wr['id'] ?>">
                                                <button type="submit" class="btn btn-success btn-xs" onclick="return confirm('Approve withdrawal?')">✅ Approve</button>
                                            </form>
                                            <button class="btn btn-danger btn-xs" onclick="openRejectModal('withdrawal', <?= $wr['id'] ?>)">❌ Reject</button>
                                        </div>
                                        <?php elseif ($wr['status'] === 'approved'): ?>
                                        <span style="font-size:12px;color:var(--success)">✅ Approved</span>
                                        <?php else: ?>
                                        <span style="font-size:12px;color:var(--danger)">❌ Rejected</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                <?php if (empty($withdrawals)): ?><tr><td colspan="7"><div class="empty-state"><div class="empty-icon">📤</div><p>No withdrawal requests</p></div></td></tr><?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal-overlay" id="rejectModal">
    <div class="modal-box">
        <div class="modal-header">
            <h3>❌ Reject Request</h3>
            <button class="modal-close" onclick="closeModal('rejectModal')">✕</button>
        </div>
        <form method="POST">
            <input type="hidden" name="action" id="reject_action">
            <input type="hidden" name="req_id" id="reject_req_id">
            <div class="modal-body">
                <div class="form-group">
                    <label>Rejection Reason</label>
                    <textarea name="subadmin_note" class="form-control" rows="3" placeholder="Reason for rejection..."></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeModal('rejectModal')">Cancel</button>
                <button type="submit" class="btn btn-danger">Reject</button>
            </div>
        </form>
    </div>
</div>

<?php include 'partials/scripts.php'; ?>
<script>
function switchTab(tab) {
    document.querySelectorAll('.tab-btn').forEach((b,i) => {
        b.classList.toggle('active', (i===0 && tab==='deposits') || (i===1 && tab==='withdrawals'));
    });
    document.getElementById('tab-deposits').classList.toggle('hidden', tab!=='deposits');
    document.getElementById('tab-withdrawals').classList.toggle('hidden', tab!=='withdrawals');
}
function openRejectModal(type, id) {
    document.getElementById('reject_action').value = 'reject_' + type;
    document.getElementById('reject_req_id').value = id;
    openModal('rejectModal');
}
</script>
<style>.hidden{display:none;}</style>
</body>
</html>
