<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Panel</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link rel="stylesheet" href="css/main/main.css?ver=<?php echo time(); ?>">
    <script src="js/main/main.js?ver=<?php echo time(); ?>" defer></script>

    <!-- Highlight.js -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/json.min.js"></script>

    <style>
        #content { padding: 10px; }

        .table-container {
            height: calc(100vh - 220px);
            overflow-y: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            background: #fff;
            border-radius: 8px;
            font-size: 14px;
        }

        th, td {
            padding: 8px 10px;
            border-bottom: 1px solid #ddd;
            text-align: left;
            vertical-align: top;
        }

        thead th {
            position: sticky;
            top: 0;
            background: #3e3f42;
            color: #fff;
            z-index: 10;
        }

        tr:hover { background-color: #f1f5f9; }

        button.view-btn {
            background: #1c4d4c;
            color: #fff;
            border: none;
            border-radius: 4px;
            padding: 5px 10px;
            cursor: pointer;
            font-size: 13px;
        }

        button.view-btn:hover { background: #163b3b; }

        textarea.raw-response {
            width: 200px;
            height: 100px;
            resize: none;
            background: #f9fafb;
            border: 1px solid #ccc;
            border-radius: 4px;
            font-size: 12px;
            padding: 6px;
            color: #333;
            overflow: auto;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0; left: 0; right: 0; bottom: 0;
            background: rgba(0,0,0,0.6);
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }

        .modal-content {
            background: #1e1e1e;
            border-radius: 8px;
            padding: 20px;
            width: 80%;
            max-width: 700px;
            max-height: 90vh;
            position: relative;
            box-shadow: 0 4px 20px rgba(0,0,0,0.3);
        }

        .modal-close {
            position: absolute;
            top: 10px;
            right: 15px;
            cursor: pointer;
            font-size: 18px;
            color: #ccc;
        }

        pre {
            padding: 10px;
            border-radius: 6px;
            white-space: pre-wrap;
            word-wrap: break-word;
            font-size: 13px;
            background: #1e1e1e;
            color: #c9d1d9;
        }

        #modalBody {
            overflow: auto;
            max-height: 75vh;
        }

        .pagination {
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 10px;
            flex-wrap: wrap;
        }

        .pagination button {
            padding: 5px 10px;
            border: 1px solid #ccc;
            background: #fff;
            cursor: pointer;
            border-radius: 4px;
        }

        .pagination button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .pagination input[type="number"] {
            width: 50px;
            padding: 5px;
            border-radius: 4px;
            border: 1px solid #ccc;
            text-align: center;
        }

        .pagination select, #search-input {
            padding: 5px;
            border-radius: 4px;
            border: 1px solid #ccc;
        }

        #search-container {
            margin-bottom: 10px;
        }
    </style>
</head>
<body>

<div class="left-panel left-panel-show" id="left-panel"></div>

<div class="main-content main-content-normal" id="main-content">
    <div id="content">
        <!-- Pagination Controls -->
        <div class="pagination" id="pagination">
            <button id="prevBtn">Prev</button>
            <input type="number" id="pageInput" min="1" value="1">
            <button id="goBtn">Go</button>
            <span id="totalPages">/ 1</span>
            <span id="totalRows">(Total: 0 rows)</span>
            <button id="nextBtn">Next</button>
            <select id="rowsPerPage">
                <option value="5">5 rows</option>
                <option value="10" selected>10 rows</option>
                <option value="20">20 rows</option>
                <option value="50">50 rows</option>
                <option value="100">100 rows</option>
                <option value="500">500 rows</option>
                <option value="1000">1,000 rows</option>
                <option value="5000">5,000 rows</option>
                <option value="10000">10,000 rows</option>
                <option value="50000">50,000 rows</option>
                <option value="100000">100,000 rows</option>
            </select>
        </div>

        <!-- Table -->
        <div class="table-container">
            <table id="webhookTable">
                <thead>
                    <tr>
                        <th>Order ID</th>
                        <th>Webhook Category</th>
                        <th>Raw Response</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <tr><td colspan="4">Loading data...</td></tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Modal -->
<div class="modal" id="responseModal">
    <div class="modal-content">
        <span class="modal-close" id="modalClose">&times;</span>
        <h3 style="color: #fff;">Raw Response</h3>
        <pre><code id="modalBody" class="language-json"></code></pre>
    </div>
</div>

<script>
let webhookData = [];
let filteredData = [];
let currentPage = 1;
let rowsPerPage = parseInt(document.getElementById('rowsPerPage').value);

