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

$admin_authenticated = false;

if (isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true && isset($_SESSION['admin_user'])) {
    $mod_username = $conn->real_escape_string($_SESSION['admin_user']);
    $query = $conn->query("SELECT extra_json FROM modarator_permissions WHERE username = '$mod_username' LIMIT 1");
    
    if ($query && $query->num_rows > 0) {
        $user_data = $query->fetch_assoc();
        if (!empty($user_data['extra_json'])) {
            $extra_data = json_decode($user_data['extra_json'], true);
            if (isset($extra_data['withdrawals']) && $extra_data['withdrawals'] === 'Yes') {
                $admin_authenticated = true;
            }
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    
    if (!$admin_authenticated) {
        http_response_code(403);
        echo json_encode(["status" => "error", "message" => "Access Denied. You do not have permission."]);
        exit;
    }

    $type = $_POST['type'] ?? '';

    if ($type === 'total_unpaid') {
        $result = $conn->query("SELECT SUM(amount) as total FROM withdraw WHERE status='Pending'");
        $total = 0;
        if ($result && $row = $result->fetch_assoc()) {
            $total = (int)$row['total'];
        }
        echo json_encode(["status" => "success", "total" => $total]);
        exit;
    }

    if ($type === 'get_all') {
        $status = $conn->real_escape_string($_POST['status'] ?? '');
        $page = max(1, (int)($_POST['page'] ?? 1));
        $per_page = max(1, (int)($_POST['per_page'] ?? 20));
        $offset = ($page - 1) * $per_page;
        $where = "";
        
        if ($status && in_array($status, ['Pending', 'Success', 'Failed'])) {
            $where = " WHERE status = '$status'";
        }
        
        $countQuery = "SELECT COUNT(*) as total FROM withdraw" . $where;
        $countResult = $conn->query($countQuery);
        $total = $countResult->fetch_assoc()['total'] ?? 0;
        $last_page = max(1, ceil($total / $per_page));
        
        $sql = "SELECT * FROM withdraw" . $where . " ORDER BY id DESC LIMIT $offset, $per_page";
        $result = $conn->query($sql);
        $data = [];
        
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $data[] = $row;
            }
        }
        
        echo json_encode([
            "status" => "success",
            "data" => $data,
            "total" => (int)$total,
            "current_page" => $page,
            "per_page" => $per_page,
            "last_page" => $last_page
        ]);
        exit;
    }

    if ($type === 'success') {
        $id = (int)($_POST['id'] ?? 0);
        
        if (!$id) {
            echo json_encode(["status" => "error", "message" => "Missing ID"]);
            exit;
        }
        
        $check = $conn->query("SELECT status FROM withdraw WHERE id = $id");
        if ($check && $row = $check->fetch_assoc()) {
            if ($row['status'] !== 'Pending') {
                echo json_encode(["status" => "error", "message" => "Request already processed"]);
                exit;
            }
        } else {
            echo json_encode(["status" => "error", "message" => "Request not found"]);
            exit;
        }
        
        $update = $conn->query("UPDATE withdraw SET status = 'Success' WHERE id = $id");
        if ($update) {
            echo json_encode(["status" => "success", "message" => "Withdraw approved successfully"]);
        } else {
            echo json_encode(["status" => "error", "message" => "Failed to approve"]);
        }
        exit;
    }

    if ($type === 'failed') {
        $id = (int)($_POST['id'] ?? 0);
        
        if (!$id) {
            echo json_encode(["status" => "error", "message" => "Missing ID"]);
            exit;
        }
        
        $get = $conn->query("SELECT amount, email FROM withdraw WHERE id = $id AND status = 'Pending'");
        if (!$get || $get->num_rows === 0) {
            echo json_encode(["status" => "error", "message" => "Request not found or already processed"]);
            exit;
        }
        
        $row = $get->fetch_assoc();
        $amount = (int)$row['amount'];
        $withdraw_email = $conn->real_escape_string($row['email']);
        
        $refund = $conn->query("UPDATE users SET winning = winning + $amount WHERE email = '$withdraw_email'");
        if (!$refund) {
            echo json_encode(["status" => "error", "message" => "Failed to refund user"]);
            exit;
        }
        
        $update = $conn->query("UPDATE withdraw SET status = 'Failed' WHERE id = $id");
        if ($update) {
            echo json_encode(["status" => "success", "message" => "Withdraw rejected and refunded"]);
        } else {
            echo json_encode(["status" => "error", "message" => "Failed to update status"]);
        }
        exit;
    }

    echo json_encode(["status" => "error", "message" => "Invalid API type"]);
    exit;
}

