// pdf-export-final.js - Export PDF avec format paysage garanti pour le tableau

/**
 * Export PDF avec tableau détaillé en format paysage garanti
 */
async function exportToPDFComplete() {
    try {
        showTemporaryMessage('📄 Génération du PDF en cours...', 'warning');
        
        const { jsPDF } = window.jspdf;
        
        // Créer PDF en portrait pour les graphiques
        const pdf = new jsPDF('portrait', 'mm', 'a4');
        pdf.setFont("helvetica");
        pdf.setCharSpace(0);
        
        const portraitWidth = pdf.internal.pageSize.getWidth();
        const portraitHeight = pdf.internal.pageSize.getHeight();
        
        // === PAGES PORTRAIT ===
        await addPortraitContent(pdf, portraitWidth, portraitHeight);
        
        // === PAGES PAYSAGE POUR TABLEAU ===
        // Important: Créer les pages paysage manuellement
        await addLandscapeTableDirectly(pdf);
        
        // Télécharger
        const fileName = `OZIXSOFT_Rapport_${new Date().toISOString().split('T')[0]}_${Date.now()}.pdf`;
        pdf.save(fileName);
        
        showTemporaryMessage('✅ PDF généré avec tableau paysage', 'success');
        console.log('📄 Export PDF complet réussi:', fileName);
        
    } catch (error) {
        console.error('❌ Erreur export PDF:', error);
        showTemporaryMessage('❌ Erreur lors de l\'export PDF', 'error');
    }
}

