// Export functionality for the Antibiotic Management System

// Export to PDF
function exportToPDF() {
    const exportBtn = document.querySelector('[onclick="exportToPDF()"]');
    if (exportBtn) {
        exportBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> جاري التصدير...';
        exportBtn.disabled = true;
    }
    
    // Get current page data
    const currentPage = window.location.pathname.split('/').pop();
    let exportUrl = 'export/pdf_export.php';
    
    // Add page-specific parameters
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.toString()) {
        exportUrl += '?' + urlParams.toString() + '&page=' + currentPage;
    } else {
        exportUrl += '?page=' + currentPage;
    }
    
    // Add timestamp to prevent caching
    exportUrl += (exportUrl.includes('?') ? '&' : '?') + 'v=' + Date.now();
    
    // Open in new window with specific size
    const newWindow = window.open(exportUrl, '_blank', 'width=1200,height=800');
    
    if (!newWindow) {
        // If popup blocked, try direct navigation
        window.location.href = exportUrl;
    }
    
    // Reset button
    setTimeout(() => {
        if (exportBtn) {
            exportBtn.innerHTML = '<i class="fas fa-file-pdf"></i> تصدير PDF';
            exportBtn.disabled = false;
        }
    }, 1000);
    
    // Show notification if function exists
    if (typeof showNotification === 'function') {
        showNotification('تم فتح صفحة التصدير - اضغط طباعة لحفظ PDF', 'success');
    }
}

// Export to Excel
function exportToExcel() {
    const exportBtn = document.querySelector('[onclick="exportToExcel()"]');
    if (exportBtn) {
        exportBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> جاري التصدير...';
        exportBtn.disabled = true;
    }
    
    // Get current page data
    const currentPage = window.location.pathname.split('/').pop();
    let exportUrl = 'export/excel_export.php';
    
    // Add page-specific parameters
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.toString()) {
        exportUrl += '?' + urlParams.toString() + '&page=' + currentPage;
    } else {
        exportUrl += '?page=' + currentPage;
    }
    
    // Add timestamp to prevent caching
    exportUrl += (exportUrl.includes('?') ? '&' : '?') + 'v=' + Date.now();
    
    // Direct navigation to download the file (server will send proper headers)
    window.location.href = exportUrl;
    
    // Reset button
    setTimeout(() => {
        if (exportBtn) {
            exportBtn.innerHTML = '<i class="fas fa-file-excel"></i> تصدير Excel';
            exportBtn.disabled = false;
        }
    }, 1000);
    
    // Show notification if function exists
    if (typeof showNotification === 'function') {
        showNotification('جاري تحميل ملف Excel...', 'success');
    }
}

// Export table to Excel (client-side)
function exportTableToExcel(tableId, filename = 'data') {
    const table = document.getElementById(tableId);
    if (!table) {
        showNotification('لم يتم العثور على الجدول', 'error');
        return;
    }
    
    // Create workbook
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.table_to_sheet(table);
    
    // Add worksheet to workbook
    XLSX.utils.book_append_sheet(wb, ws, 'البيانات');
    
    // Save file
    XLSX.writeFile(wb, `${filename}_${new Date().toISOString().split('T')[0]}.xlsx`);
    
    showNotification('تم تصدير الجدول بنجاح', 'success');
}

// Export chart as image
function exportChartAsImage(chartId, filename = 'chart') {
    const canvas = document.getElementById(chartId);
    if (!canvas) {
        showNotification('لم يتم العثور على الرسم البياني', 'error');
        return;
    }
    
    // Create download link
    const link = document.createElement('a');
    link.download = `${filename}_${new Date().toISOString().split('T')[0]}.png`;
    link.href = canvas.toDataURL();
    link.click();
    
    showNotification('تم تصدير الرسم البياني بنجاح', 'success');
}

// Print current page
function printPage() {
    // Hide non-printable elements
    const nonPrintable = document.querySelectorAll('.no-print, .btn, .navbar, .sidebar');
    nonPrintable.forEach(element => {
        element.style.display = 'none';
    });
    
    // Print
    window.print();
    
    // Restore elements
    nonPrintable.forEach(element => {
        element.style.display = '';
    });
}

// Export specific report to PDF
function exportReportToPDF(reportId) {
    if (!reportId) {
        showNotification('معرف التقرير مطلوب', 'error');
        return;
    }
    
    const link = document.createElement('a');
    link.href = `export/report_pdf.php?id=${reportId}`;
    link.download = `report_${reportId}_${new Date().toISOString().split('T')[0]}.pdf`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    showNotification('تم بدء تصدير التقرير', 'success');
}

// Export filtered data
function exportFilteredData(filters = {}) {
    const queryString = new URLSearchParams(filters).toString();
    const exportUrl = `export/filtered_export.php?${queryString}`;
    
    // Show export options modal
    showExportModal(exportUrl);
}