$user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
if (strpos($user_agent, 'iPhone') !== false) {
    $default_per_page = 200;
} elseif (strpos($user_agent, 'Android') !== false) {
    $default_per_page = 100;
} else {
    $default_per_page = 500; 
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bunasex Withdraw Manager</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        * { font-family: 'Inter', sans-serif; }
        body { background: #f4f6fa; min-height: 100vh; padding: 20px 0; }
        .container { max-width: 1400px; }
        .main-card { border-radius: 28px; box-shadow: 0 20px 40px rgba(0,0,0,0.06); border: none; overflow: hidden; background: #ffffff; }
        .card-header-custom { background: linear-gradient(135deg, #7c3aed, #4f46e5); padding: 18px 25px; display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; border-bottom: none; }
        .card-header-custom h4 { color: #fff; font-weight: 700; margin: 0; display: flex; align-items: center; gap: 12px; font-size: 1.3rem; }
        .btn-soft-light { background: rgba(255,255,255,0.15); border: 1px solid rgba(255,255,255,0.25); color: #fff; border-radius: 50px; padding: 6px 18px; font-weight: 500; transition: 0.3s; text-decoration: none; }
        .btn-soft-light:hover { background: #fff; color: #4f46e5; }
        .total-unpaid { background: linear-gradient(135deg, #f59e0b, #d97706); color: #fff; border-radius: 20px; padding: 6px 20px; font-weight: 700; display: inline-flex; align-items: center; gap: 8px; font-size: 0.95rem; white-space: nowrap; }
        .nav-tabs-custom .nav-link { border: none; border-radius: 50px; padding: 8px 20px; font-weight: 600; color: #6b7280; transition: 0.3s; }
        .nav-tabs-custom .nav-link.active { background: #4f46e5; color: #fff; }
        .table-custom { margin-bottom: 0; font-size: 0.9rem; min-width: 700px; }
        .table-custom thead th { background: #f8faff; color: #1f2937; font-weight: 600; font-size: 0.8rem; text-transform: uppercase; letter-spacing: 0.5px; border-bottom: 2px solid #e5e7eb; padding: 12px 10px; white-space: nowrap; }
        .table-custom tbody td { padding: 12px 10px; vertical-align: middle; border-bottom: 1px solid #f1f3f5; color: #1f2937; word-break: break-word; }
        .table-custom tbody tr:hover { background: #f8faff; }
        .action-btn { width: 32px; height: 32px; border-radius: 8px; display: inline-flex; align-items: center; justify-content: center; border: none; font-size: 0.85rem; transition: 0.2s; margin: 0 2px; }
        .btn-success-custom { background: #d1fae5; color: #065f46; }
        .btn-success-custom:hover { background: #a7f3d0; }
        .btn-danger-custom { background: #fee2e2; color: #b91c1c; }
        .btn-danger-custom:hover { background: #fca5a5; }
        .pagination-custom .page-link { border-radius: 50px !important; margin: 0 4px; color: #4f46e5; border: 1px solid #e5e7eb; }
        .pagination-custom .page-item.active .page-link { background: #4f46e5; border-color: #4f46e5; color: #fff; }
        .error-container { max-width: 400px; margin: 100px auto; text-align: center; background: #fff; padding: 40px; border-radius: 28px; box-shadow: 0 20px 40px rgba(0,0,0,0.08); }
        .error-container i { font-size: 3rem; color: #ef4444; margin-bottom: 15px; }
        .toast-container-custom { position: fixed; top: 20px; right: 20px; z-index: 9999; }
        .toast-custom { border-radius: 16px; box-shadow: 0 12px 30px rgba(0,0,0,0.12); border: none; }
        .spinner-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.25); z-index: 9998; justify-content: center; align-items: center; }
        .spinner-overlay.show { display: flex; }
        .spinner-overlay .spinner-border { width: 3rem; height: 3rem; color: #4f46e5; }
        @media (max-width: 768px) { .card-header-custom { flex-direction: column; align-items: stretch; gap: 12px; } .card-header-custom h4 { font-size: 1.1rem; } .total-unpaid { font-size: 0.8rem; padding: 4px 14px; } .table-custom { font-size: 0.75rem; min-width: 650px; } .action-btn { width: 28px; height: 28px; font-size: 0.7rem; } }
    </style>
</head>
<body>

<div class="spinner-overlay" id="loadingSpinner">
    <div class="spinner-border" role="status"><span class="visually-hidden">Loading...</span></div>
</div>

<div class="toast-container-custom">
    <div id="liveToast" class="toast toast-custom" role="alert">
        <div class="toast-header" id="toastHeader">
            <strong id="toastTitle">Notification</strong>
            <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
        </div>
        <div class="toast-body" id="toastMessage">Message</div>
    </div>
</div>

<div class="container">
    <?php if (!$admin_authenticated): ?>
        <div class="error-container">
            <i class="fas fa-exclamation-triangle"></i>
            <h4>Access Denied</h4>
            <p class="text-muted mt-2">You do not have permission to view this page. Please login with an authorized account.</p>
        </div>
    <?php else: ?>
        <div class="main-card">
            <div class="card-header-custom">
                <h4><i class="fas fa-arrow-up"></i> Bunasex Withdraw Manager</h4>
                <div class="d-flex gap-2 align-items-center flex-wrap">
                    <span class="total-unpaid" id="totalUnpaid">
                        <i class="fas fa-coins"></i> Pending: <span id="unpaidAmount">0</span> ৳
                    </span>
                    <a href="/" class="btn-soft-light"><i class="fas fa-home"></i> Home</a>
                </div>
            </div>

            <div class="card-body p-3">
                <ul class="nav nav-tabs-custom nav-pills mb-3" id="myTab" role="tablist">
                    <li class="nav-item"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#pendingTab" type="button">Pending</button></li>
                    <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#successTab" type="button">Success</button></li>
                    <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#failedTab" type="button">Failed</button></li>
                </ul>

                <div class="tab-content">
                    <div class="tab-pane fade show active" id="pendingTab">
                        <div class="table-responsive">
                            <table class="table table-custom">
                                <thead><tr>
                                    <th>ID</th> <th>Email</th> <th>Method</th> <th>Amount</th> <th>TrxID</th> <th>Date</th> <th>Action</th>
                                </tr></thead>
                                <tbody id="pendingBody"><tr><td colspan="7" class="text-center">Loading...</td></tr></tbody>
                            </table>
                        </div>
                        <div id="pendingPagination" class="d-flex justify-content-center mt-3"></div>
                    </div>

                    <div class="tab-pane fade" id="successTab">
                        <div class="table-responsive">
                            <table class="table table-custom">
                                <thead><tr>
                                    <th>ID</th> <th>Email</th> <th>Method</th> <th>Amount</th> <th>TrxID</th> <th>Date</th>
                                </tr></thead>
                                <tbody id="successBody"><tr><td colspan="6" class="text-center">Loading...</td></tr></tbody>
                            </table>
                        </div>
                        <div id="successPagination" class="d-flex justify-content-center mt-3"></div>
                    </div>

                    <div class="tab-pane fade" id="failedTab">
                        <div class="table-responsive">
                            <table class="table table-custom">
                                <thead><tr>
                                    <th>ID</th> <th>Email</th> <th>Method</th> <th>Amount</th> <th>TrxID</th> <th>Date</th>
                                </tr></thead>
                                <tbody id="failedBody"><tr><td colspan="6" class="text-center">Loading...</td></tr></tbody>
                            </table>
                        </div>
                        <div id="failedPagination" class="d-flex justify-content-center mt-3"></div>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

<?php if ($admin_authenticated): ?>
<script>
$(document).ready(function() {

    const DEFAULT_PER_PAGE = <?php echo json_encode($default_per_page); ?>;
    const API_URL = window.location.href;
    let currentPage = { Pending: 1, Success: 1, Failed: 1 };
    let lastPage = { Pending: 1, Success: 1, Failed: 1 };

    function showToast(message, type = 'success') {
        const header = $('#toastHeader'), title = $('#toastTitle'), body = $('#toastMessage');
        if (type === 'success') { header.removeClass('bg-danger bg-warning').addClass('bg-success text-white'); title.text('✅ Success'); }
        else if (type === 'warning') { header.removeClass('bg-success bg-danger').addClass('bg-warning text-dark'); title.text('⚠️ Warning'); }
        else { header.removeClass('bg-success bg-warning').addClass('bg-danger text-white'); title.text('❌ Error'); }
        body.text(message);
        new bootstrap.Toast($('#liveToast'), { delay: 3500 }).show();
    }

    function showLoading(show) {
        if (show) $('#loadingSpinner').addClass('show');
        else $('#loadingSpinner').removeClass('show');
    }

    function fetchData(status, page = 1) {
        showLoading(true);
        $.post(API_URL, {
            type: 'get_all',
            status: status,
            page: page,
            per_page: DEFAULT_PER_PAGE
        }, function(response) {
            showLoading(false);
            const targetBody = status.toLowerCase() + 'Body';
            const paginationId = status.toLowerCase() + 'Pagination';

            if (response.status === 'success') {
                const data = response.data;
                const current = response.current_page;
                const last = response.last_page;
                currentPage[status] = current;
                lastPage[status] = last;

                let html = '';
                if (data.length === 0) {
                    const colSpan = (status === 'Pending') ? 7 : 6;
                    html = `<tr><td colspan="${colSpan}" class="text-center text-muted">No records found</td></tr>`;
                } else {
                    data.forEach(row => {
                        const actions = (status === 'Pending') ? `
                            <button class="action-btn btn-success-custom approveBtn" data-id="${row.id}" title="Approve"><i class="fas fa-check"></i></button>
                            <button class="action-btn btn-danger-custom rejectBtn" data-id="${row.id}" title="Reject"><i class="fas fa-times"></i></button>
                        ` : '';
                        html += `<tr>
                            <td>#${row.id}</td>
                            <td>${row.email}</td>
                            <td>${row.method}</td>
                            <td>${parseInt(row.amount).toLocaleString()} ৳</td>
                            <td>${row.trxid}</td>
                            <td><small>${row.date || ''} ${row.time || ''}</small></td>
                            ${actions ? `<td>${actions}</td>` : ''}
                        </tr>`;
                    });
                }
                $('#' + targetBody).html(html);
                renderPagination(paginationId, status, current, last);
            } else {
                showToast(response.message || 'Failed to load data', 'error');
            }
        }).fail(() => { showLoading(false); showToast('Server error fetching data', 'error'); });
    }

    function renderPagination(containerId, status, current, last) {
        if(last <= 1) { $('#' + containerId).html(''); return; }
        
        let html = `<ul class="pagination pagination-custom">`;
        html += `<li class="page-item ${current <= 1 ? 'disabled' : ''}"><a class="page-link" href="#" data-status="${status}" data-page="${current-1}">Prev</a></li>`;
        let start = Math.max(1, current - 2);
        let end = Math.min(last, current + 2);
        if (start > 1) html += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
        for (let i = start; i <= end; i++) {
            html += `<li class="page-item ${i === current ? 'active' : ''}"><a class="page-link" href="#" data-status="${status}" data-page="${i}">${i}</a></li>`;
        }
        if (end < last) html += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
        html += `<li class="page-item ${current >= last ? 'disabled' : ''}"><a class="page-link" href="#" data-status="${status}" data-page="${current+1}">Next</a></li>`;
        html += `</ul>`;
        $('#' + containerId).html(html);
    }

    $(document).on('click', '.pagination-custom .page-link', function(e) {
        e.preventDefault();
        const status = $(this).data('status');
        const page = parseInt($(this).data('page'));
        if (page && page >= 1 && page <= lastPage[status]) {
            fetchData(status, page);
        }
    });

    $(document).on('click', '.approveBtn', function() {
        const id = $(this).data('id');
        if (!confirm('Approve this withdraw request?')) return;
        showLoading(true);
        $.post(API_URL, { type: 'success', id: id }, function(response) {
            showLoading(false);
            if (response.status === 'success') {
                showToast(response.message, 'success');
                loadAllData();
            } else showToast(response.message, 'error');
        }).fail(() => { showLoading(false); showToast('Server error', 'error'); });
    });

    $(document).on('click', '.rejectBtn', function() {
        const id = $(this).data('id');
        if (!confirm('Reject this withdraw request? This will refund the user.')) return;
        showLoading(true);
        $.post(API_URL, { type: 'failed', id: id }, function(response) {
            showLoading(false);
            if (response.status === 'success') {
                showToast(response.message, 'success');
                loadAllData();
            } else showToast(response.message, 'error');
        }).fail(() => { showLoading(false); showToast('Server error', 'error'); });
    });

    function loadTotalUnpaid() {
        $.post(API_URL, { type: 'total_unpaid' }, function(response) {
            if (response.status === 'success') $('#unpaidAmount').text(response.total.toLocaleString());
        });
    }

    function loadAllData() {
        fetchData('Pending', currentPage.Pending);
        fetchData('Success', currentPage.Success);
        fetchData('Failed', currentPage.Failed);
        loadTotalUnpaid();
    }

    $('button[data-bs-toggle="tab"]').on('shown.bs.tab', function(e) {
        const target = $(e.target).attr('data-bs-target');
        if (target === '#pendingTab') fetchData('Pending', currentPage.Pending);
        else if (target === '#successTab') fetchData('Success', currentPage.Success);
        else if (target === '#failedTab') fetchData('Failed', currentPage.Failed);
    });

    loadAllData();
});
</script>
<?php endif; ?>
</body>
</html>
