/**
 * Admin Reports Locations Page JavaScript
 * اسکریپت اختصاصی صفحه گزارشات مکان‌ها
 */

// Helper functions for Persian numbers
function toPersianNumbers(str) {
    const persianDigits = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
    return str.toString().replace(/\d/g, (digit) => persianDigits[parseInt(digit)]);
}

function toEnglishNumbers(str) {
    const persianDigits = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
    const englishDigits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    
    let result = str.toString();
    for (let i = 0; i < persianDigits.length; i++) {
        result = result.replace(new RegExp(persianDigits[i], 'g'), englishDigits[i]);
    }
    return result;
}

// Persian months for charts
const persianMonths = [
    'فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور',
    'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند'
];

// Chart configuration
function getChartConfig() {
    const locale = document.documentElement.lang || 'fa';
    
    return {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                labels: {
                    font: {
                        family: locale === 'fa' ? 'IRANSans, sans-serif' : 'Arial, sans-serif'
                    }
                }
            },
            tooltip: {
                titleFont: {
                    family: locale === 'fa' ? 'IRANSans, sans-serif' : 'Arial, sans-serif'
                },
                bodyFont: {
                    family: locale === 'fa' ? 'IRANSans, sans-serif' : 'Arial, sans-serif'
                }
            }
        },
        scales: {
            x: {
                ticks: {
                    font: {
                        family: locale === 'fa' ? 'IRANSans, sans-serif' : 'Arial, sans-serif'
                    }
                }
            },
            y: {
                ticks: {
                    font: {
                        family: locale === 'fa' ? 'IRANSans, sans-serif' : 'Arial, sans-serif'
                    }
                }
            }
        }
    };
}

// Format numbers based on locale
function formatNumber(num) {
    const locale = document.documentElement.lang || 'fa';
    if (locale === 'fa') {
        return toPersianNumbers(num.toLocaleString());
    }
    return num.toLocaleString();
}

// Show toast notification
function showToast(message, type = 'info') {
    // Create toast element
    const toast = document.createElement('div');
    toast.className = `toast align-items-center text-white bg-${type === 'error' ? 'danger' : type} border-0`;
    toast.setAttribute('role', 'alert');
    toast.innerHTML = `
        <div class="d-flex">
            <div class="toast-body">${message}</div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
        </div>
    `;
    
    // Add to page
    let toastContainer = document.querySelector('.toast-container');
    if (!toastContainer) {
        toastContainer = document.createElement('div');
        toastContainer.className = 'toast-container position-fixed top-0 end-0 p-3';
        document.body.appendChild(toastContainer);
    }
    
    toastContainer.appendChild(toast);
    
    // Show toast
    if (typeof bootstrap !== 'undefined') {
        const bsToast = new bootstrap.Toast(toast);
        bsToast.show();
        
        // Remove after hide
        toast.addEventListener('hidden.bs.toast', () => {
            toast.remove();
        });
    } else {
        // Fallback without Bootstrap
        toast.style.display = 'block';
        setTimeout(() => {
            toast.remove();
        }, 5000);
    }
}

// Animate numbers
function animateNumber(element, start, end, duration = 1000) {
    const range = end - start;
    const increment = range / (duration / 16);
    let current = start;
    
    const timer = setInterval(() => {
        current += increment;
        if (current >= end) {
            current = end;
            clearInterval(timer);
        }
        element.textContent = formatNumber(Math.floor(current));
    }, 16);
}

// Show location on map
function showLocationOnMap(lat, lng) {
    if (!lat || !lng) {
        showToast('مختصات این مکان موجود نیست', 'warning');
        return;
    }
    
    // Open in new window with map
    const mapUrl = `https://maps.google.com/maps?q=${lat},${lng}&z=15&output=embed`;
    window.open(mapUrl, '_blank', 'width=800,height=600');
}

