<?php
// Exportation de toutes les factures en PDF dans un ZIP
require_once('config/connexion.php');
require_once(__DIR__ . '/vendor/tcpdf/tcpdf.php');

// Nettoyer le buffer avant d'envoyer le ZIP
if (ob_get_level()) {
    ob_end_clean();
}

$date_debut = $_GET['date_debut'] ?? '';
$date_fin = $_GET['date_fin'] ?? '';

if (empty($date_debut) || empty($date_fin)) {
    die('Dates de début et de fin requises');
}
if (!DateTime::createFromFormat('Y-m-d', $date_debut) || !DateTime::createFromFormat('Y-m-d', $date_fin)) {
    die('Format de date invalide');
}

// Récupérer les factures de la période
$sql = "SELECT facture_num, libelle, objet_assure, facture_date, total FROM facture_table WHERE DATE(facture_date) BETWEEN ? AND ? ORDER BY facture_date DESC";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $date_debut, $date_fin);
$stmt->execute();
$stmt->bind_result($facture_num, $libelle, $objet_assure, $facture_date, $total);

$factures = array();
while ($stmt->fetch()) {
    $factures[] = array(
        'facture_num' => $facture_num,
        'libelle' => $libelle,
        'objet_assure' => $objet_assure,
        'facture_date' => $facture_date,
        'total' => $total
    );
}
$stmt->close();

if (empty($factures)) {
    die('Aucune facture trouvée pour cette période');
}

// Note: Le CSS Tailwind de facture.php n'est pas pleinement supporté par TCPDF.
// On utilise donc un template HTML simple et lisible avec styles inline.

// Récupérer les informations de la compagnie (une seule fois)
$sql_company = "SELECT compagnie_name, adresse, tel1, tel2, fax, whatsapp, mail_1, mail_2, mail_3, footer, logo, logo_format, facture_ref, facture_prefixe, facture_suffixe FROM compagnie_table LIMIT 1";
$result_company = $conn->query($sql_company);
$company_info = [];
if ($result_company && $row_company = $result_company->fetch_assoc()) {
        $company_info = [
                'name' => $row_company['compagnie_name'] ?? 'HIBA ASSURANCE',
                'address' => $row_company['adresse'] ?? '',
                'tel1' => $row_company['tel1'] ?? '',
                'tel2' => $row_company['tel2'] ?? '',
                'fax' => $row_company['fax'] ?? '',
                'whatsapp' => $row_company['whatsapp'] ?? '',
                'mail_1' => $row_company['mail_1'] ?? '',
                'mail_2' => $row_company['mail_2'] ?? '',
                'mail_3' => $row_company['mail_3'] ?? '',
                'footer' => $row_company['footer'] ?? '',
                'logo' => $row_company['logo'] ?? '',
                'logo_format' => $row_company['logo_format'] ?? 'wide',
                'facture_ref' => $row_company['facture_ref'] ?? '',
                'facture_prefixe' => $row_company['facture_prefixe'] ?? '',
                'facture_suffixe' => $row_company['facture_suffixe'] ?? ''
        ];
}

// Helpers pour formatage
if (!function_exists('formatClientName')) {
        function formatClientName($client_company, $client_genre) {
                if (empty($client_company)) return 'N/A';
                switch (strtolower((string)$client_genre)) {
                        case 'mâle':
                        case 'masculin':
                        case 'm':
                                return 'M. ' . $client_company;
                        case 'femelle':
                        case 'feminin':
                        case 'f':
                                return 'Mme ' . $client_company;
                        case 'personne morale':
                        case 'morale':
                        case 'societe':
                                return 'STE ' . $client_company;
                        default:
                                return $client_company;
                }
        }
}