async function addPortraitContent(pdf, pageWidth, pageHeight) {
    const margin = 15;
    let currentY = margin;
    
    // === EN-TÊTE ===
    pdf.setFontSize(22);
    pdf.setTextColor(102, 126, 234);
    pdf.text('KOMBAR FERD', margin, currentY);
    currentY += 8;
    
    pdf.setFontSize(18);
    pdf.text('Rapport de Pesees Detaille', margin, currentY);
    currentY += 12;
    
    // Date
    pdf.setFontSize(11);
    pdf.setTextColor(80, 80, 80);
    const now = new Date();
    pdf.text(`Genere le ${now.toLocaleDateString('fr-FR')} a ${now.toLocaleTimeString('fr-FR', {hour: '2-digit', minute: '2-digit'})}`, margin, currentY);
    currentY += 12;
    
    // === FILTRES ===
    pdf.setDrawColor(200, 200, 200);
    pdf.rect(margin, currentY, pageWidth - 2*margin, 25);
    currentY += 6;
    
    pdf.setFontSize(12);
    pdf.setTextColor(0, 0, 0);
    pdf.text('Criteres de Filtrage:', margin + 3, currentY);
    currentY += 6;
    
    pdf.setFontSize(10);
    const filters = reportsData.currentFilters;
    
    const periodText = filters.period === 'custom' 
        ? `Periode personnalisee: ${filters.startDate} vers ${filters.endDate}`
        : `Periode: ${filters.period}`;
    pdf.text(`- ${periodText}`, margin + 3, currentY);
    currentY += 4;
    
    if (filters.site !== 'all') {
        pdf.text(`- Site: ${filters.site}`, margin + 3, currentY);
        currentY += 4;
    }
    if (filters.client !== 'all') {
        pdf.text(`- Client: ${filters.client}`, margin + 3, currentY);
        currentY += 4;
    }
    if (filters.fournisseur !== 'all') {
        pdf.text(`- Fournisseur: ${filters.fournisseur}`, margin + 3, currentY);
        currentY += 4;
    }
    currentY += 10;
    
    // === MÉTRIQUES ===
    pdf.setFontSize(16);
    pdf.setTextColor(102, 126, 234);
    pdf.text('Metriques Cles', margin, currentY);
    currentY += 10;
    
    const metrics = {
        totalWeighings: document.getElementById('totalWeighingsMetric')?.textContent || '0',
        totalWeight: document.getElementById('totalWeightMetric')?.textContent || '0 T',
        avgWeight: document.getElementById('avgWeightMetric')?.textContent || '0 kg',
        activeClients: document.getElementById('activeClientsMetric')?.textContent || '0',
        activeFournisseurs: document.getElementById('activeFournisseursMetric')?.textContent || '0'
    };
    
    pdf.setFontSize(11);
    pdf.setTextColor(0, 0, 0);
    const col1X = margin;
    const col2X = pageWidth / 2 + 10;
    
    pdf.text(`Total des pesees: ${metrics.totalWeighings}`, col1X, currentY);
    pdf.text(`Clients actifs: ${metrics.activeClients}`, col2X, currentY);
    currentY += 6;
    
    pdf.text(`Poids total: ${metrics.totalWeight}`, col1X, currentY);
    pdf.text(`Fournisseurs actifs: ${metrics.activeFournisseurs}`, col2X, currentY);
    currentY += 6;
    
    pdf.text(`Poids moyen: ${metrics.avgWeight}`, col1X, currentY);
    currentY += 15;
    
    // === GRAPHIQUES COMPACTS ===
    const chartsToExport = [
        { id: 'evolutionChart', title: 'Evolution des Pesees' },
        { id: 'productsChart', title: 'Repartition par Produit' },
        { id: 'topClientsChart', title: 'Top 10 Clients' },
        { id: 'topFournisseursChart', title: 'Top 10 Fournisseurs' },
        { id: 'sitesChart', title: 'Performance par Site' },
        { id: 'clientFournisseurChart', title: 'Relations Client-Fournisseur' }
    ];
    
    for (const chartInfo of chartsToExport) {
        const chartElement = document.getElementById(chartInfo.id);
        if (!chartElement) continue;
        
        try {
            if (currentY > pageHeight - 100) {
                pdf.addPage('portrait');
                currentY = margin;
            }
            
            pdf.setFontSize(14);
            pdf.setTextColor(102, 126, 234);
            pdf.text(chartInfo.title, margin, currentY);
            currentY += 8;
            
            const chartContainer = chartElement.closest('.chart-card');
            if (!chartContainer) continue;
            
            const canvas = await html2canvas(chartContainer, {
                backgroundColor: '#ffffff',
                scale: 2,
                useCORS: true,
                allowTaint: false,
                logging: false
            });
            
            const imgData = canvas.toDataURL('image/png', 0.90);
            const maxWidth = pageWidth - 2 * margin;
            const maxHeight = 70;
            
            let imgWidth = maxWidth;
            let imgHeight = (canvas.height * imgWidth) / canvas.width;
            
            if (imgHeight > maxHeight) {
                imgHeight = maxHeight;
                imgWidth = (canvas.width * imgHeight) / canvas.height;
            }
            
            const imgX = (pageWidth - imgWidth) / 2;
            
            if (currentY + imgHeight > pageHeight - margin) {
                pdf.addPage('portrait');
                currentY = margin;
                pdf.setFontSize(14);
                pdf.setTextColor(102, 126, 234);
                pdf.text(chartInfo.title, margin, currentY);
                currentY += 8;
            }
            
            pdf.addImage(imgData, 'PNG', imgX, currentY, imgWidth, imgHeight);
            currentY += imgHeight + 12;
            
        } catch (error) {
            console.warn(`Erreur capture ${chartInfo.id}:`, error);
        }
    }
}

