/**
 * @fileoverview Manages the mail log functionality.
 * This file handles:
 * - Filter initialization and updates
 * - Pagination
 * - Mail details modal
 * - Download functionality
 */

document.addEventListener('DOMContentLoaded', function() {
    // Get filter elements
    const statusFilter = document.getElementById('statusFilter');
    const dateRangeFilter = document.getElementById('dateRangeFilter');
    const userFilter = document.getElementById('userFilter');
    const templateFilter = document.getElementById('templateFilter');
    const clearFiltersBtn = document.querySelector('button[onclick="clearFilters()"]');
    
    // Initialize filters from URL parameters
    const urlParams = new URLSearchParams(window.location.search);
    if (statusFilter) statusFilter.value = urlParams.get('status') || '';
    if (dateRangeFilter) dateRangeFilter.value = urlParams.get('date_range') || '7d';
    if (userFilter) userFilter.value = urlParams.get('user_id') || '';
    if (templateFilter) templateFilter.value = urlParams.get('template_id') || '';
    
    // If no filters are set in URL, trigger initial load with default values
    if (!urlParams.toString()) {
        updateFilters();
    }
    
    // Add event listeners for filters
    if (statusFilter) statusFilter.addEventListener('change', updateFilters);
    if (dateRangeFilter) dateRangeFilter.addEventListener('change', updateFilters);
    if (userFilter) userFilter.addEventListener('change', updateFilters);
    if (templateFilter) templateFilter.addEventListener('change', updateFilters);
    
    // Add event listener for clear filters button
    if (clearFiltersBtn) {
        clearFiltersBtn.addEventListener('click', function(e) {
            e.preventDefault();
            clearFilters();
        });
    }
});

function updateFilters() {
    const status = document.getElementById('statusFilter').value;
    const dateRange = document.getElementById('dateRangeFilter').value;
    const userId = document.getElementById('userFilter').value;
    const templateId = document.getElementById('templateFilter').value;
    
    // Build URL with current page number
    const currentPage = new URLSearchParams(window.location.search).get('page') || 1;
    const url = `/settings/mails?page=${currentPage}&status=${status}&date_range=${dateRange}&user_id=${userId}&template_id=${templateId}`;
    
    window.location.href = url;
}

function clearFilters() {
    window.location.href = '/settings/mails';
}

function changePage(page) {
    const status = document.getElementById('statusFilter').value;
    const dateRange = document.getElementById('dateRangeFilter').value;
    const userId = document.getElementById('userFilter').value;
    const templateId = document.getElementById('templateFilter').value;
    
    window.location.href = `/settings/mails?page=${page}&status=${status}&date_range=${dateRange}&user_id=${userId}&template_id=${templateId}`;
}

function viewMailDetails(mailId) {
    const csrfToken = document.querySelector('meta[name="csrf-token"]').content;
    fetch(`/settings/mails/${mailId}`, {
        headers: {
            'X-CSRF-Token': csrfToken
        }
    })
        .then(response => response.json())
        .then(mail => {
            document.getElementById('modalSubject').textContent = mail.subject;
            document.getElementById('modalRecipient').textContent = mail.recipient;
            document.getElementById('modalStatus').innerHTML = `
                <span class="badge ${mail.status === 'pending' ? 'bg-warning' : mail.status === 'sent' ? 'bg-success' : 'bg-danger'}">
                    ${mail.status}
                </span>
            `;
            document.getElementById('modalTemplate').textContent = mail.template ? mail.template.name : '-';
            document.getElementById('modalCreatedAt').textContent = new Date(mail.created_at).toLocaleString();
            document.getElementById('modalSentAt').textContent = mail.sent_at ? new Date(mail.sent_at).toLocaleString() : '-';
            document.getElementById('modalBody').innerHTML = mail.body;
            
            new bootstrap.Modal(document.getElementById('mailDetailsModal')).show();
        });
}

function downloadMailLog() {
    const status = document.getElementById('statusFilter').value;
    const dateRange = document.getElementById('dateRangeFilter').value;
    const userId = document.getElementById('userFilter').value;
    const templateId = document.getElementById('templateFilter').value;
    
    window.location.href = `/settings/mails/download?status=${status}&date_range=${dateRange}&user_id=${userId}&template_id=${templateId}`;
} 