if (!function_exists('convertirEnLettres')) {
        function convertirEnLettres($montant) {
                $formatter = new NumberFormatter("fr", NumberFormatter::SPELLOUT);
                $dirhams = floor((float)$montant);
                $centimes = round(((float)$montant - $dirhams) * 100);
                $montantEnLettres = ucfirst($formatter->format($dirhams)) . " dirhams";
                if ($centimes > 0) {
                        $montantEnLettres .= " et " . $formatter->format($centimes) . " centimes";
                }
                return $montantEnLettres;
        }
}

// Créer le ZIP sur un chemin qui n'existe pas encore (évite l'avertissement "Using empty file as ZipArchive is deprecated")
$zip = new ZipArchive();
$tmp_zip = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'factures_zip_' . uniqid('', true) . '.zip';
if (file_exists($tmp_zip)) {
    unlink($tmp_zip);
}
if ($zip->open($tmp_zip, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
    die('Impossible de créer le fichier ZIP');
}

foreach ($factures as $row) {
        $facture_num = $row['facture_num'];

        // Requêter les détails complets comme dans facture.php
        $sql_detail = "SELECT f.facture_num, f.facture_date, f.libelle, f.objet_assure, f.start_date, f.end_date, f.total, c.n_dossier, c.client_company, c.client_genre, c.client_adresse, c.client_ice, p.policy_type, p.policy_category, p.marque 
                                     FROM facture_table f
                                     LEFT JOIN policy_table p ON f.libelle = p.n_policy
                                     LEFT JOIN clients_table c ON p.client_id = c.id
                                     WHERE f.facture_num = ?";
        $stmt2 = $conn->prepare($sql_detail);
        $stmt2->bind_param("s", $facture_num);
        $stmt2->execute();
        $stmt2->bind_result($fn, $fd, $lib, $oa, $sd, $ed, $tot, $nd, $cc, $cg, $ca, $ci, $pt, $pc, $mq);
        $fact = null;
        if ($stmt2->fetch()) {
            $fact = array(
                'facture_num' => $fn,
                'facture_date' => $fd,
                'libelle' => $lib,
                'objet_assure' => $oa,
                'start_date' => $sd,
                'end_date' => $ed,
                'total' => $tot,
                'n_dossier' => $nd,
                'client_company' => $cc,
                'client_genre' => $cg,
                'client_adresse' => $ca,
                'client_ice' => $ci,
                'policy_type' => $pt,
                'policy_category' => $pc,
                'marque' => $mq
            );
        }
        $stmt2->close();
        if (!$fact) { continue; }

        $facture_num_formatted = $fact['facture_num'];
        $nom_client_formate = formatClientName($fact['client_company'] ?? '', $fact['client_genre'] ?? '');
        $total_ttc = (float)($fact['total'] ?? 0);
        $montant_en_lettres = convertirEnLettres($total_ttc);

        // Préparer logo
        $logo_tag = '';
        if (!empty($company_info['logo']) && file_exists($company_info['logo'])) {
                $logo_style = ($company_info['logo_format'] === 'square') ? 'max-width:150px; max-height:150px; object-fit:contain;' : 'max-width:auto; max-height:150px; object-fit:contain;';
                $logo_src = htmlspecialchars($company_info['logo']);
                $logo_tag = '<img src="' . $logo_src . '" style="' . $logo_style . '" alt="Logo" />';
        }

        // Footer multi-lignes
        $footer_display = (string)($company_info['footer'] ?? '');
        $footer_display = str_replace(['\\n','&#10;'], "\n", $footer_display);
        $footer_lines = array_filter(array_map('trim', explode("\n", $footer_display)));
        $footer_html = '';
        if (!empty($footer_lines)) {
                foreach ($footer_lines as $line) {
                        if ($line !== '') {
                                $footer_html .= '<p style="margin:2px 0; text-align:center; line-height:1.2;">' . htmlspecialchars($line) . '</p>';
                        }
                }
        } else {
                $footer_html = '<p style="margin:2px 0; text-align:center;">Intermédiaire d\'assurances régi par la loi 17-99.</p>';
        }

                // Construire l'HTML (template lisible pour TCPDF)
                ob_start();
                ?>
                <div style="font-family: DejaVu Sans, sans-serif; font-size: 11px; color: #111;">
                    <table width="100%" cellpadding="0" cellspacing="0" style="margin-bottom: 8px;">
                        <tr>
                            <td align="left" valign="top"><?php echo $logo_tag ?: '<div style="width:150px; height:75px; border:1px dashed #ccc; display:inline-block; text-align:center; line-height:75px; font-size:12px; color:#666;">Logo</div>'; ?></td>
                            <td align="right" valign="bottom"><h2 style="margin: 0;"># Facture</h2></td>
                        </tr>
                    </table>

                    <table width="100%" cellpadding="6" cellspacing="0" style="background:#f1f5f9; border:1px solid #e3e6f0; margin-bottom: 12px;">
                        <tr>
                            <td width="45%" valign="top" style="border-right:1px solid #e3e6f0;">
                                <div style="width: 100%;">
                                    <h3 style="margin: 0 0 6px 0; font-size: 14px;"><?php echo htmlspecialchars($company_info['name'] ?? ''); ?></h3>
                                    <?php if (!empty($company_info['address'])): ?>
                                        <div>Adresse: <?php echo htmlspecialchars($company_info['address']); ?></div>
                                    <?php endif; ?>
                                    <?php if (!empty($company_info['tel1'])): ?>
                                        <div>Tél: <?php echo htmlspecialchars($company_info['tel1']); ?></div>
                                    <?php endif; ?>
                                    <?php if (!empty($company_info['tel2'])): ?>
                                        <div>Tél: <?php echo htmlspecialchars($company_info['tel2']); ?></div>
                                    <?php endif; ?>
                                    <?php if (!empty($company_info['fax'])): ?>
                                        <div>Fax: <?php echo htmlspecialchars($company_info['fax']); ?></div>
                                    <?php endif; ?>
                                    <?php if (!empty($company_info['whatsapp'])): ?>
                                        <div>WhatsApp: <?php echo htmlspecialchars($company_info['whatsapp']); ?></div>
                                    <?php endif; ?>
                                    <?php if (!empty($company_info['mail_1'])): ?>
                                        <div>Email: <?php echo htmlspecialchars($company_info['mail_1']); ?></div>
                                    <?php endif; ?>
                                    <?php if (!empty($company_info['mail_2'])): ?>
                                        <div>Email: <?php echo htmlspecialchars($company_info['mail_2']); ?></div>
                                    <?php endif; ?>
                                    <?php if (!empty($company_info['mail_3'])): ?>
                                        <div>Email: <?php echo htmlspecialchars($company_info['mail_3']); ?></div>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td width="35%" valign="top" align="right">
                                <div>
                                    <div style="color:#64748b;">Facture N</div>
                                    <div style="font-weight:bold; font-size: 13px; color:#0f766e;"><?php echo htmlspecialchars($facture_num_formatted); ?></div>
                                </div>
                            </td>
                            <td width="20%" valign="top" align="right">
                                <div>
                                    <div style="color:#64748b;">Date</div>
                                    <div style="font-weight:bold; font-size: 13px; color:#0f766e;"><?php echo htmlspecialchars(date('d/m/Y', strtotime($fact['facture_date']))); ?></div>
                                </div>
                                <div style="margin-top:6px;">
                                    <div style="color:#64748b;">N° client</div>
                                    <div style="font-weight:bold; font-size: 13px; color:#0f766e;"><?php echo htmlspecialchars($fact['n_dossier'] ?? 'N/A'); ?></div>
                                </div>
                            </td>
                        </tr>
                    </table>

                    <table width="100%" cellpadding="6" cellspacing="0" style="border:1px solid #e3e6f0; border-collapse: collapse;">
                        <thead>
                            <tr style="background:#0f766e; color:#fff;">
                                <th style="border:1px solid #e3e6f0; text-align:center;">LIBELLE</th>
                                <th style="border:1px solid #e3e6f0; text-align:center;">OBJET ASSURE</th>
                                <th style="border:1px solid #e3e6f0; text-align:center;">DATE D'EFFET</th>
                                <th style="border:1px solid #e3e6f0; text-align:center;">DATE D'ECHEANCE</th>
                                <th style="border:1px solid #e3e6f0; text-align:center;">PRIME TOTAL (DH)</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td style="border:1px solid #e3e6f0; text-align:center;">Police :<br><?php echo htmlspecialchars($fact['libelle'] ?? ''); ?></td>
                                <td style="border:1px solid #e3e6f0; text-align:center;">
                                    <?php
                                    $display = '';
                                    $cat = isset($fact['policy_category']) ? trim($fact['policy_category']) : '';
                                    if (preg_match('/^rd$/i', $cat)) {
                                        $display = htmlspecialchars($fact['policy_type'] ?? '');
                                    } else {
                                        $immat = trim((string)($fact['objet_assure'] ?? ''));
                                        $parts = preg_split('/\s*-\s*/u', $immat);
                                        if (count($parts) === 3) {
                                            $part1 = trim($parts[2]);
                                            $part2 = trim($parts[1]);
                                            $part3 = trim($parts[0]);
                                            $display = $part3 . ' - ' . '<span dir="rtl" style="display:inline-block;">' . $part2 . '</span>' . ' - ' . $part1;
                                        } else {
                                            $display = htmlspecialchars($immat);
                                        }
                                        if (!empty($fact['marque'])) {
                                            $display .= '<br><small style="color:#666; font-style:italic;">' . htmlspecialchars($fact['marque']) . '</small>';
                                        }
                                    }
                                    echo $display;
                                    ?>
                                </td>
                                <td style="border:1px solid #e3e6f0; text-align:center;"><?php echo htmlspecialchars(date('d/m/Y', strtotime($fact['start_date']))); ?></td>
                                <td style="border:1px solid #e3e6f0; text-align:center;"><?php echo htmlspecialchars(date('d/m/Y', strtotime($fact['end_date']))); ?></td>
                                <td style="border:1px solid #e3e6f0; text-align:center; font-weight:bold;"><?php echo number_format($total_ttc, 2, ',', ' '); ?> DH</td>
                            </tr>
                        </tbody>
                    </table>

                    <div style="margin-top: 12px;">
                        <div style="font-weight:bold; color:#0f766e;">Arrêtée la présente facture à la somme de :</div>
                        <div><strong><?php echo htmlspecialchars($montant_en_lettres); ?></strong>.</div>
                    </div>

                    <div style="margin-top: 14px; font-size: 9px; color:#4b5563; text-align:center;">
                        <?php echo $footer_html; ?>
                    </div>
                </div>
                <?php
        $html = ob_get_clean();

        // Générer le PDF à partir du HTML
                $pdf = new TCPDF();
                $pdf->SetMargins(10, 10, 10);
                $pdf->SetAutoPageBreak(TRUE, 12);
                $pdf->AddPage();
                $pdf->writeHTML($html, true, false, true, false, '');
        $pdf_content = $pdf->Output('', 'S');

        // Nom du fichier: dossier unique "Factures" + numéro de facture
        $safe_num = preg_replace('/[^A-Za-z0-9_\-]/', '_', $facture_num_formatted);
        $pdf_filename = 'Factures/Facture_' . $safe_num . '.pdf';
        $zip->addFromString($pdf_filename, $pdf_content);
}
// Connection is managed globally; do not close it here.
$zip->close();

// Envoyer le ZIP au navigateur
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="Factures_' . date('d-m-Y', strtotime($date_debut)) . '_au_' . date('d-m-Y', strtotime($date_fin)) . '.zip"');
header('Content-Length: ' . filesize($tmp_zip));
readfile($tmp_zip);
unlink($tmp_zip);
exit;