// Fetch webhook logs
async function fetchWebhookLogs() {
    const tableBody = document.querySelector('#webhookTable tbody');
    tableBody.innerHTML = '<tr><td colspan="4">Loading data...</td></tr>';

    try {
        const response = await fetch('../php/fetch_webhook_logs.php');
        webhookData = await response.json();
        filteredData = [...webhookData];

        if (!Array.isArray(webhookData) || webhookData.length === 0) {
            tableBody.innerHTML = '<tr><td colspan="4">No logs found</td></tr>';
            return;
        }

        renderTable();
        updatePaginationControls();
    } catch (error) {
        console.error('Error fetching logs:', error);
        tableBody.innerHTML = '<tr><td colspan="4">Error loading data</td></tr>';
    }
}

// Render table
function renderTable(data = filteredData) {
    const tableBody = document.querySelector('#webhookTable tbody');
    const start = (currentPage - 1) * rowsPerPage;
    const end = start + rowsPerPage;
    const pageData = data.slice(start, end);

    let rows = '';
    pageData.forEach(item => {
        const status = item.status || 'unknown';
        rows += `
            <tr>
                <td>${item.id}</td>
                <td>${status}</td>
                <td><textarea class="raw-response" readonly>${JSON.stringify(item, null, 2)}</textarea></td>
                <td><button class="view-btn" onclick='viewResponse(${JSON.stringify(item)})'>View</button></td>
            </tr>
        `;
    });

    tableBody.innerHTML = rows;
}

// Update pagination
function updatePaginationControls(data = filteredData) {
    const totalPages = Math.ceil(data.length / rowsPerPage);
    document.getElementById('pageInput').value = currentPage;
    document.getElementById('totalPages').textContent = `/ ${totalPages}`;
    document.getElementById('prevBtn').disabled = currentPage === 1;
    document.getElementById('nextBtn').disabled = currentPage === totalPages || totalPages === 0;
    document.getElementById('totalRows').textContent = `(Total: ${data.length} rows)`;
}

// Event listeners
document.getElementById('prevBtn').addEventListener('click', () => {
    if (currentPage > 1) currentPage--;
    renderTable();
    updatePaginationControls();
});

document.getElementById('nextBtn').addEventListener('click', () => {
    const totalPages = Math.ceil(filteredData.length / rowsPerPage);
    if (currentPage < totalPages) currentPage++;
    renderTable();
    updatePaginationControls();
});

document.getElementById('goBtn').addEventListener('click', () => {
    const totalPages = Math.ceil(filteredData.length / rowsPerPage);
    let page = parseInt(document.getElementById('pageInput').value);
    if (isNaN(page) || page < 1) page = 1;
    if (page > totalPages) page = totalPages;
    currentPage = page;
    renderTable();
    updatePaginationControls();
});

document.getElementById('rowsPerPage').addEventListener('change', (e) => {
    rowsPerPage = parseInt(e.target.value);
    currentPage = 1;
    renderTable();
    updatePaginationControls();
});

// Wait for dynamically created search input using MutationObserver
const observer = new MutationObserver((mutations, obs) => {
    const searchInput = document.getElementById('search-input');
    if (searchInput) {
        let debounceTimeout;

        searchInput.addEventListener('input', (e) => {
            clearTimeout(debounceTimeout);
            debounceTimeout = setTimeout(() => {
                const query = e.target.value.toLowerCase();
                filteredData = webhookData.filter(item =>
                    Object.values(item).some(val =>
                        String(val).toLowerCase().includes(query)
                    )
                );
                currentPage = 1;
                renderTable();
                updatePaginationControls();
            }, 500); // 500ms debounce
        });


        // Stop observing once input is found
        obs.disconnect();
    }
});

// Start observing body for added nodes
observer.observe(document.body, {
    childList: true,
    subtree: true
});



// View raw response in modal
function viewResponse(item) {
    const modal = document.getElementById('responseModal');
    const modalBody = document.getElementById('modalBody');
    modalBody.textContent = JSON.stringify(item, null, 2);
    hljs.highlightElement(modalBody);
    modal.style.display = 'flex';
}

// Modal close
document.getElementById('modalClose').addEventListener('click', () => {
    document.getElementById('responseModal').style.display = 'none';
});

window.onclick = (event) => {
    const modal = document.getElementById('responseModal');
    if (event.target === modal) modal.style.display = 'none';
};

// Initialize
document.addEventListener('DOMContentLoaded', fetchWebhookLogs);
</script>

</body>
</html>