// Show export options modal
function showExportModal(baseUrl) {
    const modalHtml = `
        <div class="modal fade" id="exportModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">خيارات التصدير</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">نوع الملف:</label>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="exportType" value="pdf" id="exportPDF" checked>
                                <label class="form-check-label" for="exportPDF">PDF</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="exportType" value="excel" id="exportExcel">
                                <label class="form-check-label" for="exportExcel">Excel</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="exportType" value="csv" id="exportCSV">
                                <label class="form-check-label" for="exportCSV">CSV</label>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="dateRange" class="form-label">نطاق التاريخ:</label>
                            <select class="form-select" id="dateRange">
                                <option value="all">جميع التواريخ</option>
                                <option value="today">اليوم</option>
                                <option value="week">هذا الأسبوع</option>
                                <option value="month">هذا الشهر</option>
                                <option value="year">هذا العام</option>
                                <option value="custom">نطاق مخصص</option>
                            </select>
                        </div>
                        <div id="customDateRange" class="mb-3" style="display: none;">
                            <div class="row">
                                <div class="col-md-6">
                                    <label for="startDate" class="form-label">من تاريخ:</label>
                                    <input type="date" class="form-control" id="startDate">
                                </div>
                                <div class="col-md-6">
                                    <label for="endDate" class="form-label">إلى تاريخ:</label>
                                    <input type="date" class="form-control" id="endDate">
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="includeCharts">
                                <label class="form-check-label" for="includeCharts">
                                    تضمين الرسوم البيانية
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                        <button type="button" class="btn btn-primary" onclick="processExport('${baseUrl}')">تصدير</button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // Remove existing modal
    const existingModal = document.getElementById('exportModal');
    if (existingModal) {
        existingModal.remove();
    }
    
    // Add modal to page
    document.body.insertAdjacentHTML('beforeend', modalHtml);
    
    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('exportModal'));
    modal.show();
    
    // Handle date range change
    document.getElementById('dateRange').addEventListener('change', function() {
        const customRange = document.getElementById('customDateRange');
        if (this.value === 'custom') {
            customRange.style.display = 'block';
        } else {
            customRange.style.display = 'none';
        }
    });
}

// Process export with selected options
function processExport(baseUrl) {
    const exportType = document.querySelector('input[name="exportType"]:checked').value;
    const dateRange = document.getElementById('dateRange').value;
    const includeCharts = document.getElementById('includeCharts').checked;
    
    let exportUrl = baseUrl + `&type=${exportType}&range=${dateRange}&charts=${includeCharts}`;
    
    // Add custom date range if selected
    if (dateRange === 'custom') {
        const startDate = document.getElementById('startDate').value;
        const endDate = document.getElementById('endDate').value;
        if (startDate && endDate) {
            exportUrl += `&start_date=${startDate}&end_date=${endDate}`;
        }
    }
    
    // Create download link
    const link = document.createElement('a');
    link.href = exportUrl;
    link.download = `export_${new Date().toISOString().split('T')[0]}.${exportType}`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    // Close modal
    const modal = bootstrap.Modal.getInstance(document.getElementById('exportModal'));
    modal.hide();
    
    showNotification('تم بدء التصدير', 'success');
}

// Bulk export selected items
function exportSelected() {
    const checkboxes = document.querySelectorAll('input[name="selected_items[]"]:checked');
    if (checkboxes.length === 0) {
        showNotification('يرجى اختيار عنصر واحد على الأقل', 'warning');
        return;
    }
    
    const selectedIds = Array.from(checkboxes).map(cb => cb.value);
    const exportUrl = `export/bulk_export.php?ids=${selectedIds.join(',')}`;
    
    showExportModal(exportUrl);
}

// Initialize export functionality
document.addEventListener('DOMContentLoaded', function() {
    // Add export buttons to tables
    const tables = document.querySelectorAll('.table');
    tables.forEach(table => {
        if (table.id && !table.querySelector('.export-buttons')) {
            const exportButtons = document.createElement('div');
            exportButtons.className = 'export-buttons mb-3';
            exportButtons.innerHTML = `
                <button type="button" class="btn btn-sm btn-outline-success me-2" onclick="exportTableToExcel('${table.id}')">
                    <i class="fas fa-file-excel"></i> Excel
                </button>
                <button type="button" class="btn btn-sm btn-outline-danger" onclick="printPage()">
                    <i class="fas fa-print"></i> طباعة
                </button>
            `;
            table.parentNode.insertBefore(exportButtons, table);
        }
    });
});

// Load SheetJS library if not already loaded
if (typeof XLSX === 'undefined') {
    const script = document.createElement('script');
    script.src = 'https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js';
    document.head.appendChild(script);
}