<?php
require '../includes/db.php';
require 'includes/admin_auth.php';

// Mark as Processing
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['mark_processing'])) {
    $id = intval($_POST['processing_id']);
    $txn_id = trim($_POST['transaction_ids']);

    $stmt = $pdo->prepare("SELECT * FROM withdrawal_requests WHERE id = ?");
    $stmt->execute([$id]);
    $request = $stmt->fetch();

    if ($request && $request['status'] === 'pending') {
        $pdo->prepare("UPDATE withdrawal_requests SET status = 'processing', transaction_ids = ? WHERE id = ?")
            ->execute([$txn_id, $id]);
        header("Location: payouts.php");
        exit();
    }
}

// Approve with Transaction ID
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['approve_with_txn'])) {
    $id = intval($_POST['approve_id']);
    $txn_id = trim($_POST['transaction_ids']);

    $stmt = $pdo->prepare("SELECT * FROM withdrawal_requests WHERE id = ?");
    $stmt->execute([$id]);
    $request = $stmt->fetch();

    if ($request && in_array($request['status'], ['pending', 'processing'])) {
        $pdo->prepare("UPDATE withdrawal_requests SET status = 'success', transaction_ids = ? WHERE id = ?")
            ->execute([$txn_id, $id]);
        header("Location: payouts.php");
        exit();
    }
}

// Reject Request
if (isset($_GET['action'], $_GET['id']) && $_GET['action'] === 'reject') {
    $id = intval($_GET['id']);

    $stmt = $pdo->prepare("SELECT * FROM withdrawal_requests WHERE id = ?");
    $stmt->execute([$id]);
    $request = $stmt->fetch();

    if ($request && in_array($request['status'], ['pending', 'processing'])) {
        $user_id = $request['user_id'];
        $totalRefund = $request['total_deducted'];

        // Refund balance
        $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?")->execute([$totalRefund, $user_id]);

        // Update request status
        $pdo->prepare("UPDATE withdrawal_requests SET status = 'failed' WHERE id = ?")->execute([$id]);

        header("Location: payouts.php");
        exit();
    }
}

// Fetch all requests
$query = "
    SELECT wr.*, u.name, u.username
    FROM withdrawal_requests wr
    JOIN users u ON u.id = wr.user_id
    ORDER BY wr.id DESC
";
$requests = $pdo->query($query)->fetchAll();
?>

