<?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) {
        $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 Geft_Read, Geft_Edit, Geft_Delete FROM `Zabbar_Admin_Permission` WHERE username = ? AND password = ? LIMIT 1");
    if ($stmt) {
        $stmt->bind_param("ss", $sess_username, $sess_password);
        $stmt->execute();
        $res = $stmt->get_result();
        if ($row = $res->fetch_assoc()) {
            $canRead = (strtolower(trim($row['Geft_Read'] ?? '')) === 'yes' || $row['Geft_Read'] == 1);
            $canEdit = (strtolower(trim($row['Geft_Edit'] ?? '')) === 'yes' || $row['Geft_Edit'] == 1);
            $canDelete = (strtolower(trim($row['Geft_Delete'] ?? '')) === 'yes' || $row['Geft_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') {
        $limit = 10;
        $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
        if ($page < 1) $page = 1;
        $offset = ($page - 1) * $limit;

        $countQuery = $conn->query("SELECT COUNT(id) as total FROM gift_requests");
        $totalRows = $countQuery->fetch_assoc()['total'];
        $totalPages = ceil($totalRows / $limit);

        $sql = "SELECT gr.*, 
                       s.username AS sender_username, 
                       r.username AS receiver_username 
                FROM gift_requests gr 
                LEFT JOIN users s ON gr.sender_uid = s.uid 
                LEFT JOIN users r ON gr.receiver_uid = r.uid 
                ORDER BY gr.id DESC 
                LIMIT $limit OFFSET $offset";
                
        $result = $conn->query($sql);
        $data = [];
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $data[] = $row;
            }
        }
        
        echo json_encode([
            "status" => "success", 
            "data" => $data, 
            "totalPages" => $totalPages, 
            "currentPage" => $page
        ]);
        exit;
    }

    if ($action === 'process' && $_SERVER['REQUEST_METHOD'] === 'POST') {
        $id = (int)($_POST['id'] ?? 0);
        $type = strtolower(trim($_POST['type'] ?? ''));

        if ($type === 'success' || $type === 'approve') $type = 'approved';
        if ($type === 'fail' || $type === 'reject') $type = 'failed';

        if (($type === 'approved' || $type === 'failed') && !$canEdit) {
            echo json_encode(["status" => "error", "message" => "Edit permission denied."]);
            exit;
        }

        if ($type === 'delete' && !$canDelete) {
            echo json_encode(["status" => "error", "message" => "Delete permission denied."]);
            exit;
        }

        $conn->begin_transaction();

        try {
            $stmt = $conn->prepare("SELECT * FROM gift_requests WHERE id = ? FOR UPDATE");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $req = $stmt->get_result()->fetch_assoc();
            $stmt->close();

            if (!$req) {
                throw new Exception("Request not found in database.");
            }

            $current_status = strtolower(trim($req['status'] ?? 'pending'));
            if ($current_status === 'success') $current_status = 'approved';
            
            $sender_uid = (string)$req['sender_uid'];
            $receiver_uid = (string)$req['receiver_uid'];
            $total = (float)$req['total'];
            $amount = (float)$req['amount'];

            if ($type === 'approved') {
                if ($current_status === 'approved') {
                    throw new Exception("This request is already approved.");
                }

                $stmt = $conn->prepare("SELECT ban_reason FROM users WHERE uid = ? FOR UPDATE");
                $stmt->bind_param("s", $receiver_uid);
                $stmt->execute();
                $rxUser = $stmt->get_result()->fetch_assoc();
                $stmt->close();

                if (!$rxUser) {
                    throw new Exception("Receiver user does not exist.");
                }
                if (strtolower(trim($rxUser['ban_reason'] ?? '')) === 'ban') {
                    throw new Exception("Receiver user is banned.");
                }

                if ($current_status === 'failed') {
                    $stmt = $conn->prepare("SELECT balance FROM users WHERE uid = ? FOR UPDATE");
                    $stmt->bind_param("s", $sender_uid);
                    $stmt->execute();
                    $senderData = $stmt->get_result()->fetch_assoc();
                    $stmt->close();

                    if (!$senderData) {
                        throw new Exception("Sender user does not exist.");
                    }
                    if ((float)$senderData['balance'] < $total) {
                        throw new Exception("Sender does not have enough balance to re-approve.");
                    }

                    $stmt = $conn->prepare("UPDATE users SET balance = balance - ? WHERE uid = ?");
                    $stmt->bind_param("ds", $total, $sender_uid);
                    if (!$stmt->execute()) {
                        throw new Exception("Failed to deduct sender balance.");
                    }
                    $stmt->close();
                }

                $stmt = $conn->prepare("UPDATE gift_requests SET status = 'approved' WHERE id = ?");
                $stmt->bind_param("i", $id);
                if (!$stmt->execute()) {
                    throw new Exception("Failed to update request status in database.");
                }
                $stmt->close();

                $stmt = $conn->prepare("UPDATE users SET balance = balance + ? WHERE uid = ?");
                $stmt->bind_param("ds", $amount, $receiver_uid);
                if (!$stmt->execute()) {
                    throw new Exception("Failed to add balance to receiver.");
                }
                $stmt->close();

                $stmt_fcm = $conn->prepare("SELECT uid, fcm_key, username FROM users WHERE uid IN (?, ?)");
                $stmt_fcm->bind_param("ss", $sender_uid, $receiver_uid);
                $stmt_fcm->execute();
                $res_fcm = $stmt_fcm->get_result();
                $user_fcm_keys = [];
                $user_names = [];
                while($row = $res_fcm->fetch_assoc()){
                    $user_fcm_keys[$row['uid']] = $row['fcm_key'];
                    $user_names[$row['uid']] = $row['username'];
                }
                $stmt_fcm->close();

                $receiver_name = $user_names[$receiver_uid] ?? "UID: " . $receiver_uid;
                $sender_name   = $user_names[$sender_uid] ?? "UID: " . $sender_uid;

                $msg_sender = "অভিনন্দন! আপনার গিফট অনুরোধ সফলভাবে সম্পন্ন হয়েছে। ৳{$amount} সফলভাবে {$receiver_name}-এর অ্যাকাউন্টে পাঠানো হয়েছে। আমাদের সেবা ব্যবহার করার জন্য ধন্যবাদ। ❤️";
                $msg_receiver = "আপনি {$sender_name} এর কাছ থেকে ৳{$amount} এর একটি গিফট পেয়েছেন! ❤️";

                sendFCM_v1($user_fcm_keys[$sender_uid] ?? '', "🎁 ব্যালেন্স গিফট সফল", $msg_sender);
                sendFCM_v1($user_fcm_keys[$receiver_uid] ?? '', "🎁 নতুন গিফট প্রাপ্ত", $msg_receiver);

                $msg = "Request approved successfully. Balance sent to Receiver.";

            } elseif ($type === 'failed') {
                if ($current_status === 'approved') {
                    throw new Exception("Cannot fail an approved request directly.");
                }
                if ($current_status === 'failed') {
                    throw new Exception("This request is already failed.");
                }

                $stmt = $conn->prepare("SELECT uid FROM users WHERE uid = ? FOR UPDATE");
                $stmt->bind_param("s", $sender_uid);
                $stmt->execute();
                $senderExists = $stmt->get_result()->fetch_assoc();
                $stmt->close();

                if (!$senderExists) {
                    throw new Exception("Sender user does not exist.");
                }

                $stmt = $conn->prepare("UPDATE gift_requests SET status = 'failed' WHERE id = ?");
                $stmt->bind_param("i", $id);
                if (!$stmt->execute()) {
                    throw new Exception("Failed to update request status in database.");
                }
                $stmt->close();

                $stmt = $conn->prepare("UPDATE users SET balance = balance + ? WHERE uid = ?");
                $stmt->bind_param("ds", $total, $sender_uid);
                if (!$stmt->execute()) {
                    throw new Exception("Failed to refund sender.");
                }
                $stmt->close();

                $stmt_fcm = $conn->prepare("SELECT uid, fcm_key, username FROM users WHERE uid IN (?, ?)");
                $stmt_fcm->bind_param("ss", $sender_uid, $receiver_uid);
                $stmt_fcm->execute();
                $res_fcm = $stmt_fcm->get_result();
                $user_fcm_keys = [];
                $user_names = [];
                while($row = $res_fcm->fetch_assoc()){
                    $user_fcm_keys[$row['uid']] = $row['fcm_key'];
                    $user_names[$row['uid']] = $row['username'];
                }
                $stmt_fcm->close();

                $sender_name = $user_names[$sender_uid] ?? "UID: " . $sender_uid;

                $msg_sender = "দুঃখিত! আপনার ৳{$amount} ব্যালেন্স গিফট অনুরোধটি সম্পন্ন করা যায়নি। কোনো ব্যালেন্স কাটা হয়নি। প্রয়োজনে আবার চেষ্টা করুন বা সাপোর্টে যোগাযোগ করুন।";
                $msg_receiver = "{$sender_name} এর কাছ থেকে আপনার জন্য আসা গিফট রিকোয়েস্টটি বাতিল করা হয়েছে।";

                sendFCM_v1($user_fcm_keys[$sender_uid] ?? '', "❌ ব্যালেন্স গিফট ব্যর্থ", $msg_sender);
                sendFCM_v1($user_fcm_keys[$receiver_uid] ?? '', "ℹ️ গিফট বাতিল", $msg_receiver);

                $msg = "Request failed and amount refunded to sender.";

            } elseif ($type === 'delete') {
                $stmt = $conn->prepare("DELETE FROM gift_requests WHERE id = ?");
                $stmt->bind_param("i", $id);
                if (!$stmt->execute()) {
                    throw new Exception("Failed to delete request.");
                }
                $stmt->close();

                $msg = "Request deleted successfully.";
            } else {
                throw new Exception("Invalid action type.");
            }

            $conn->commit();
            echo json_encode(["status" => "success", "message" => $msg]);

        } catch (Exception $e) {
            $conn->rollback();
            echo json_encode(["status" => "error", "message" => $e->getMessage()]);
        }
        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 gift requests.</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>Gift Requests Management</title>
    <style>
        :root {
            --slate-50: #f8fafc;
            --slate-100: #f1f5f9;
            --slate-200: #e2e8f0;
            --slate-300: #cbd5e1;
            --slate-500: #64748b;
            --slate-700: #334155;
            --slate-900: #0f172a;
            --primary: #4f46e5;
            --primary-light: #eeebff;
            --emerald-500: #10b981;
            --emerald-50: #ecfdf5;
            --rose-500: #f43f5e;
            --rose-50: #fff1f2;
            --amber-500: #f59e0b;
            --amber-50: #fffbeb;
            --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; color: var(--slate-900); }
        
        .content-body { padding: 40px; overflow-y: auto; flex-grow: 1; }
        
        .table-container { background: var(--white); border: 1px solid var(--slate-200); border-radius: var(--radius-lg); box-shadow: var(--shadow-sm); overflow-x: auto; display: flex; flex-direction: column;}
        table { width: 100%; border-collapse: collapse; text-align: left; }
        th, td { padding: 16px 20px; border-bottom: 1px solid var(--slate-100); font-size: 14px; }
        th { background: var(--slate-50); font-weight: 600; color: var(--slate-700); text-transform: uppercase; font-size: 12px; letter-spacing: 0.5px; }
        tbody tr:hover { background: var(--slate-50); }
        
        .badge { display: inline-flex; align-items: center; padding: 4px 10px; border-radius: 9999px; font-size: 12px; font-weight: 600; text-transform: capitalize; }
        .badge.pending { background: var(--amber-50); color: var(--amber-500); }
        .badge.approved { background: var(--emerald-50); color: var(--emerald-500); }
        .badge.failed { background: var(--rose-50); color: var(--rose-500); }

        .user-block { display: flex; flex-direction: column; gap: 4px; }
        .user-name { font-weight: 700; color: var(--slate-900); font-size: 14px; display: flex; align-items: center;}
        .user-uid { font-family: monospace; font-size: 11px; color: var(--slate-500); }
        
        .history-link {
            color: var(--primary);
            display: inline-flex;
            align-items: center;
            justify-content: center;
            background: var(--primary-light);
            padding: 4px;
            border-radius: 6px;
            transition: 0.2s;
            margin-left: 8px;
            text-decoration: none;
        }
        .history-link:hover {
            background: var(--primary);
            color: var(--white);
            transform: scale(1.05);
        }
        .history-link svg { width: 14px; height: 14px; }

        .action-btns { display: flex; gap: 8px; }
        .btn-action { border: none; background: none; cursor: pointer; border-radius: 8px; padding: 8px; transition: 0.2s; display: inline-flex; align-items: center; justify-content: center; color: var(--white); }
        .btn-action svg { width: 16px; height: 16px; }
        .btn-action:disabled { opacity: 0.5; cursor: not-allowed; }
        .btn-action.approve-btn { background: var(--emerald-500); }
        .btn-action.approve-btn:hover:not(:disabled) { background: #059669; transform: translateY(-2px); }
        .btn-action.failed-btn { background: var(--rose-500); }
        .btn-action.failed-btn:hover:not(:disabled) { background: #e11d48; transform: translateY(-2px); }
        .btn-action.delete-btn { background: var(--slate-700); }
        .btn-action.delete-btn:hover:not(:disabled) { background: var(--slate-900); transform: translateY(-2px); }

        .pagination-container { padding: 20px; display: flex; justify-content: space-between; align-items: center; border-top: 1px solid var(--slate-100); background: var(--white); border-bottom-left-radius: var(--radius-lg); border-bottom-right-radius: var(--radius-lg); }
        .pagination-info { font-size: 13px; color: var(--slate-500); }
        .pagination-controls { display: flex; gap: 6px; }
        .page-btn { padding: 6px 12px; border: 1px solid var(--slate-200); background: var(--white); color: var(--slate-700); border-radius: 6px; cursor: pointer; font-size: 13px; font-weight: 600; transition: 0.2s; }
        .page-btn:hover:not(:disabled) { background: var(--slate-50); border-color: var(--slate-300); }
        .page-btn.active { background: var(--primary); color: var(--white); border-color: var(--primary); }
        .page-btn:disabled { opacity: 0.5; cursor: not-allowed; }

        .loader { text-align: center; padding: 40px; color: var(--slate-700); font-weight: 600; font-size: 16px; }

        .toast-container { position: fixed; bottom: 24px; right: 24px; z-index: 1000; display: flex; flex-direction: column; gap: 10px; }
        .toast { padding: 14px 20px; border-radius: 10px; color: #fff; font-size: 14px; font-weight: 600; box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1); animation: slideIn 0.3s ease forwards; display: flex; align-items: center; gap: 10px; }
        .toast.success { background: var(--emerald-500); }
        .toast.error { background: var(--rose-500); }
        @keyframes slideIn { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } }

        @media (max-width: 768px) { body { flex-direction: column; } .header { padding: 20px; } .content-body { padding: 20px; } .pagination-container { flex-direction: column; gap: 12px; } }
    </style>
</head>
<body>

<div class="main-content">
    <div class="header">
        <div class="header-title">
            <h1>Gift Requests</h1>
        </div>
    </div>
    
    <div class="content-body">
        <div class="table-container" id="dataTableWrap">
            <div class="loader" id="loader">Loading gift requests...</div>
            <table id="dataTable" style="display: none;">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Sender</th>
                        <th>Receiver</th>
                        <th>Details</th>
                        <th>Type & Status</th>
                        <th>Date</th>
                        <th style="text-align: right;">Actions</th>
                    </tr>
                </thead>
                <tbody id="dataBody"></tbody>
            </table>
            
            <div class="pagination-container" id="paginationControls" style="display: none;">
                <div class="pagination-info" id="pageInfo">Showing Page 1</div>
                <div class="pagination-controls" id="pageBtns"></div>
            </div>
        </div>
    </div>
</div>

<div class="toast-container" id="toastContainer"></div>

<script>
    const canEdit = <?= $canEdit ? 'true' : 'false' ?>;
    const canDelete = <?= $canDelete ? 'true' : 'false' ?>;
    let currentPage = 1;

    function showToast(message, type = 'success') {
        const container = document.getElementById('toastContainer');
        const toast = document.createElement('div');
        toast.className = `toast ${type}`;
        
        let icon = type === 'success' 
            ? `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:20px;height:20px;"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75 11.25 15 15 9.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" /></svg>` 
            : `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:20px;height:20px;"><path stroke-linecap="round" stroke-linejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3Z" /></svg>`;
        
        toast.innerHTML = `${icon} <span>${message}</span>`;
        container.appendChild(toast);
        
        setTimeout(() => {
            toast.style.opacity = '0';
            toast.style.transform = 'translateX(100%)';
            toast.style.transition = 'all 0.3s ease';
            setTimeout(() => toast.remove(), 300);
        }, 3000);
    }

    function loadData(page = 1) {
        currentPage = page;
        const loader = document.getElementById('loader');
        const table = document.getElementById('dataTable');
        const pagination = document.getElementById('paginationControls');

        fetch(`?api=fetch&page=${page}&t=${Date.now()}`)
            .then(res => res.json())
            .then(res => {
                loader.style.display = 'none';
                if (res.status === 'success') {
                    renderTable(res.data);
                    renderPagination(res.totalPages, res.currentPage);
                    table.style.display = 'table';
                    pagination.style.display = res.totalPages > 1 ? 'flex' : 'none';
                } else {
                    loader.style.display = 'block';
                    loader.innerHTML = `<span style="color:var(--rose-500)">${res.message}</span>`;
                }
            })
            .catch(err => {
                loader.style.display = 'block';
                loader.innerHTML = `<span style="color:var(--rose-500)">Failed to load data.</span>`;
            });
    }

    function renderPagination(totalPages, current) {
        const info = document.getElementById('pageInfo');
        const btns = document.getElementById('pageBtns');
        
        info.textContent = `Page ${current} of ${totalPages}`;
        btns.innerHTML = '';

        let prevBtn = document.createElement('button');
        prevBtn.className = 'page-btn';
        prevBtn.textContent = 'Prev';
        prevBtn.disabled = (current === 1);
        prevBtn.onclick = () => loadData(current - 1);
        btns.appendChild(prevBtn);

        let nextBtn = document.createElement('button');
        nextBtn.className = 'page-btn';
        nextBtn.textContent = 'Next';
        nextBtn.disabled = (current === totalPages || totalPages === 0);
        nextBtn.onclick = () => loadData(current + 1);
        btns.appendChild(nextBtn);
    }

    function renderTable(data) {
        const tbody = document.getElementById('dataBody');
        tbody.innerHTML = '';

        if (data.length === 0) {
            tbody.innerHTML = `<tr><td colspan="7" style="text-align:center; padding: 40px; color:var(--slate-500);">No requests found on this page.</td></tr>`;
            return;
        }

        data.forEach(item => {
            let actionsHtml = '';
            let currentStatus = (item.status || 'pending').toLowerCase().trim();
            if (currentStatus === 'success') currentStatus = 'approved';
            
            let senderName = item.sender_username || 'Unknown';
            let receiverName = item.receiver_username || 'Unknown';
            
            let senderHistoryLink = item.sender_username ? 
                `<a href="Usersmoneyhistory.php?username=${encodeURIComponent(item.sender_username)}" class="history-link" title="Money History" target="_blank">
                    <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="M12 6v6h4.5m4.5 0a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" /></svg>
                </a>` : '';
                
            let receiverHistoryLink = item.receiver_username ? 
                `<a href="Usersmoneyhistory.php?username=${encodeURIComponent(item.receiver_username)}" class="history-link" title="Money History" target="_blank">
                    <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="M12 6v6h4.5m4.5 0a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" /></svg>
                </a>` : '';


            if (canEdit || canDelete) {
                actionsHtml += `<div class="action-btns" style="justify-content: flex-end;">`;
                
                if (canEdit) {
                    if (currentStatus === 'pending') {
                        actionsHtml += `
                            <button class="btn-action approve-btn" onclick="processAction(${item.id}, 'approved', this)" title="Approve">
                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="m4.5 12.75 6 6 9-13.5" /></svg>
                            </button>
                            <button class="btn-action failed-btn" onclick="processAction(${item.id}, 'failed', this)" title="Reject">
                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12" /></svg>
                            </button>`;
                    } else if (currentStatus === 'failed') {
                        actionsHtml += `
                            <button class="btn-action approve-btn" onclick="processAction(${item.id}, 'approved', this)" title="Approve">
                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="m4.5 12.75 6 6 9-13.5" /></svg>
                            </button>`;
                    }
                }
                
                if (canDelete) {
                    actionsHtml += `
                        <button class="btn-action delete-btn" onclick="processAction(${item.id}, 'delete', this)" title="Delete">
                            <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>`;
                }
                actionsHtml += `</div>`;
            }

            let tr = document.createElement('tr');
            tr.innerHTML = `
                <td><strong>#${item.id}</strong></td>
                <td>
                    <div class="user-block">
                        <div class="user-name">${senderName} ${senderHistoryLink}</div>
                        <span class="user-uid">UID: ${item.sender_uid || '-'}</span>
                    </div>
                </td>
                <td>
                    <div class="user-block">
                        <div class="user-name">${receiverName} ${receiverHistoryLink}</div>
                        <span class="user-uid">UID: ${item.receiver_uid || '-'}</span>
                    </div>
                </td>
                <td>
                    <div style="font-size:13px; color:var(--slate-700)">Amt: <strong>${item.amount}</strong></div>
                    <div style="font-size:12px; color:var(--slate-500)">Fee: ${item.fee}</div>
                    <div style="font-size:13px; font-weight:700; margin-top:2px; color:var(--slate-900)">Total: ${item.total}</div>
                </td>
                <td>
                    <div style="margin-bottom:6px; font-size:13px; color:var(--slate-700);">${item.type || '-'}</div>
                    <span class="badge ${currentStatus}">${currentStatus}</span>
                </td>
                <td style="font-size:13px; color:var(--slate-500);">${item.created_at || '-'}</td>
                <td style="text-align:right;">${actionsHtml}</td>
            `;
            tbody.appendChild(tr);
        });
    }

    function processAction(id, type, btn) {
        let msg = type === 'delete' 
            ? 'Are you sure you want to permanently delete this request?' 
            : `Are you sure you want to mark this request as ${type}?`;
            
        if (!confirm(msg)) return;
        if (btn) btn.disabled = true;

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

        fetch('?api=process', {
            method: 'POST',
            body: formData
        })
        .then(res => res.json())
        .then(res => {
            if (res.status === 'success') {
                showToast(res.message, 'success');
                loadData(currentPage);
            } else {
                showToast(res.message, 'error');
                if (btn) btn.disabled = false;
            }
        })
        .catch(err => {
            showToast('Connection error.', 'error');
            if (btn) btn.disabled = false;
        });
    }

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