<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();

// Redirect to login if the admin is not authenticated
if (!isset($_SESSION['admin_id'])) {
    header("Location: index.php");
    exit();
}

// Include Database Connection
require_once "../account/include/db.php";

// --- ACTION LOGIC (Approve / Decline / Delete) ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && isset($_POST['trans_id'])) {
    $trans_id = (int)$_POST['trans_id'];
    $action = $_POST['action'];

    // 1. DELETE ACTION
    if ($action === 'delete') {
        $del_query = "DELETE FROM `transactions` WHERE `id` = ?";
        if ($stmt = mysqli_prepare($conn, $del_query)) {
            mysqli_stmt_bind_param($stmt, "i", $trans_id);
            if (mysqli_stmt_execute($stmt)) {
                $_SESSION['swal_success'] = "Withdrawal record deleted.";
                $_SESSION['swal_title'] = "Deleted";
            }
            mysqli_stmt_close($stmt);
        }
    } 
    
    // 2. APPROVE / DECLINE ACTION
    else {
        // Fetch transaction details safely
        $fetch_query = "SELECT t.user_id, t.amount, t.status, u.full_name 
                        FROM `transactions` t 
                        JOIN `users` u ON t.user_id = u.id 
                        WHERE t.id = ? LIMIT 1";
        
        if ($stmt = mysqli_prepare($conn, $fetch_query)) {
            mysqli_stmt_bind_param($stmt, "i", $trans_id);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_bind_result($stmt, $tr_user_id, $tr_amount, $tr_status, $tr_full_name);
            
            if (mysqli_stmt_fetch($stmt)) {
                $user_id = $tr_user_id;
                $amount = $tr_amount;
                $status = $tr_status;
                $full_name = $tr_full_name;
                mysqli_stmt_close($stmt);

                if ($status === 'pending') {
                    if ($action === 'approve') {
                        // Mark as completed (Money is usually already deducted on request)
                        $update_t = "UPDATE `transactions` SET `status` = 'completed' WHERE `id` = ?";
                        $stmt_t = mysqli_prepare($conn, $update_t);
                        mysqli_stmt_bind_param($stmt_t, "i", $trans_id);
                        
                        if (mysqli_stmt_execute($stmt_t)) {
                            $_SESSION['swal_success'] = "Withdrawal of $" . number_format($amount, 2) . " marked as completed.";
                            $_SESSION['swal_title'] = "Approved";
                        }
                        mysqli_stmt_close($stmt_t);

                    } elseif ($action === 'decline') {
                        // Mark failed AND Refund the money to user balance
                        $update_t = "UPDATE `transactions` SET `status` = 'failed' WHERE `id` = ?";
                        $stmt_t = mysqli_prepare($conn, $update_t);
                        mysqli_stmt_bind_param($stmt_t, "i", $trans_id);
                        
                        $update_u = "UPDATE `users` SET `balance` = `balance` + ? WHERE `id` = ?";
                        $stmt_u = mysqli_prepare($conn, $update_u);
                        mysqli_stmt_bind_param($stmt_u, "di", $amount, $user_id);

                        if (mysqli_stmt_execute($stmt_t) && mysqli_stmt_execute($stmt_u)) {
                            $_SESSION['swal_success'] = "Request declined. Funds refunded to " . $full_name;
                            $_SESSION['swal_title'] = "Declined & Refunded";
                        }
                        mysqli_stmt_close($stmt_t);
                        mysqli_stmt_close($stmt_u);
                    }
                }
            } else { mysqli_stmt_close($stmt); }
        }
    }
    header("Location: manage_withdrawals.php?page=" . (isset($_GET['page']) ? (int)$_GET['page'] : 1));
    exit();
}

// --- PAGINATION ---
$limit = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

$total_res = mysqli_query($conn, "SELECT COUNT(*) as total FROM `transactions` WHERE `type` = 'withdrawal'");
$total_data = mysqli_fetch_assoc($total_res);
$total_records = $total_data['total'] ?? 0;
$total_pages = ceil($total_records / $limit);

