/**
 * Quick Date Filters for Reports
 * Adds quick filter buttons for Today, Yesterday, This Week, This Month, etc.
 */

// Quick date filters functionality
function initializeDateFilters() {
    const dateFromInput = document.querySelector('input[name="date_from"]') || document.querySelector('#date_from');
    const dateToInput = document.querySelector('input[name="date_to"]') || document.querySelector('#date_to');
    
    if (!dateFromInput || !dateToInput) {
        // Silently return if date filters not found - page may not need them
        return;
    }

    // Create quick filter buttons container
    const quickFiltersHtml = `
        <div class="btn-group btn-group-sm mr-2" role="group">
            <button type="button" class="btn btn-outline-primary" onclick="setDateFilter('today')">Today</button>
            <button type="button" class="btn btn-outline-primary" onclick="setDateFilter('yesterday')">Yesterday</button>
            <button type="button" class="btn btn-outline-primary" onclick="setDateFilter('week')">This Week</button>
            <button type="button" class="btn btn-outline-primary" onclick="setDateFilter('month')">This Month</button>
            <button type="button" class="btn btn-outline-primary" onclick="setDateFilter('last_month')">Last Month</button>
            <button type="button" class="btn btn-outline-primary" onclick="setDateFilter('quarter')">This Quarter</button>
            <button type="button" class="btn btn-outline-primary" onclick="setDateFilter('year')">This Year</button>
            <button type="button" class="btn btn-outline-secondary" onclick="clearDateFilter()">Clear</button>
        </div>
    `;

    // Find the best place to insert quick filters
    let targetContainer = null;
    
    // Look for existing filter containers
    const searchForms = document.querySelectorAll('form[method="GET"]');
    if (searchForms.length > 0) {
        const lastForm = searchForms[searchForms.length - 1];
        const buttonGroups = lastForm.querySelectorAll('.btn-group');
        if (buttonGroups.length > 0) {
            // Insert before the last button group
            const lastButtonGroup = buttonGroups[buttonGroups.length - 1];
            lastButtonGroup.insertAdjacentHTML('beforebegin', quickFiltersHtml);
        } else {
            // Insert at the end of the form
            lastForm.insertAdjacentHTML('beforeend', '<div class="col-12 mb-2">' + quickFiltersHtml + '</div>');
        }
    } else {
        // Create a new container above the main content
        const pageHeading = document.querySelector('.d-sm-flex.align-items-center.justify-content-between.mb-4');
        if (pageHeading) {
            pageHeading.insertAdjacentHTML('afterend', 
                `<div class="card shadow-sm mb-3">
                    <div class="card-body py-2">
                        <div class="d-flex align-items-center">
                            <strong class="mr-3 text-muted">Quick Filters:</strong>
                            ${quickFiltersHtml}
                        </div>
                    </div>
                </div>`
            );
        }
    }
}

// Set date filter based on period
function setDateFilter(period) {
    const today = new Date();
    const dateFromInput = document.querySelector('input[name="date_from"]') || document.querySelector('#date_from');
    const dateToInput = document.querySelector('input[name="date_to"]') || document.querySelector('#date_to');
    
    if (!dateFromInput || !dateToInput) return;

    let fromDate, toDate;

    switch(period) {
        case 'today':
            fromDate = toDate = formatDate(today);
            break;
            
        case 'yesterday':
            const yesterday = new Date(today);
            yesterday.setDate(today.getDate() - 1);
            fromDate = toDate = formatDate(yesterday);
            break;
            
        case 'week':
            const startOfWeek = new Date(today);
            const day = today.getDay();
            const diff = today.getDate() - day + (day === 0 ? -6 : 1); // Monday as start of week
            startOfWeek.setDate(diff);
            fromDate = formatDate(startOfWeek);
            toDate = formatDate(today);
            break;
            
        case 'month':
            const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
            fromDate = formatDate(startOfMonth);
            toDate = formatDate(today);
            break;
            
        case 'last_month':
            const startOfLastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1);
            const endOfLastMonth = new Date(today.getFullYear(), today.getMonth(), 0);
            fromDate = formatDate(startOfLastMonth);
            toDate = formatDate(endOfLastMonth);
            break;
            
        case 'quarter':
            const quarter = Math.floor(today.getMonth() / 3);
            const startOfQuarter = new Date(today.getFullYear(), quarter * 3, 1);
            fromDate = formatDate(startOfQuarter);
            toDate = formatDate(today);
            break;
            
        case 'year':
            const startOfYear = new Date(today.getFullYear(), 0, 1);
            fromDate = formatDate(startOfYear);
            toDate = formatDate(today);
            break;
            
        default:
            return;
    }

    dateFromInput.value = fromDate;
    dateToInput.value = toDate;

    // Highlight the selected button
    highlightSelectedFilter(period);
    
    // Auto-submit the form if it exists
    const form = dateFromInput.closest('form');
    if (form && form.method.toLowerCase() === 'get') {
        // Small delay to ensure values are set
        setTimeout(() => {
            form.submit();
        }, 100);
    }
}

