<?php
/**
 * Génération PDF des bulletins
 * - Dompdf (par défaut)
 * - mPDF + template PDF background (si un template est fourni)
 */
require_once __DIR__ . '/../vendor/autoload.php';

use Dompdf\Dompdf;
use Dompdf\Options;

function generateBulletinPDF(string $html, string $filename = 'bulletin.pdf', string $pageFormat = 'A4', string $orientation = 'portrait'): void {
    $options = new Options();
    $options->set('isHtml5ParserEnabled', true);
    $options->set('isRemoteEnabled', true);
    $options->set('isFontSubsettingEnabled', true);
    $options->set('defaultPaperSize', $pageFormat);
    $options->set('defaultPaperOrientation', $orientation);
    $options->set('dpi', 150);
    $options->set('defaultFont', 'dejavu sans');

    $dompdf = new Dompdf($options);
    $dompdf->loadHtml($html);
    $dompdf->setPaper($pageFormat, $orientation);
    $dompdf->render();

    $dompdf->stream($filename, ['Attachment' => true]);
    exit;
}

function generateBulletinPDFInline(string $html): string {
    $options = new Options();
    $options->set('isHtml5ParserEnabled', true);
    $options->set('isRemoteEnabled', true);
    $options->set('isFontSubsettingEnabled', true);
    $options->set('defaultPaperSize', 'A4');
    $options->set('defaultPaperOrientation', 'portrait');
    $options->set('dpi', 150);
    $options->set('defaultFont', 'dejavu sans');

    $dompdf = new Dompdf($options);
    $dompdf->loadHtml($html);
    $dompdf->setPaper('A4', 'portrait');
    $dompdf->render();
    return $dompdf->output();
}

/**
 * Génère un bulletin PDF avec un fichier PDF comme fond de page (template)
 * Utilise mPDF qui supporte l'import de pages PDF existantes.
 */
function generateBulletinPDFWithTemplate(string $html, string $filename, string $templatePath): void {
    $mpdf = new \Mpdf\Mpdf([
        'mode'                => 'utf-8',
        'format'              => 'A4',
        'orientation'         => 'P',
        'margin_left'         => 8,
        'margin_right'        => 8,
        'margin_top'          => 10,
        'margin_bottom'       => 10,
        'margin_header'       => 0,
        'margin_footer'       => 0,
        'tempDir'             => sys_get_temp_dir() . '/mpdf_nukunu',
        'autoLangToFont'      => true,
        'autoScriptToLang'    => true,
        'default_font_size'   => 10,
        'default_font'        => 'dejavusans',
        'shrink_tables_to_fit' => 1,
        'auto_page_break'     => 8,
    ]);

    // Importer la première page du template PDF comme fond plein page
    if (file_exists($templatePath)) {
        $pageCount = $mpdf->SetSourceFile($templatePath);
        if ($pageCount > 0) {
            $tplId = $mpdf->importPage(1);
            $mpdf->useTemplate($tplId, 0, 0, 210, 297);
        }
    }

    // Ajouter le contenu HTML par-dessus le template
    $styledHtml = '<div style="position:relative;">' . $html . '</div>';
    $mpdf->WriteHTML($styledHtml);

    $mpdf->Output($filename, \Mpdf\Output\Destination::DOWNLOAD);
    exit;
}

/**
 * Récupère le chemin du template PDF assigné à une classe/école
 * Retourne null si aucun template trouvé.
 */
function getBulletinTemplatePath(PDO $pdo, int $schoolId, int $classId, string $academicYear): ?string {
    // Priorité : (class_id + year) > (class_id seul) > (school_id + year) > (school_id seul)
    $sql = "
        SELECT bt.filename
        FROM bulletin_template_assignments bta
        JOIN bulletin_templates bt ON bta.template_id = bt.id
        WHERE bt.is_active = 1
          AND (
               (bta.school_id = ? AND bta.class_id = ? AND bta.academic_year = ?)
            OR (bta.school_id = ? AND bta.class_id = ? AND bta.academic_year IS NULL)
            OR (bta.school_id = ? AND bta.class_id IS NULL AND bta.academic_year = ?)
            OR (bta.school_id = ? AND bta.class_id IS NULL AND bta.academic_year IS NULL)
          )
        ORDER BY
            CASE
                WHEN bta.class_id = ? AND bta.academic_year = ? THEN 1
                WHEN bta.class_id = ? AND bta.academic_year IS NULL THEN 2
                WHEN bta.class_id IS NULL AND bta.academic_year = ? THEN 3
                ELSE 4
            END
        LIMIT 1
    ";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        $schoolId, $classId, $academicYear,
        $schoolId, $classId,
        $schoolId, $academicYear,
        $schoolId,
        $classId, $academicYear,
        $classId,
        $academicYear,
    ]);
    $row = $stmt->fetch();
    if ($row && $row['filename']) {
        $path = __DIR__ . '/../uploads/bulletin_templates/' . $row['filename'];
        return file_exists($path) ? $path : null;
    }
    return null;
}