// Export data
function exportData(format) {
    const loadingOverlay = document.getElementById('loadingOverlay');
    if (loadingOverlay) {
        loadingOverlay.classList.add('show');
    }
    
    const params = new URLSearchParams(window.location.search);
    params.set('export', format);
    
    const exportUrl = window.location.pathname + '?' + params.toString();
    
    // Create temporary link and trigger download
    const link = document.createElement('a');
    link.href = exportUrl;
    link.download = `locations-report-${new Date().toISOString().split('T')[0]}.${format}`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    if (loadingOverlay) {
        setTimeout(() => {
            loadingOverlay.classList.remove('show');
        }, 1000);
    }
    
    showToast(`خروجی ${format.toUpperCase()} در حال دانلود...`, 'success');
}

// Toggle DataTable columns
function toggleColumns() {
    if (window.locationsTable && $.fn.DataTable.isDataTable('#locationsTable')) {
        $('.buttons-colvis').trigger('click');
    }
}

// Refresh table
function refreshTable() {
    const loadingOverlay = document.getElementById('loadingOverlay');
    if (loadingOverlay) {
        loadingOverlay.classList.add('show');
    }
    
    setTimeout(() => {
        window.location.reload();
    }, 1000);
}

// Update statistics via AJAX
function updateStatistics() {
    fetch(window.location.href + '?ajax=1')
        .then(response => response.json())
        .then(data => {
            if (data.stats) {
                const elements = {
                    'totalLocations': data.stats.total,
                    'activeLocations': data.stats.active,
                    'premiumLocations': data.stats.premium,
                    'todayLocations': data.stats.today
                };
                
                Object.entries(elements).forEach(([id, value]) => {
                    const element = document.getElementById(id);
                    if (element) {
                        element.textContent = formatNumber(value);
                    }
                });
            }
        })
        .catch(error => {
            console.error('Error updating statistics:', error);
        });
}

// Update today counter
function updateTodayCounter() {
    fetch('/admin/api/locations/today-count')
        .then(response => response.json())
        .then(data => {
            const element = document.getElementById('todayLocations');
            if (element) {
                element.textContent = formatNumber(data.count);
            }
        })
        .catch(error => {
            console.error('Error updating today counter:', error);
        });
}

// Initialize auto-refresh
function initializeAutoRefresh() {
    // Update statistics every 5 minutes
    setInterval(updateStatistics, 300000);
    
    // Update "today" counter every minute
    setInterval(updateTodayCounter, 60000);
}

// Initialize number animations
function initializeNumberAnimations() {
    setTimeout(() => {
        const statsNumbers = document.querySelectorAll('.stats-number');
        statsNumbers.forEach(element => {
            const finalValue = parseInt(element.textContent.replace(/[^\d]/g, ''));
            if (!isNaN(finalValue)) {
                element.textContent = '0';
                animateNumber(element, 0, finalValue, 1500);
            }
        });
    }, 500);
}

// Export table data as CSV
function exportTableData() {
    const table = document.getElementById('locationsTable');
    if (!table) {
        showToast('جدول یافت نشد', 'error');
        return;
    }

    let csv = [];
    const rows = table.querySelectorAll('tr');

    for (let i = 0; i < rows.length; i++) {
        const row = [];
        const cols = rows[i].querySelectorAll('td, th');

        for (let j = 0; j < cols.length - 1; j++) { // Skip last column (actions)
            let cellText = cols[j].innerText.trim();
            // Clean up text
            cellText = cellText.replace(/"/g, '""');
            row.push('"' + cellText + '"');
        }
        csv.push(row.join(','));
    }

    // Create and download CSV file
    const csvContent = csv.join('\n');
    const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');

    if (link.download !== undefined) {
        const url = URL.createObjectURL(blob);
        link.setAttribute('href', url);
        link.setAttribute('download', `locations-report-${new Date().toISOString().split('T')[0]}.csv`);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        showToast('فایل CSV دانلود شد', 'success');
    } else {
        showToast('مرورگر شما از دانلود پشتیبانی نمی‌کند', 'error');
    }
}

// Make functions globally available
window.showLocationOnMap = showLocationOnMap;
window.exportData = exportData;
window.exportTableData = exportTableData;
window.toggleColumns = toggleColumns;
window.refreshTable = refreshTable;
window.showToast = showToast;
