<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WhatsApp Message Log</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>

    <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; }

        /* Style for the brief Attempt Status column */
        .status-cell {
            font-weight: bold;
            font-size: 13px;
        }
        .status-cell.success { color: #10b981; }
        .status-cell.error { color: #ef4444; }
        .status-cell.warning { color: #f59e0b; }
        .status-cell.skipped { color: #6b7280; }

        .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: 90%; /* Increased size for logs */
            max-width: 900px;
            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">
        <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>

        <div class="table-container">
            <table id="messageLogTable">
                <thead>
                    <tr>
                        <th style="width: 120px;">Timestamp</th>
                        <th style="width: 80px;">Order ID</th>
                        <th style="width: 100px;">Recipient</th>
                        <th style="width: 100px;">Order Status</th>
                        <th>Attempt Status</th>
                        <th style="width: 80px;">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <tr><td colspan="6">Loading message log data...</td></tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal" id="responseModal">
    <div class="modal-content">
        <span class="modal-close" id="modalClose">&times;</span>
        <h3 style="color: #fff;">WhatsApp Message & API Response Log</h3>
        
        <div id="modalBody">
            <h4 style="color: #ccc; margin-top: 0;">Sent Message:</h4>
            <pre style="background: #282c34; color: #abb2bf;"><code id="sentMessageBody" class="language-text"></code></pre>

            <h4 style="color: #ccc;">API Request/Response Data:</h4>
            <pre><code id="apiResponseCode" class="language-json"></code></pre>
        </div>
    </div>
</div>

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

// --- LOGIC FUNCTIONS ---

// Fetch message logs
async function fetchMessageLogs() {
    const tableBody = document.querySelector('#messageLogTable tbody');
    tableBody.innerHTML = '<tr><td colspan="6">Loading message log data...</td></tr>';

    try {
        // Updated fetch URL
        const response = await fetch('../php/fetch_message_log.php');
        logData = await response.json();
        filteredData = [...logData];

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

        // Reverse the array to show the newest entries first
        filteredData.reverse(); 
        
        renderTable();
        updatePaginationControls();
    } catch (error) {
        console.error('Error fetching message logs:', error);
        tableBody.innerHTML = '<tr><td colspan="6">Error loading data</td></tr>';
    }
}

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

    let rows = '';
    pageData.forEach(item => {
        const attemptStatus = item.attempt_status || 'Unknown';
        let statusClass = '';

        if (attemptStatus.toLowerCase().includes('success')) {
            statusClass = 'success';
        } else if (attemptStatus.toLowerCase().includes('error')) {
            statusClass = 'error';
        } else if (attemptStatus.toLowerCase().includes('skipped')) {
            statusClass = 'skipped';
        } else if (attemptStatus.toLowerCase().includes('warning')) {
            statusClass = 'warning';
        }
        
        // Pass the entire item object to viewResponse
        const itemJson = JSON.stringify(item).replace(/'/g, '&#39;');

        rows += `
            <tr>
                <td>${item.timestamp || 'N/A'}</td>
                <td>${item.order_id || 'N/A'}</td>
                <td>${item.recipient || 'N/A'}</td>
                <td>${item.status || 'N/A'}</td>
                <td class="status-cell ${statusClass}">${attemptStatus}</td>
                <td><button class="view-btn" onclick='viewResponse(${itemJson})'>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 || 1}`;
    document.getElementById('prevBtn').disabled = currentPage === 1;
    document.getElementById('nextBtn').disabled = currentPage >= totalPages || totalPages === 0;
    document.getElementById('totalRows').textContent = `(Total: ${data.length} rows)`;
}

// View raw response in modal
function viewResponse(item) {
    const modal = document.getElementById('responseModal');
    const sentMessageBody = document.getElementById('sentMessageBody');
    const apiResponseCode = document.getElementById('apiResponseCode');
    
    // 1. Sent Message Body
    // Replace the raw newlines with visible content and set as text
    sentMessageBody.textContent = item.sent_message || 'Message content not logged.';
    
    // 2. Full API Data (Request and Response combined)
    const apiData = {
        'timestamp': item.timestamp,
        'order_id': item.order_id,
        'attempt_status': item.attempt_status,
        'recipient': item.recipient,
        'http_code': item.http_code,
        'raw_api_response': item.api_response ? JSON.parse(item.api_response) : item.api_response
    };

    apiResponseCode.textContent = JSON.stringify(apiData, null, 2);
    
    // Highlight the API Response JSON
    hljs.highlightElement(apiResponseCode);
    
    // Since 'sent_message' is not JSON, we just show it as text (no highlight.js for plain text)
    
    modal.style.display = 'flex';
}


// --- 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();
});

// Modal close listeners
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';
};


// Wait for dynamically created search input using MutationObserver (Keeping original logic for completeness)
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 = logData.filter(item =>
                    Object.values(item).some(val =>
                        String(val).toLowerCase().includes(query)
                    )
                );
                // Reverse the array again for filtering (since logData was reversed earlier)
                // filteredData.reverse(); // NO, filter the original, then rely on reverse for display or skip this reverse and just filter. 
                // Let's rely on the initial reverse and just filter the `logData` which is the original order (newest at bottom)
                // Let's re-run the whole fetch/filter process to be safe
                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
});


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

</body>
</html>