async function addLandscapeTableDirectly(pdf) {
    // Récupérer les données
    const data = await loadReportsData();
    if (!data || data.length === 0) {
        return;
    }
    
    // Créer une nouvelle page et forcer l'orientation paysage
    // Méthode alternative : manipuler directement les dimensions
    const landscapeWidth = 297;
    const landscapeHeight = 210;
    
    // Ajouter page avec dimensions forcées
    pdf.addPage();
    
    // Forcer l'orientation en modifiant les dimensions internes
    const currentPageIndex = pdf.internal.getNumberOfPages();
    pdf.internal.pages[currentPageIndex][2] = landscapeWidth;  // largeur
    pdf.internal.pages[currentPageIndex][3] = landscapeHeight; // hauteur
    
    // Alternative: utiliser internal pour forcer l'orientation
    pdf.internal.pageSize = {
        width: landscapeWidth,
        height: landscapeHeight,
        getWidth: function() { return landscapeWidth; },
        getHeight: function() { return landscapeHeight; }
    };
    
    const margin = 15;
    let currentY = margin;
    
    // Titre
    pdf.setFontSize(16);
    pdf.setTextColor(102, 126, 234);
    pdf.text('Donnees Detaillees (Format Paysage)', margin, currentY);
    currentY += 12;
    
    // Configuration tableau pour format paysage
    const colWidths = [35, 35, 50, 50, 45, 40, 35];
    const headers = ['Date', 'Code', 'Client', 'Fournisseur', 'Produit', 'Site', 'Poids'];
    
    // En-têtes colorés
    pdf.setFillColor(102, 126, 234);
    pdf.setTextColor(255, 255, 255);
    pdf.setFontSize(10);
    
    // Dessiner rectangle d'en-tête sur toute la largeur
    const totalTableWidth = colWidths.reduce((sum, width) => sum + width, 0);
    pdf.rect(margin, currentY, totalTableWidth, 10, 'F');
    
    let startX = margin + 3;
    headers.forEach((header, index) => {
        pdf.text(header, startX, currentY + 7);
        startX += colWidths[index];
    });
    currentY += 15;
    
    // Données du tableau
    pdf.setTextColor(0, 0, 0);
    pdf.setFontSize(9);
    
    const maxRowsPerPage = Math.floor((landscapeHeight - currentY - 20) / 6);
    let rowCount = 0;
    
    for (let i = 0; i < Math.min(500, data.length); i++) {
        const item = data[i];
        
        if (rowCount >= maxRowsPerPage) {
            // Nouvelle page paysage
            pdf.addPage();
            
            // Forcer à nouveau les dimensions paysage
            const newPageIndex = pdf.internal.getNumberOfPages();
            pdf.internal.pages[newPageIndex][2] = landscapeWidth;
            pdf.internal.pages[newPageIndex][3] = landscapeHeight;
            pdf.internal.pageSize = {
                width: landscapeWidth,
                height: landscapeHeight,
                getWidth: function() { return landscapeWidth; },
                getHeight: function() { return landscapeHeight; }
            };
            
            currentY = margin;
            
            // Répéter en-têtes
            pdf.setFillColor(102, 126, 234);
            pdf.setTextColor(255, 255, 255);
            pdf.setFontSize(10);
            pdf.rect(margin, currentY, totalTableWidth, 10, 'F');
            
            startX = margin + 3;
            headers.forEach((header, index) => {
                pdf.text(header, startX, currentY + 7);
                startX += colWidths[index];
            });
            currentY += 15;
            
            pdf.setTextColor(0, 0, 0);
            pdf.setFontSize(9);
            rowCount = 0;
        }
        
        // Alternance de couleurs
        if (rowCount % 2 === 0) {
            pdf.setFillColor(248, 249, 250);
            pdf.rect(margin, currentY - 1, totalTableWidth, 6, 'F');
        }
        
        // Données de la ligne
        const rowData = [
            new Date(item.dmv).toLocaleDateString('fr-FR'),
            item.CodePesee || '-',
            item.NomClient || '-',
            item.NomFournisseur || '-',
            item.NomProduit || '-',
            item.NomSite || item.CodeSite || '-',
            `${parseFloat(item.PoidsNet || 0).toLocaleString()} kg`
        ];
        
        startX = margin + 3;
        rowData.forEach((cellData, index) => {
            let text = cellData.toString();
            // Largeurs plus généreuses en paysage
            const maxLen = index < 2 ? 15 : (index === 6 ? 18 : 25);
            if (text.length > maxLen) {
                text = text.substring(0, maxLen - 2) + '..';
            }
            pdf.text(text, startX, currentY + 4);
            startX += colWidths[index];
        });
        
        currentY += 6;
        rowCount++;
    }
    
    // Note si données tronquées
    if (data.length > 500) {
        currentY += 8;
        pdf.setFontSize(10);
        pdf.setTextColor(150, 150, 150);
        pdf.text(`Note: Affichage des 500 premieres lignes sur ${data.length} total.`, margin, currentY);
    }
}

// Export pour utilisation globale
if (typeof window !== 'undefined') {
    window.exportToPDFComplete = exportToPDFComplete;
}