// Clear date filters
function clearDateFilter() {
    const dateFromInput = document.querySelector('input[name="date_from"]') || document.querySelector('#date_from');
    const dateToInput = document.querySelector('input[name="date_to"]') || document.querySelector('#date_to');
    
    if (dateFromInput) dateFromInput.value = '';
    if (dateToInput) dateToInput.value = '';
    
    // Remove highlight from all buttons
    document.querySelectorAll('.btn-group button').forEach(btn => {
        btn.classList.remove('active', 'btn-primary');
        if (!btn.classList.contains('btn-outline-secondary')) {
            btn.classList.add('btn-outline-primary');
        }
    });
    
    // Auto-submit the form
    const form = dateFromInput ? dateFromInput.closest('form') : null;
    if (form && form.method.toLowerCase() === 'get') {
        setTimeout(() => {
            form.submit();
        }, 100);
    }
}

// Highlight selected filter button
function highlightSelectedFilter(period) {
    // Remove active state from all buttons
    document.querySelectorAll('.btn-group button').forEach(btn => {
        btn.classList.remove('active', 'btn-primary');
        if (!btn.classList.contains('btn-outline-secondary')) {
            btn.classList.add('btn-outline-primary');
        }
    });
    
    // Add active state to selected button
    const buttons = document.querySelectorAll('.btn-group button');
    const periodMap = {
        'today': 0,
        'yesterday': 1,
        'week': 2,
        'month': 3,
        'last_month': 4,
        'quarter': 5,
        'year': 6
    };
    
    if (periodMap.hasOwnProperty(period) && buttons[periodMap[period]]) {
        const activeBtn = buttons[periodMap[period]];
        activeBtn.classList.remove('btn-outline-primary');
        activeBtn.classList.add('btn-primary', 'active');
    }
}

// Format date to YYYY-MM-DD
function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

// Auto-detect current filter on page load
function detectCurrentFilter() {
    const dateFromInput = document.querySelector('input[name="date_from"]') || document.querySelector('#date_from');
    const dateToInput = document.querySelector('input[name="date_to"]') || document.querySelector('#date_to');
    
    if (!dateFromInput || !dateToInput || !dateFromInput.value || !dateToInput.value) {
        return;
    }
    
    const fromDate = new Date(dateFromInput.value);
    const toDate = new Date(dateToInput.value);
    const today = new Date();
    
    // Check if dates match known patterns
    if (formatDate(fromDate) === formatDate(toDate)) {
        if (formatDate(fromDate) === formatDate(today)) {
            highlightSelectedFilter('today');
        } else {
            const yesterday = new Date(today);
            yesterday.setDate(today.getDate() - 1);
            if (formatDate(fromDate) === formatDate(yesterday)) {
                highlightSelectedFilter('yesterday');
            }
        }
    }
    // Add more pattern detection as needed
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    initializeDateFilters();
    detectCurrentFilter();
});

// Auto-hide sidebar functionality
function initializeAutoHideSidebar() {
    const sidebar = document.getElementById('accordionSidebar');
    const body = document.body;
    
    if (sidebar && body) {
        // Add auto-hide class to body
        body.classList.add('sidebar-toggled');
        
        // Make sure sidebar has the correct classes for mobile/tablet collapse
        if (window.innerWidth <= 768) {
            sidebar.classList.add('toggled');
        }
    }
    
    // Listen for window resize to handle responsive behavior
    window.addEventListener('resize', function() {
        const sidebar = document.getElementById('accordionSidebar');
        if (sidebar && window.innerWidth <= 768) {
            sidebar.classList.add('toggled');
        }
    });
}

// Initialize auto-hide sidebar on page load
document.addEventListener('DOMContentLoaded', function() {
    initializeAutoHideSidebar();
});