<!DOCTYPE html>
<html>
<head>
    <title>Payout Requests</title>
    <meta charset="UTF-8">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <style>
        body { background-color: #f8f9fa; font-family: 'Segoe UI', sans-serif; }
        .page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; }
        .card-box { background-color: #fff; border-radius: 10px; box-shadow: 0 2px 6px rgba(0,0,0,0.08); padding: 20px; }
        .badge-success { background-color: #28a745; }
        .badge-pending { background-color: #ffc107; color: #212529; }
        .badge-failed { background-color: #dc3545; }
        .badge-processing { background-color: #17a2b8; }
        .table thead { background-color: #343a40; color: #fff; }
        .action-btns a, .action-btns button { margin-right: 5px; }
        small { font-size: 90%; }
    </style>
</head>
<body class="p-4">
    <div class="container">
        <div class="page-header">
            <h2><i class="bi bi-wallet2"></i> Withdrawal / Payout Requests</h2>
            <a href="dashboard.php" class="btn btn-secondary"><i class="bi bi-house-door"></i> Back to Dashboard</a>
        </div>

        <div class="card-box">
            <div class="table-responsive">
                <table class="table table-bordered table-hover align-middle">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>User</th>
                            <th>Method</th>
                            <th>Currency</th>
                            <th>Amount</th>
                            <th>Fee</th>
                            <th>Total Deducted</th>
                            <th>Status</th>
                            <th>Transaction ID</th>
                            <th>Details (Snapshot)</th>
                            <th class="text-center">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($requests as $req): ?>
                        <tr>
                            <td><?= $req['id'] ?></td>
                            <td>
                                <strong><?= htmlspecialchars($req['name']) ?></strong><br>
                                <small><?= htmlspecialchars($req['username']) ?></small>
                            </td>
                            <td><span class="badge bg-info text-dark"><?= strtoupper($req['method']) ?></span></td>
                            <td><?= htmlspecialchars($req['currency']) ?></td>
                            <td><strong class="text-success"><?= number_format($req['amount'], 2) ?></strong></td>
                            <td><?= number_format($req['fee'], 2) ?></td>
                            <td><strong><?= number_format($req['total_deducted'], 2) ?></strong></td>
                            <td>
                                <?php
                                    $statusClass = 'secondary';
                                    if ($req['status'] === 'success') $statusClass = 'success';
                                    elseif ($req['status'] === 'pending') $statusClass = 'pending';
                                    elseif ($req['status'] === 'failed') $statusClass = 'failed';
                                    elseif ($req['status'] === 'processing') $statusClass = 'processing';
                                ?>
                                <span class="badge badge-<?= $statusClass ?>"><?= ucfirst($req['status']) ?></span>
                            </td>
                            <td><?= htmlspecialchars($req['transaction_ids'] ?: '-') ?></td>
                            <td>
                                <?php
                                    $details = json_decode($req['details_json'] ?? '', true);
                                    if ($details):
                                        if ($req['method'] === 'bank'):
                                ?>
                                            <small>
                                                <strong><?= htmlspecialchars($details['account_holder'] ?? 'N/A') ?></strong><br>
                                                A/C: <?= htmlspecialchars($details['bank_account'] ?? 'N/A') ?><br>
                                                IFSC: <?= htmlspecialchars($details['ifsc_code'] ?? 'N/A') ?>
                                            </small>
                                <?php
                                        elseif ($req['method'] === 'usdt'):
                                ?>
                                            <small><strong>USDT:</strong> <?= htmlspecialchars($details['usdt_address'] ?? 'N/A') ?></small>
                                <?php
                                        elseif ($req['method'] === 'pkr'):
                                ?>
                                            <small>
                                                <strong>CNIC:</strong> <?= htmlspecialchars($details['jazzcash_cnic'] ?? 'N/A') ?><br>
                                                JazzCash: <?= htmlspecialchars($details['jazzcash_account'] ?? 'N/A') ?><br>
                                                EasyPaisa: <?= htmlspecialchars($details['easypaisa_account'] ?? 'N/A') ?>
                                            </small>
                                <?php
                                        endif;
                                    else:
                                ?>
                                        <small class="text-muted">No Snapshot Saved</small>
                                <?php endif; ?>
                            </td>
                            <td class="text-center action-btns">
                                <?php if (in_array($req['status'], ['pending', 'processing'])): ?>
                                    <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#approveModal<?= $req['id'] ?>">
                                        <i class="bi bi-check-circle"></i> Update
                                    </button>
                                    <a href="?action=reject&id=<?= $req['id'] ?>" class="btn btn-sm btn-outline-danger">
                                        <i class="bi bi-x-circle"></i> Reject
                                    </a>
                                <?php else: ?>
                                    <span class="text-muted">—</span>
                                <?php endif; ?>
                            </td>
                        </tr>

                        <!-- Modal -->
                        <div class="modal fade" id="approveModal<?= $req['id'] ?>" tabindex="-1" aria-hidden="true">
                            <div class="modal-dialog">
                                <form method="post">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <h5 class="modal-title">Update Request #<?= $req['id'] ?></h5>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                        </div>
                                        <div class="modal-body">
                                            <input type="hidden" name="approve_id" value="<?= $req['id'] ?>">
                                            <input type="hidden" name="processing_id" value="<?= $req['id'] ?>">
                                            <div class="mb-3">
                                                <label class="form-label">Transaction ID</label>
                                                <input type="text" name="transaction_ids" class="form-control" required>
                                            </div>
                                        </div>
                                        <div class="modal-footer">
                                            <button name="approve_with_txn" class="btn btn-success">Mark as Success</button>
                                            <button name="mark_processing" class="btn btn-warning">Mark as Processing</button>
                                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</body>
</html>