$query = "SELECT t.*, u.username, u.full_name 
          FROM `transactions` t 
          JOIN `users` u ON t.user_id = u.id 
          WHERE t.type = 'withdrawal' 
          ORDER BY t.created_at DESC 
          LIMIT $limit OFFSET $offset";
$result = mysqli_query($conn, $query);

include 'includes/header.php';
include 'includes/sidebar.php';
?>

<style>
    body { font-family: 'Inter', sans-serif !important; }
    .status-pill { padding: 2px 8px; border-radius: 4px; font-size: 10px; font-weight: 700; text-transform: uppercase; }
    .pagination-btn { transition: all 0.2s; border: 1px solid #1e293b; }
    .pagination-btn.active { background: #3b82f6; border-color: #3b82f6; color: white; }
</style>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<main class="md:ml-64 p-4 md:p-6 min-h-[calc(100vh-65px)] bg-slate-950 relative z-10">
    
    <div class="mb-8">
        <div class="text-[10px] font-bold text-blue-500 tracking-widest uppercase mb-1">Premiumtrustglobal Admin</div>
        <h1 class="text-3xl font-bold text-white tracking-tight">Withdrawal Requests</h1>
        <p class="text-slate-400 mt-1 text-sm">Managing <?php echo $total_records; ?> payout requests</p>
    </div>

    <div class="bg-slate-900 border border-slate-800 rounded-xl overflow-hidden shadow-2xl flex flex-col">
        <div class="overflow-x-auto">
            <table class="w-full text-left border-collapse min-w-[900px]">
                <thead>
                    <tr class="border-b border-slate-800 bg-slate-950 text-xs text-slate-400 uppercase tracking-widest">
                        <th class="p-4">User</th>
                        <th class="p-4">Amount</th>
                        <th class="p-4">Method / Destination</th>
                        <th class="p-4">Status</th>
                        <th class="p-4 text-right">Actions</th>
                    </tr>
                </thead>
                <tbody class="text-sm text-slate-300 divide-y divide-slate-800/50">
                    <?php if($result && mysqli_num_rows($result) > 0): ?>
                        <?php while ($row = mysqli_fetch_assoc($result)): ?>
                        <tr class="hover:bg-slate-800/30 transition-colors">
                            <td class="p-4">
                                <div class="font-bold text-slate-100"><?php echo htmlspecialchars($row['full_name']); ?></div>
                                <div class="text-[11px] text-slate-500">@<?php echo htmlspecialchars($row['username']); ?> • <?php echo date('M d, Y', strtotime($row['created_at'])); ?></div>
                            </td>
                            <td class="p-4">
                                <span class="text-red-400 font-mono font-bold">-$<?php echo number_format($row['amount'], 2); ?></span>
                            </td>
                            <td class="p-4">
                                <div class="text-slate-200 text-xs font-semibold uppercase"><?php echo htmlspecialchars($row['method']); ?></div>
                                <div class="text-[10px] text-slate-500 font-mono truncate max-w-[200px]"><?php echo htmlspecialchars($row['ref'] ?? 'No address provided'); ?></div>
                            </td>
                            <td class="p-4">
                                <?php if($row['status'] === 'pending'): ?>
                                    <span class="status-pill bg-amber-500/10 text-amber-500 border border-amber-500/20">Pending</span>
                                <?php elseif($row['status'] === 'completed'): ?>
                                    <span class="status-pill bg-emerald-500/10 text-emerald-500 border border-emerald-500/20">Paid</span>
                                <?php else: ?>
                                    <span class="status-pill bg-red-500/10 text-red-500 border border-red-500/20">Declined</span>
                                <?php endif; ?>
                            </td>
                            <td class="p-4 text-right">
                                <div class="flex justify-end gap-3 items-center">
                                    <?php if($row['status'] === 'pending'): ?>
                                        <form method="POST" class="inline m-0">
                                            <input type="hidden" name="trans_id" value="<?php echo $row['id']; ?>">
                                            <input type="hidden" name="action" value="approve">
                                            <button type="button" onclick="confirmWithdraw(this.form, 'approve')" class="text-emerald-500 font-bold text-[10px] uppercase">Approve</button>
                                        </form>
                                        <form method="POST" class="inline m-0">
                                            <input type="hidden" name="trans_id" value="<?php echo $row['id']; ?>">
                                            <input type="hidden" name="action" value="decline">
                                            <button type="button" onclick="confirmWithdraw(this.form, 'decline')" class="text-orange-500 font-bold text-[10px] uppercase">Decline</button>
                                        </form>
                                    <?php endif; ?>

                                    <form method="POST" class="inline m-0">
                                        <input type="hidden" name="trans_id" value="<?php echo $row['id']; ?>">
                                        <input type="hidden" name="action" value="delete">
                                        <button type="button" onclick="confirmWithdraw(this.form, 'delete')" class="bg-red-500/10 text-red-500 p-1.5 rounded hover:bg-red-500 hover:text-white transition-all">
                                            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr><td colspan="5" class="p-12 text-center text-slate-500 italic">No withdrawal requests found.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <?php if($total_pages > 1): ?>
        <div class="p-4 border-t border-slate-800 bg-slate-900/50 flex items-center justify-between">
            <div class="text-xs text-slate-500">Page <?php echo $page; ?> of <?php echo $total_pages; ?></div>
            <div class="flex gap-1">
                <?php if($page > 1): ?>
                    <a href="?page=<?php echo $page - 1; ?>" class="pagination-btn px-3 py-1 rounded text-xs text-slate-400">Prev</a>
                <?php endif; ?>
                <?php for($i = max(1, $page-1); $i <= min($total_pages, $page+1); $i++): ?>
                    <a href="?page=<?php echo $i; ?>" class="pagination-btn px-3 py-1 rounded text-xs <?php echo ($i == $page) ? 'active' : 'text-slate-400'; ?>"><?php echo $i; ?></a>
                <?php endfor; ?>
                <?php if($page < $total_pages): ?>
                    <a href="?page=<?php echo $page + 1; ?>" class="pagination-btn px-3 py-1 rounded text-xs text-slate-400">Next</a>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
</main>

<script>
function confirmWithdraw(form, type) {
    let title = 'Process Withdrawal?';
    let text = 'Verify payout details before confirming.';
    let icon = 'question';
    let btnColor = '#3b82f6';

    if(type === 'delete') {
        title = 'Delete record?';
        text = 'This will permanently remove this request from logs.';
        icon = 'warning';
        btnColor = '#ef4444';
    } else if(type === 'decline') {
        title = 'Decline payout?';
        text = 'The amount will be refunded to the user\'s balance.';
        icon = 'error';
        btnColor = '#f59e0b';
    } else if(type === 'approve') {
        title = 'Confirm Payment?';
        text = 'Ensure you have sent the funds to the user\'s address.';
        icon = 'success';
        btnColor = '#10b981';
    }

    Swal.fire({
        title: title,
        text: text,
        icon: icon,
        showCancelButton: true,
        confirmButtonColor: btnColor,
        cancelButtonColor: '#1e293b',
        confirmButtonText: 'Proceed',
        background: '#0f172a',
        color: '#f1f5f9'
    }).then((result) => { if (result.isConfirmed) form.submit(); });
}

<?php if (isset($_SESSION['swal_success'])): ?>
    Swal.fire({ title: '<?php echo $_SESSION['swal_title']; ?>', text: '<?php echo $_SESSION['swal_success']; ?>', icon: 'success', background: '#0f172a', color: '#f1f5f9', confirmButtonColor: '#3b82f6' });
    <?php unset($_SESSION['swal_success'], $_SESSION['swal_title']); ?>
<?php endif; ?>
</script>

<?php include 'includes/footer.php'; ?>