<?php
require_once '../config.php';
requireLogin('master_admin');
$admin = $conn->query("SELECT * FROM master_admin WHERE id = " . (int)$_SESSION['user_id'])->fetch_assoc();

$success = $error = '';

// Handle approve/reject
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    // Approve sub admin deposit
    if ($action === 'approve_deposit') {
        $req_id = (int)$_POST['req_id'];
        $req = $conn->query("SELECT * FROM subadmin_deposit_requests WHERE id=$req_id AND status='pending'")->fetch_assoc();
        if ($req) {
            $amount = $req['amount'];
            $sa_id = $req['sub_admin_id'];
            $sa = $conn->query("SELECT * FROM sub_admins WHERE id=$sa_id")->fetch_assoc();
            $new_sa_bal = $sa['wallet_balance'] + $amount;
            $conn->query("UPDATE sub_admins SET wallet_balance=$new_sa_bal, total_received=total_received+$amount WHERE id=$sa_id");
            $conn->query("UPDATE subadmin_deposit_requests SET status='approved', approved_by=" . (int)$_SESSION['user_id'] . ", approved_at=NOW() WHERE id=$req_id");
            $conn->query("INSERT INTO subadmin_wallet_transactions (sub_admin_id, transaction_type, amount, description, balance_after, reference_id) VALUES ($sa_id, 'credit', $amount, 'Deposit approved by Admin', $new_sa_bal, $req_id)");
            $success = "Deposit of " . formatINR($amount) . " approved for " . htmlspecialchars($sa['full_name']) . "!";
        }
    }

    if ($action === 'reject_deposit') {
        $req_id = (int)$_POST['req_id'];
        $note = sanitize($_POST['admin_note'] ?? 'Rejected by admin');
        $conn->query("UPDATE subadmin_deposit_requests SET status='rejected', admin_note='$note', approved_by=" . (int)$_SESSION['user_id'] . ", approved_at=NOW() WHERE id=$req_id");
        $success = "Deposit request rejected.";
    }

    // Approve sub admin withdrawal
    if ($action === 'approve_withdrawal') {
        $req_id = (int)$_POST['req_id'];
        $req = $conn->query("SELECT * FROM subadmin_withdrawal_requests WHERE id=$req_id AND status='pending'")->fetch_assoc();
        if ($req) {
            $amount = $req['amount'];
            $sa_id = $req['sub_admin_id'];
            $sa = $conn->query("SELECT * FROM sub_admins WHERE id=$sa_id")->fetch_assoc();
            if ($sa['wallet_balance'] < $amount) {
                $error = "Sub admin's wallet balance is insufficient.";
            } else {
                $new_sa_bal = $sa['wallet_balance'] - $amount;
                $conn->query("UPDATE sub_admins SET wallet_balance=$new_sa_bal WHERE id=$sa_id");
                $conn->query("UPDATE subadmin_withdrawal_requests SET status='approved', approved_by=" . (int)$_SESSION['user_id'] . ", approved_at=NOW() WHERE id=$req_id");
                $conn->query("INSERT INTO subadmin_wallet_transactions (sub_admin_id, transaction_type, amount, description, balance_after, reference_id) VALUES ($sa_id, 'debit', $amount, 'Withdrawal approved by Admin', $new_sa_bal, $req_id)");
                $success = "Withdrawal of " . formatINR($amount) . " approved!";
            }
        }
    }

    if ($action === 'reject_withdrawal') {
        $req_id = (int)$_POST['req_id'];
        $note = sanitize($_POST['admin_note'] ?? 'Rejected by admin');
        $conn->query("UPDATE subadmin_withdrawal_requests SET status='rejected', admin_note='$note', approved_by=" . (int)$_SESSION['user_id'] . ", approved_at=NOW() WHERE id=$req_id");
        $success = "Withdrawal request rejected.";
    }
}

$tab = $_GET['tab'] ?? 'deposits';

// Fetch pending deposits
$deposits = $conn->query("SELECT dr.*, sa.full_name as sa_name, sa.unique_code FROM subadmin_deposit_requests dr JOIN sub_admins sa ON sa.id=dr.sub_admin_id ORDER BY dr.created_at DESC")->fetch_all(MYSQLI_ASSOC);

// Fetch pending withdrawals  
$withdrawals = $conn->query("SELECT wr.*, sa.full_name as sa_name, sa.unique_code FROM subadmin_withdrawal_requests wr JOIN sub_admins sa ON sa.id=wr.sub_admin_id ORDER BY wr.created_at DESC")->fetch_all(MYSQLI_ASSOC);

$pending_dep = array_filter($deposits, fn($d) => $d['status']==='pending');
$pending_wit = array_filter($withdrawals, fn($w) => $w['status']==='pending');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Requests - Cricket Exchange Admin</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">
</head>
<body>
<div class="dashboard-wrapper">
    <?php include 'partials/sidebar.php'; ?>
    <div class="main-content">
        <div class="topbar">
            <div class="topbar-title">
                <h1>Sub Admin Requests</h1>
                <p>Approve or reject 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($admin['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; ?>

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

            <!-- Deposits Tab -->
            <div id="tab-deposits" class="<?= $tab!=='deposits' ? 'hidden' : '' ?>">
                <div class="card">
                    <div class="card-header">
                        <h3>📥 Sub Admin Deposit Requests</h3>
                    </div>
                    <div class="table-wrapper">
                        <table>
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Sub Admin</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['sa_name']) ?></div>
                                        <span class="code-badge"><?= $dep['unique_code'] ?></span>
                                    </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="<?= htmlspecialchars($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 if ($dep['admin_note']): ?><div style="font-size:11px;color:var(--text-muted)"><?= htmlspecialchars($dep['admin_note']) ?></div><?php endif; ?>
                                        <?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 yet</p></div></td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Withdrawals Tab -->
            <div id="tab-withdrawals" class="<?= $tab!=='withdrawals' ? 'hidden' : '' ?>">
                <div class="card">
                    <div class="card-header">
                        <h3>📤 Sub Admin Withdrawal Requests</h3>
                    </div>
                    <div class="table-wrapper">
                        <table>
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Sub Admin</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['sa_name']) ?></div>
                                        <span class="code-badge"><?= $wr['unique_code'] ?></span>
                                    </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>
                                            📱 <?= htmlspecialchars($wr['mobile']) ?><br>
                                            <?php if ($wr['payment_method'] === 'upi'): ?>
                                            🏦 UPI: <?= htmlspecialchars($wr['upi_id']) ?>
                                            <?php else: ?>
                                            🏦 A/C: <?= htmlspecialchars($wr['bank_account']) ?> | IFSC: <?= htmlspecialchars($wr['ifsc_code']) ?>
                                            <?php endif; ?>
                                        </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 this 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 yet</p></div></td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Reject Modal -->
<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="admin_note" class="form-control" rows="3" placeholder="Enter reason for rejection..." style="resize:vertical;"></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 Request</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>
