<?php
session_start();
require_once '../config.php';

if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit;
}
global $pdo;

$message = '';
// Approve
if (isset($_GET['approve'])) {
    $id = (int)$_GET['approve'];
    $row = $pdo->prepare("SELECT * FROM withdraw_requests WHERE id = ? AND status = 'pending'");
    $row->execute([$id]);
    $req = $row->fetch(PDO::FETCH_ASSOC);
    if ($req) {
        $pdo->beginTransaction();
        try {
            $upd = $pdo->prepare("UPDATE wallets SET main_balance = main_balance - ?, total_withdrawal = total_withdrawal + ? WHERE user_id = ? AND main_balance >= ?");
            $upd->execute([$req['amount'], $req['amount'], $req['user_id'], $req['amount']]);
            if ($upd->rowCount() === 0) {
                $pdo->rollBack();
                $message = '<div class="alert alert-danger fw-bold">Insufficient user balance. Cannot approve.</div>';
            } else {
                $pdo->prepare("UPDATE withdraw_requests SET status = 'approved' WHERE id = ?")->execute([$id]);
                $pdo->commit();
                $message = '<div class="alert alert-success fw-bold"><i class="fas fa-check"></i> Withdrawal approved & balance deducted.</div>';
            }
        } catch (Exception $e) {
            $pdo->rollBack();
            $message = '<div class="alert alert-danger">Error: ' . htmlspecialchars($e->getMessage()) . '</div>';
        }
    }
}
// Reject
if (isset($_GET['reject'])) {
    $id = (int)$_GET['reject'];
    $pdo->prepare("UPDATE withdraw_requests SET status = 'rejected' WHERE id = ? AND status = 'pending'")->execute([$id]);
    $message = '<div class="alert alert-warning fw-bold"><i class="fas fa-times"></i> Withdrawal rejected.</div>';
}

$list = $pdo->query("
    SELECT w.*, u.username, u.mobile
    FROM withdraw_requests w
    LEFT JOIN users u ON u.id = w.user_id
    ORDER BY w.id DESC
    LIMIT 100
")->fetchAll(PDO::FETCH_ASSOC);

$pageTitle = 'Withdraw Requests';
require_once 'includes/header.php';
?>
<?= $message ?>
<div class="custom-card">
    <div class="custom-card-header"><i class="fas fa-paper-plane me-2"></i> User Withdraw Requests</div>
    <div class="table-responsive">
        <table class="table table-hover mb-0">
            <thead class="table-light">
                <tr>
                    <th>ID</th>
                    <th>User</th>
                    <th>Amount</th>
                    <th>Method</th>
                    <th>Date</th>
                    <th>Status</th>
                    <th class="text-end">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($list)): ?>
                    <tr><td colspan="7" class="text-center py-4 text-muted">No withdraw requests.</td></tr>
                <?php else: foreach ($list as $r): ?>
                    <tr>
                        <td>#<?= $r['id'] ?></td>
                        <td><?= htmlspecialchars($r['username'] ?? '-') ?><br><small class="text-muted"><?= htmlspecialchars($r['mobile'] ?? '') ?></small></td>
                        <td class="fw-bold">₹<?= number_format($r['amount'], 2) ?></td>
                        <td><span class="badge bg-secondary"><?= htmlspecialchars($r['payment_method'] ?? '') ?></span></td>
                        <td><small><?= $r['created_at'] ?></small></td>
                        <td>
                            <?php if ($r['status'] === 'pending'): ?>
                                <span class="badge bg-warning">Pending</span>
                            <?php elseif ($r['status'] === 'approved'): ?>
                                <span class="badge bg-success">Approved</span>
                            <?php else: ?>
                                <span class="badge bg-danger">Rejected</span>
                            <?php endif; ?>
                        </td>
                        <td class="text-end">
                            <?php if ($r['status'] === 'pending'): ?>
                                <a href="?approve=<?= $r['id'] ?>" class="btn btn-sm btn-success" onclick="return confirm('Approve this withdrawal?');"><i class="fas fa-check"></i> Approve</a>
                                <a href="?reject=<?= $r['id'] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Reject this withdrawal?');"><i class="fas fa-times"></i> Reject</a>
                            <?php else: ?>—<?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>
</div>
<?php require_once 'includes/footer.php'; ?>
