<?php
require_once "config.php";

session_start();

date_default_timezone_set("Asia/Dhaka");

if (!isset($conn) || !($conn instanceof mysqli)) {
    die(json_encode(["status" => "error", "message" => "Database connection error"]));
}
$conn->set_charset("utf8mb4");

if (!function_exists('base64url_encode')) {
    function base64url_encode($data) {
        return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
    }
}

if (!function_exists('getAccessToken')) {
    function getAccessToken($jsonFilePath) {
        if (!file_exists($jsonFilePath)) return false;
        $credentials = json_decode(file_get_contents($jsonFilePath), true);
        if (!$credentials || !isset($credentials['private_key'])) return false;

        $clientEmail = $credentials['client_email'];
        $privateKey  = $credentials['private_key'];

        $header = json_encode(['alg' => 'RS256', 'typ' => 'JWT']);
        $now = time();
        $payload = json_encode([
            'iss'   => $clientEmail,
            'scope' => 'https://www.googleapis.com/auth/cloud-platform',
            'aud'   => 'https://oauth2.googleapis.com/token',
            'exp'   => $now + 3600,
            'iat'   => $now
        ]);

        $unsignedJwt = base64url_encode($header) . "." . base64url_encode($payload);
        $signature = '';
        openssl_sign($unsignedJwt, $signature, $privateKey, OPENSSL_ALGO_SHA256);
        $jwt = $unsignedJwt . "." . base64url_encode($signature);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://oauth2.googleapis.com/token');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', 'assertion' => $jwt]));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $response = curl_exec($ch);
        curl_close($ch);

        $responseData = json_decode($response, true);
        return isset($responseData['access_token']) ? $responseData['access_token'] : false;
    }
}

