document.addEventListener('DOMContentLoaded', function() { // DOM Elements const ticketsBody = document.getElementById('ticketsBody'); const refreshBtn = document.getElementById('refreshBtn'); const downloadBtn = document.getElementById('downloadBtn'); const totalTicketsEl = document.getElementById('total-tickets'); const totalCountEl = document.getElementById('total-count'); const uniqueCountriesEl = document.getElementById('unique-countries'); // Load data when page loads fetchData(); // Event listeners refreshBtn.addEventListener('click', fetchData); downloadBtn.addEventListener('click', downloadCSV); // Fetch data from server function fetchData() { fetch('/get_tickets') .then(response => response.json()) .then(data => { renderTable(data.tickets); updateStats(data.tickets); }) .catch(error => { console.error('Error fetching data:', error); alert('Error fetching data. Please try again.'); }); } // Render table with ticket data function renderTable(tickets) { ticketsBody.innerHTML = ''; if (tickets.length === 0) { ticketsBody.innerHTML = 'No ticket data available'; return; } tickets.forEach(ticket => { const row = document.createElement('tr'); row.innerHTML = ` ${ticket.ticket_number} ${ticket.name} ${ticket.email} ${ticket.phone} ${ticket.tickets_count} ${ticket.country} ${ticket.region} ${formatDate(ticket.timestamp)} `; ticketsBody.appendChild(row); }); } // Update statistics cards function updateStats(tickets) { totalTicketsEl.textContent = tickets.length; const totalCount = tickets.reduce((sum, ticket) => sum + ticket.tickets_count, 0); totalCountEl.textContent = totalCount; const uniqueCountries = new Set(tickets.map(ticket => ticket.country)); uniqueCountriesEl.textContent = uniqueCountries.size; } // Format date for display function formatDate(dateString) { const options = { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }; return new Date(dateString).toLocaleDateString('en-US', options); } // Download CSV function downloadCSV() { window.location.href = '/download_csv'; } });