function sendFCM_v1($fcm_key, $title, $body) {
    if (empty($fcm_key)) return false;
    $serviceAccountFile = 'noti.json'; 
    if (!file_exists($serviceAccountFile)) return false;

    $accessToken = getAccessToken($serviceAccountFile);
    if (!$accessToken) return false;

    $credentials = json_decode(file_get_contents($serviceAccountFile), true);
    $projectId = $credentials['project_id'];
    $url = "https://fcm.googleapis.com/v1/projects/" . $projectId . "/messages:send";

    $notificationMap = [
        "title" => $title,
        "body"  => $body,
        "image" => "",
        "extra" => ""
    ];

    $messagePayload = [
        "token" => $fcm_key,
        "data"  => $notificationMap
    ];

    $postData = json_encode(["message" => $messagePayload]);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $accessToken,
        'Content-Type: application/json; UTF-8'
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

function session_alive(int $timeout): bool {
    if (empty($_SESSION['auth_logged_in']) || empty($_SESSION['auth_last_activity'])) return false;
    if ((time() - (int)$_SESSION['auth_last_activity']) > $timeout) {
        $_SESSION = [];
        session_destroy();
        return false;
    }
    $_SESSION['auth_last_activity'] = time();
    return true;
}

if (!session_alive(1200)) {
    if (isset($_GET['api'])) {
        die(json_encode(["status" => "unauthorized"]));
    }
    header("Location: admin_login.php");
    exit;
}

$role = $_SESSION['auth_role'] ?? '';
$sess_username = $_SESSION['auth_username'] ?? '';
$sess_password = $_SESSION['auth_password'] ?? '';

$canRead = false;
$canEdit = false;
$canDelete = false;

if ($role === 'admin') {
    $canRead = true;
    $canEdit = true;
    $canDelete = true;
} elseif ($role === 'permission') {
    $stmt = $conn->prepare("SELECT withdrawal_history_read, withdrawal_history_edit, withdrawal_history_delete FROM `Zabbar_Admin_Permission` WHERE username = ? AND password = ? LIMIT 1");
    $stmt->bind_param("ss", $sess_username, $sess_password);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($row = $res->fetch_assoc()) {
        $canRead = (strtolower(trim($row['withdrawal_history_read'] ?? '')) === 'yes' || $row['withdrawal_history_read'] == 1);
        $canEdit = (strtolower(trim($row['withdrawal_history_edit'] ?? '')) === 'yes' || $row['withdrawal_history_edit'] == 1);
        $canDelete = (strtolower(trim($row['withdrawal_history_delete'] ?? '')) === 'yes' || $row['withdrawal_history_delete'] == 1);
    }
    $stmt->close();
}

if (isset($_GET['api'])) {
    header('Content-Type: application/json');
    
    if (!$canRead) {
        echo json_encode(["status" => "error", "message" => "Permission denied."]);
        exit;
    }

    $action = $_GET['api'];

    if ($action === 'fetch') {
        $page = max(1, (int)($_GET['page'] ?? 1));
        $limit = 50;
        $offset = ($page - 1) * $limit;
        
        $filter = $_GET['filter'] ?? 'all';
        $whereClause = "1=1";
        
        if ($filter === 'success') {
            $whereClause = "LOWER(TRIM(w.status)) IN ('success', 'approved')";
        } elseif ($filter === 'failed') {
            $whereClause = "LOWER(TRIM(w.status)) IN ('failed', 'rejected')";
        } elseif ($filter === 'pending') {
            $whereClause = "LOWER(TRIM(w.status)) NOT IN ('success', 'approved', 'failed', 'rejected')";
        }

        $sql = "SELECT w.id, w.username, w.email, w.method, w.number, w.amount, w.trxid, w.status, w.date, w.time, w.fcm, u.profile_pic 
                FROM withdraw w 
                LEFT JOIN users u ON w.username = u.username 
                WHERE $whereClause 
                ORDER BY w.id DESC LIMIT ? OFFSET ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ii", $limit, $offset);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $data = [];
        while ($row = $result->fetch_assoc()) {
            $data[] = $row;
        }
        $stmt->close();

        echo json_encode([
            "status" => "success",
            "data" => $data,
            "page" => $page
        ]);
        exit;
    }

    if ($action === 'approve' && $_SERVER['REQUEST_METHOD'] === 'POST') {
        if (!$canEdit) {
            echo json_encode(["status" => "error", "message" => "Edit permission denied."]);
            exit;
        }

        $id = (int)$_POST['id'];

        $conn->begin_transaction();
        try {
            $stmt = $conn->prepare("SELECT username, amount, status FROM withdraw WHERE id = ? FOR UPDATE");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $res = $stmt->get_result();
            if ($res->num_rows === 0) {
                throw new Exception("Record not found.");
            }
            $row = $res->fetch_assoc();
            $stmt->close();

            $currentStatus = strtolower(trim($row['status']));
            if ($currentStatus === 'success' || $currentStatus === 'approved') {
                throw new Exception("This transaction is already success.");
            }

            $username = $row['username'];
            $amount = (float)$row['amount'];

            // If previously failed, we need to deduct from winning again
            if ($currentStatus === 'failed' || $currentStatus === 'rejected') {
                // Check winning balance
                $stmtCheck = $conn->prepare("SELECT winning FROM users WHERE username = ? FOR UPDATE");
                $stmtCheck->bind_param("s", $username);
                $stmtCheck->execute();
                $resCheck = $stmtCheck->get_result();
                if ($userRow = $resCheck->fetch_assoc()) {
                    if ((float)$userRow['winning'] < $amount) {
                        throw new Exception("Insufficient winning balance to approve again.");
                    }
                    // Deduct from winning
                    $stmtDeduct = $conn->prepare("UPDATE users SET winning = winning - ? WHERE username = ?");
                    $stmtDeduct->bind_param("ds", $amount, $username);
                    $stmtDeduct->execute();
                    $stmtDeduct->close();
                } else {
                    throw new Exception("User not found.");
                }
                $stmtCheck->close();
            }
            // If pending -> approve, no deduction needed (already deducted at request time)

            // Mark as success
            $stmtUpdateStatus = $conn->prepare("UPDATE withdraw SET status = 'success' WHERE id = ?");
            $stmtUpdateStatus->bind_param("i", $id);
            $stmtUpdateStatus->execute();
            $stmtUpdateStatus->close();

            // FCM
            $stmtFcm = $conn->prepare("SELECT fcm_key FROM users WHERE username = ? LIMIT 1");
            $stmtFcm->bind_param("s", $username);
            $stmtFcm->execute();
            $fcmRes = $stmtFcm->get_result();
            $fcmToken = '';
            if ($fcmRow = $fcmRes->fetch_assoc()) {
                $fcmToken = $fcmRow['fcm_key'] ?? '';
            }
            $stmtFcm->close();

            if (!empty($fcmToken)) {
                $title = "💸 উইথড্র সফল";
                $body = "অভিনন্দন! আপনার ৳{$amount} উইথড্র অনুরোধ সফলভাবে সম্পন্ন হয়েছে। নির্ধারিত পেমেন্ট মাধ্যমে টাকা পাঠানো হয়েছে। আমাদের সেবা ব্যবহার করার জন্য ধন্যবাদ। ❤️";
                sendFCM_v1($fcmToken, $title, $body);
            }

            $conn->commit();
            echo json_encode(["status" => "success"]);
        } catch (Exception $e) {
            $conn->rollback();
            echo json_encode(["status" => "error", "message" => $e->getMessage()]);
        }
        exit;
    }

    if ($action === 'reject' && $_SERVER['REQUEST_METHOD'] === 'POST') {
        if (!$canEdit) {
            echo json_encode(["status" => "error", "message" => "Edit permission denied."]);
            exit;
        }

        $id = (int)$_POST['id'];
        
        $conn->begin_transaction();
        try {
            $stmtCheck = $conn->prepare("SELECT status, username, amount FROM withdraw WHERE id = ? FOR UPDATE");
            $stmtCheck->bind_param("i", $id);
            $stmtCheck->execute();
            $resCheck = $stmtCheck->get_result();
            if ($row = $resCheck->fetch_assoc()) {
                $currStatus = strtolower(trim($row['status']));
                if ($currStatus === 'success' || $currStatus === 'approved') {
                    throw new Exception("Cannot fail a successful transaction.");
                }
                if ($currStatus === 'failed' || $currStatus === 'rejected') {
                    throw new Exception("Already failed.");
                }
                $username = $row['username'];
                $amount = (float)$row['amount'];
            } else {
                throw new Exception("Record not found.");
            }
            $stmtCheck->close();

            // Mark as failed
            $stmt = $conn->prepare("UPDATE withdraw SET status = 'failed' WHERE id = ?");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $stmt->close();

            // Refund to winning
            $stmtRefund = $conn->prepare("UPDATE users SET winning = winning + ? WHERE username = ?");
            $stmtRefund->bind_param("ds", $amount, $username);
            $stmtRefund->execute();
            $stmtRefund->close();

            // FCM
            $stmtFcm = $conn->prepare("SELECT fcm_key FROM users WHERE username = ? LIMIT 1");
            $stmtFcm->bind_param("s", $username);
            $stmtFcm->execute();
            $fcmRes = $stmtFcm->get_result();
            $fcmToken = '';
            if ($fcmRow = $fcmRes->fetch_assoc()) {
                $fcmToken = $fcmRow['fcm_key'] ?? '';
            }
            $stmtFcm->close();

            if (!empty($fcmToken)) {
                $title = "❌ উইথড্র ব্যর্থ";
                $body = "দুঃখিত! আপনার ৳{$amount} উইথড্র অনুরোধটি সম্পন্ন করা যায়নি। প্রয়োজনে আবার অনুরোধ করুন বা সাপোর্টে যোগাযোগ করুন।";
                sendFCM_v1($fcmToken, $title, $body);
            }

            $conn->commit();
            echo json_encode(["status" => "success"]);
        } catch (Exception $e) {
            $conn->rollback();
            echo json_encode(["status" => "error", "message" => $e->getMessage()]);
        }
        exit;
    }

    if ($action === 'delete' && $_SERVER['REQUEST_METHOD'] === 'POST') {
        if (!$canDelete) {
            echo json_encode(["status" => "error", "message" => "Delete permission denied."]);
            exit;
        }
        $id = (int)$_POST['id'];
        $stmt = $conn->prepare("DELETE FROM withdraw WHERE id = ?");
        $stmt->bind_param("i", $id);
        if ($stmt->execute()) {
            echo json_encode(["status" => "success"]);
        } else {
            echo json_encode(["status" => "error", "message" => $stmt->error]);
        }
        $stmt->close();
        exit;
    }
    
    exit;
}

if (!$canRead) {
    die("<!DOCTYPE html><html><head><title>Access Denied</title></head><body style='font-family:system-ui; display:grid; place-items:center; height:100vh; margin:0; background:#f8fafc;'><div style='text-align:center; padding:40px; background:#fff; border-radius:16px; box-shadow:0 10px 15px -3px rgba(0,0,0,0.1);'><h2 style='color:#be123c; margin-top:0;'>Access Denied</h2><p style='color:#334155;'>You do not have permission to view withdrawal history.</p><a href='index.php' style='display:inline-block; margin-top:16px; padding:10px 20px; background:#4f46e5; color:#fff; text-decoration:none; border-radius:8px; font-weight:600;'>Return Dashboard</a></div></body></html>");
}
require_once "header.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Withdrawal History</title>
    <style>
        :root {
            --slate-50: #f8fafc;
            --slate-100: #f1f5f9;
            --slate-200: #e2e8f0;
            --slate-700: #334155;
            --slate-900: #0f172a;
            --primary: #4f46e5;
            --primary-light: #eeebff;
            --emerald-500: #10b981;
            --rose-500: #f43f5e;
            --amber-500: #f59e0b;
            --white: #ffffff;
            --shadow-sm: 0 1px 3px 0 rgba(0,0,0,0.05);
            --shadow-md: 0 4px 6px -1px rgba(0,0,0,0.05);
            --radius-md: 12px;
            --radius-lg: 16px;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Inter', system-ui, sans-serif; }
        body { background-color: var(--slate-50); color: var(--slate-900); display: flex; height: 100vh; overflow: hidden; }
        
        .main-content { flex-grow: 1; display: flex; flex-direction: column; overflow: hidden; }
        .header { padding: 24px 40px; background: var(--white); border-bottom: 1px solid var(--slate-200); display: flex; justify-content: space-between; align-items: center; }
        .header-title h1 { font-size: 24px; font-weight: 800; }
        
        .tabs { display: flex; gap: 16px; padding: 0 40px; background: var(--white); border-bottom: 1px solid var(--slate-200); }
        .tab-btn { background: none; border: none; padding: 16px 8px; font-size: 14px; font-weight: 600; color: var(--slate-700); cursor: pointer; border-bottom: 2px solid transparent; transition: 0.2s; }
        .tab-btn.active { color: var(--primary); border-bottom-color: var(--primary); }
        .tab-btn:hover:not(.active) { color: var(--slate-900); }

        .content-body { padding: 40px; overflow-y: auto; flex-grow: 1; scroll-behavior: smooth; }
        
        .table-container { background: var(--white); border-radius: var(--radius-lg); border: 1px solid var(--slate-200); box-shadow: var(--shadow-sm); overflow-x: auto; margin-bottom: 20px; }
        table { width: 100%; border-collapse: collapse; text-align: left; }
        th, td { padding: 16px 24px; border-bottom: 1px solid var(--slate-100); font-size: 14px; }
        th { background: var(--slate-50); font-weight: 700; color: var(--slate-700); white-space: nowrap; }
        td { color: var(--slate-900); vertical-align: middle; }
        tr:last-child td { border-bottom: none; }
        tr:hover td { background-color: var(--slate-50); }

        .user-block { display: flex; align-items: center; gap: 12px; }
        .user-avatar { width: 36px; height: 36px; border-radius: 50%; object-fit: cover; flex-shrink: 0; border: 2px solid var(--slate-200); }
        .user-details { display: flex; flex-direction: column; gap: 2px; overflow: hidden; }
        .user-details span { font-weight: 700; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .user-details small { color: var(--slate-700); font-size: 12px; }
        .amount-txt { font-weight: 800; color: var(--rose-500); font-size: 15px; }

        .badge { padding: 6px 12px; border-radius: 999px; font-size: 12px; font-weight: 700; display: inline-flex; align-items: center; gap: 4px; text-transform: capitalize; }
        .badge.pending { background: #fef3c7; color: #b45309; }
        .badge.success { background: #d1fae5; color: #047857; }
        .badge.failed { background: #fee2e2; color: #b91c1c; }

        .action-btns { display: flex; gap: 8px; flex-wrap: wrap; }
        .icon-btn { border: none; background: none; cursor: pointer; border-radius: 8px; padding: 8px; transition: 0.2s; display: inline-flex; align-items: center; justify-content: center; text-decoration: none; }
        .icon-btn svg { width: 18px; height: 18px; }
        .icon-btn.approve { color: var(--emerald-500); background: #ecfdf5; }
        .icon-btn.approve:hover { background: #d1fae5; transform: translateY(-2px); }
        .icon-btn.reject { color: var(--amber-500); background: #fffbeb; }
        .icon-btn.reject:hover { background: #fef3c7; transform: translateY(-2px); }
        .icon-btn.delete { color: var(--rose-500); background: #fff1f2; }
        .icon-btn.delete:hover { background: #ffe4e6; transform: translateY(-2px); }
        .icon-btn.history { color: var(--primary); background: var(--primary-light); }
        .icon-btn.history:hover { background: #e0e7ff; transform: translateY(-2px); }
        
        .loader { text-align: center; padding: 20px; color: var(--slate-700); font-weight: 600; font-size: 14px; display: none; }

        @media (max-width: 768px) { body { flex-direction: column; } .header, .tabs, .content-body { padding: 16px; } }
    </style>
</head>
<body>

<div class="main-content">
    <div class="header">
        <div class="header-title">
            <h1>Withdrawal History</h1>
        </div>
    </div>
    
    <div class="tabs">
        <button class="tab-btn active" onclick="setFilter('all', this)">All</button>
        <button class="tab-btn" onclick="setFilter('pending', this)">Pending</button>
        <button class="tab-btn" onclick="setFilter('success', this)">Success</button>
        <button class="tab-btn" onclick="setFilter('failed', this)">Failed</button>
    </div>
    
    <div class="content-body" id="scrollArea">
        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th>User Details</th>
                        <th>Payment Info</th>
                        <th>Amount</th>
                        <th>Transaction ID</th>
                        <th>Date & Time</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody id="dataTable"></tbody>
            </table>
        </div>
        <div class="loader" id="loader">Loading more records...</div>
        <div class="loader" id="noMore" style="display:none; color:var(--slate-400);">No more records.</div>
    </div>
</div>

<script>
    let currentPage = 1;
    let currentFilter = 'all';
    let isLoading = false;
    let hasMore = true;
    
    const canEdit = <?= $canEdit ? 'true' : 'false' ?>;
    const canDelete = <?= $canDelete ? 'true' : 'false' ?>;
    
    const tbody = document.getElementById('dataTable');
    const loader = document.getElementById('loader');
    const noMore = document.getElementById('noMore');
    const scrollArea = document.getElementById('scrollArea');

    function setFilter(filterType, btnElement) {
        document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
        btnElement.classList.add('active');
        currentFilter = filterType;
        loadData(true);
    }

    function loadData(reset = false) {
        if (isLoading) return;
        if (reset) {
            currentPage = 1;
            hasMore = true;
            tbody.innerHTML = '';
            noMore.style.display = 'none';
        }
        if (!hasMore) return;

        isLoading = true;
        loader.style.display = 'block';

        fetch(`?api=fetch&page=${currentPage}&filter=${currentFilter}`)
            .then(res => res.json())
            .then(res => {
                if (res.status === 'success') {
                    renderTable(res.data, reset);
                    if (res.data.length < 50) {
                        hasMore = false;
                        noMore.style.display = tbody.innerHTML !== '' ? 'block' : 'none';
                    }
                } else {
                    alert(res.message || "An error occurred fetching data.");
                }
            })
            .catch(err => console.error(err))
            .finally(() => {
                isLoading = false;
                loader.style.display = 'none';
            });
    }

    function renderTable(data, reset) {
        if (reset && data.length === 0) {
            tbody.innerHTML = `<tr><td colspan="7" style="text-align:center; padding: 40px; color: var(--slate-700);">No records found.</td></tr>`;
            return;
        }

        data.forEach(row => {
            let sRaw = (row.status || '').trim().toLowerCase();
            let sClass = 'pending';
            let dStatus = row.status || 'Pending';
            
            if (sRaw === 'success' || sRaw === 'approved') {
                sClass = 'success';
                dStatus = 'Success';
            } else if (sRaw === 'failed' || sRaw === 'rejected') {
                sClass = 'failed';
                dStatus = 'Failed';
            }

            let avatarHtml = '';
            if (row.profile_pic) {
                avatarHtml = `<img src="${row.profile_pic}" class="user-avatar" onerror="this.onerror=null; this.outerHTML='<div class=\'user-avatar\' style=\'background:var(--slate-200); display:grid; place-items:center; font-weight:700; color:var(--slate-700);\'>${(row.username || '?')[0].toUpperCase()}</div>';">`;
            } else {
                avatarHtml = `<div class="user-avatar" style="background:var(--slate-200); display:grid; place-items:center; font-weight:700; color:var(--slate-700); font-size:14px;">${(row.username || '?')[0].toUpperCase()}</div>`;
            }

            let moneyHistoryLink = `<a href="Usersmoneyhistory.php?username=${encodeURIComponent(row.username)}" class="icon-btn history" title="User Money History" onclick="event.stopPropagation();">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M12 6v12m-3-2.818l.879.659c1.171.879 3.07.879 4.242 0 1.172-.879 1.172-2.303 0-3.182C13.536 12.219 12.768 12 12 12c-.725 0-1.45-.22-2.003-.659-1.106-.879-1.106-2.303 0-3.182s2.9-.879 4.006 0l.415.33M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0z" /></svg>
            </a>`;

            let actionButtons = moneyHistoryLink;
            
            if (canEdit) {
                if (sClass !== 'success') {
                    actionButtons += `
                        <button class="icon-btn approve" onclick="handleAction('approve', ${row.id})" title="Mark as Success">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="m4.5 12.75 6 6 9-13.5" /></svg>
                        </button>
                    `;
                }
                if (sClass !== 'success' && sClass !== 'failed') {
                    actionButtons += `
                        <button class="icon-btn reject" onclick="handleAction('reject', ${row.id})" title="Mark as Failed">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12" /></svg>
                        </button>
                    `;
                }
            }
            if (canDelete) {
                actionButtons += `
                    <button class="icon-btn delete" onclick="handleAction('delete', ${row.id})" title="Delete Record">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0" /></svg>
                    </button>
                `;
            }

            let tr = document.createElement('tr');
            tr.innerHTML = `
                <td>
                    <div class="user-block">
                        ${avatarHtml}
                        <div class="user-details">
                            <span>${row.username || 'N/A'}</span>
                            <small>${row.email || 'No email'}</small>
                        </div>
                    </div>
                </td>
                <td>
                    <div class="user-details" style="display:flex; flex-direction:column; gap:2px;">
                        <span style="text-transform: capitalize;">${row.method || 'N/A'}</span>
                        <small>${row.number || 'N/A'}</small>
                    </div>
                </td>
                <td>
                    <div class="amount-txt">- ৳ ${row.amount || '0'}</div>
                </td>
                <td style="font-family: monospace; letter-spacing: 0.5px;">${row.trxid || 'N/A'}</td>
                <td>
                    <div class="user-details" style="display:flex; flex-direction:column; gap:2px;">
                        <span>${row.date || ''}</span>
                        <small>${row.time || ''}</small>
                    </div>
                </td>
                <td>
                    <div class="badge ${sClass}">
                        ${dStatus}
                    </div>
                </td>
                <td>
                    <div class="action-btns">
                        ${actionButtons}
                    </div>
                </td>
            `;
            tbody.appendChild(tr);
        });
    }

    scrollArea.addEventListener('scroll', () => {
        if (scrollArea.scrollTop + scrollArea.clientHeight >= scrollArea.scrollHeight - 50) {
            if (!isLoading && hasMore) {
                currentPage++;
                loadData(false);
            }
        }
    });

    function handleAction(action, id) {
        let msg = "";
        if (action === 'approve') msg = "Approve this withdrawal?";
        else if (action === 'reject') msg = "Mark this withdrawal as Failed? Amount will be refunded to winning.";
        else if (action === 'delete') msg = "Permanently delete this record?";

        if (!confirm(msg)) return;

        const formData = new FormData();
        formData.append('id', id);

        fetch(`?api=${action}`, { method: 'POST', body: formData })
            .then(res => res.json())
            .then(res => {
                if (res.status === 'success') {
                    loadData(true);
                } else {
                    alert(res.message || "An error occurred.");
                }
            })
            .catch(err => console.error(err));
    }

    window.onload = () => loadData(true);
</script>
</body>
</html>