<?php
if(!isset($_SESSION)){
    session_start();
}


// Vérification rôle autorisé
$authorizedRoles = ['admin', 'ca', 'bureau'];
$userRole = null;

if (isset($_SESSION['user'])) {
    if (method_exists($_SESSION['user'], 'getRole')) {
        $userRole = strtolower($_SESSION['user']->getRole());
    } elseif (method_exists($_SESSION['user'], 'getId_rolle')) {
        switch ($_SESSION['user']->getId_rolle()) {
            case 1: $userRole = 'admin'; break;
            case 2: $userRole = 'ca'; break;
            case 3: $userRole = 'bureau'; break;
            default: $userRole = 'user'; break;
        }
    }
}

if (!in_array($userRole, $authorizedRoles, true)) {
    http_response_code(403);
    echo 'Accès réservé aux administrateurs, CA ou bureau.';
    exit;
}


// === Includes (adapte les chemins à ton arborescence) ===
require_once './model/Bdd.php';
require_once './scripts/lib/fpdf/fpdf.php';   // FPDF sans Composer
require_once './scripts/lib/phpqrcode/qrlib.php';
require_once './model/class/Emprunt.php';
require_once './model/class/Ouvrage.php';

session_start();

/* === Vérif session + rôle côté serveur (PAS DE HTML) === */
$userRole = null;
if (isset($_SESSION['user'])) {
    if (method_exists($_SESSION['user'], 'getRole')) {
        $userRole = strtolower((string)$_SESSION['user']->getRole());
    } elseif (method_exists($_SESSION['user'], 'getId_rolle')) {
        switch ((int)$_SESSION['user']->getId_rolle()) {
            case 1: $userRole = 'admin';  break;
            case 2: $userRole = 'ca';     break;
            case 3: $userRole = 'bureau'; break;
            default: $userRole = 'user';
        }
    }
}
if (!in_array($userRole, $authorizedRoles, true)) {
    http_response_code(403);
    exit; // rien d’autre (pas d’echo)
}
/* === Utilitaires === */
function latin1(string $s): string {
    $x = @iconv('UTF-8','ISO-8859-1//TRANSLIT',$s);
    return $x !== false ? $x : utf8_decode($s);
}

/** Coupe proprement une chaîne pour tenir sur une largeur en mm (FPDF) */
function fitText(FPDF $pdf, string $text, float $maxWidth): string {
    $text = preg_replace('/\s+/', ' ', trim($text));
    if ($pdf->GetStringWidth(latin1($text)) <= $maxWidth) return $text;
    $ellipsis = '…';
    $wEll = $pdf->GetStringWidth(latin1($ellipsis));
    $out = '';
    for ($i=0, $n=mb_strlen($text); $i<$n; $i++) {
        $t = $out . mb_substr($text, $i, 1);
        if ($pdf->GetStringWidth(latin1($t)) + $wEll > $maxWidth) {
            return $out . $ellipsis;
        }
        $out = $t;
    }
    return $out;
}

/* === Données === */
$ouvrages = Ouvrage::getAllOuvrages();

/* === Mise en page : A4 paysage, 4 colonnes, cellules fixes === */
$orientation = 'L';            // 'P' portrait ; 'L' paysage
$cols = 4;                     // nb colonnes (portrait=3 conseille, paysage=4)
$margin = 10;                  // mm
$qrSize = 45;                  // taille QR (mm), constante ⇒ pas “compressé”
$headerH = 12;                 // hauteur du header
$cellPadding = 4;              // padding interne de cellule

// Calculs formats A4
$pageW = ($orientation === 'L') ? 297 : 210;
$pageH = ($orientation === 'L') ? 210 : 297;

$usableW = $pageW - 2*$margin;
$cellW   = $usableW / $cols;

// Hauteur de cellule = QR + 2*padding + lignes texte
$titleH  = 5;   // hauteur ligne titre
$subH    = 4;   // hauteur ligne sous-titre
$lines   = 2;   // nombre de lignes max (1 titre, 1 sous)
$cellH   = $qrSize + 2*$cellPadding + $titleH + $subH + 2; // marge fine

/* === PDF === */
$pdf = new FPDF($orientation,'mm','A4');
$pdf->SetTitle(latin1('QR Codes Ouvrages'));
$pdf->SetAuthor(latin1('Ludothèque'));
$pdf->SetMargins($margin, $margin, $margin);
$pdf->SetAutoPageBreak(true, $margin);
$pdf->AddPage();

$pdf->SetFont('Arial','B',14);
$pdf->Cell(0, $headerH, latin1('QR Codes - Ouvrages'), 0, 1, 'C');
$pdf->Ln(2);

$pdf->SetFont('Arial','',9);

$tmpFiles = [];
$rowY = $pdf->GetY();
$colIndex = 0;

if (empty($ouvrages)) {
    $pdf->SetFont('Arial','I',12);
    $pdf->Cell(0, 10, latin1('Aucun ouvrage'), 0, 1, 'C');
    $pdfData = $pdf->Output('S');
    while (ob_get_level()) { ob_end_clean(); }
    header('Content-Type: application/pdf');
    header('Content-Disposition: inline; filename="qr_ouvrages.pdf"');
    header('Content-Length: ' . strlen($pdfData));
    echo $pdfData;
    exit;
}

foreach ($ouvrages as $idx => $o) {
    // Données affichage
    $id        = (int)$o->getId_ouvrage();
    $numero    = (string)($o->getNumero() ?? '');
    $titre     = (string)($o->getTitre() ?? '');
    $typeObj   = $o->getId_type();
    $typeLabel = ($typeObj instanceof Type) ? (string)($typeObj->getLibelle() ?? '-') : (string)$typeObj;

    // Position X/Y de la cellule courante
    $x = $margin + $colIndex * $cellW;
    $y = $rowY;

    // Saut de page si on dépasse
    if ($y + $cellH > $pageH - $margin) {
        $pdf->AddPage();
        $pdf->SetFont('Arial','B',14);
        $pdf->Cell(0, $headerH, latin1('QR Codes - Ouvrages (suite)'), 0, 1, 'C');
        $pdf->Ln(2);
        $pdf->SetFont('Arial','',9);
        $rowY = $pdf->GetY();
        $y = $rowY;
        $colIndex = 0;
        $x = $margin;
    }

    // Cadre de la cellule (propre, fond blanc)
    $pdf->SetFillColor(255,255,255);
    $pdf->Rect($x, $y, $cellW, $cellH, 'D');

    // Génère QR en fichier tmp (le QR garde une taille fixe $qrSize)
    $url = Ouvrage::scanUrl($id);
    $tmp = tempnam(sys_get_temp_dir(), 'qr_') . '.png';
    QRcode::png($url, $tmp, QR_ECLEVEL_M, 6); // ECC M ; module size 6
    $tmpFiles[] = $tmp;

    // Place le QR centré horizontalement
    $imgX = $x + ($cellW - $qrSize)/2;
    $imgY = $y + $cellPadding;
    $pdf->Image($tmp, $imgX, $imgY, $qrSize, $qrSize, 'PNG');

    // Zone de texte sous le QR
    $textX = $x + 2;
    $textW = $cellW - 4;

    // Ligne 1 : Numéro (gras)
    $pdf->SetFont('Arial','B',9);
    $pdf->SetXY($textX, $imgY + $qrSize + 2);
    $line1 = 'N°: ' . $numero;
    $line1 = fitText($pdf, $line1, $textW);
    $pdf->Cell($textW, $titleH, latin1($line1), 0, 2, 'C');

    // Ligne 2 : Titre (normal)
    $pdf->SetFont('Arial','',8.5);
    $line2 = fitText($pdf, $titre, $textW);
    $pdf->Cell($textW, $subH, latin1($line2), 0, 2, 'C');

    // (Option) Ligne 3 : Type (italique) → décommente si tu veux
    // $pdf->SetFont('Arial','I',8);
    // $line3 = fitText($pdf, (string)$typeLabel, $textW);
    // $pdf->Cell($textW, 4, latin1($line3), 0, 2, 'C');

    // Colonne suivante
    $colIndex++;
    if ($colIndex >= $cols) {
        // passe à la ligne
        $colIndex = 0;
        $rowY += $cellH + 6; // espacement vertical entre lignes
    }
}

// Données PDF en mémoire et envoi propre
$pdfData = $pdf->Output('S');
foreach ($tmpFiles as $f) { @unlink($f); }

while (ob_get_level()) { ob_end_clean(); }
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="qr_ouvrages.pdf"');
header('Content-Length: ' . strlen($pdfData));
echo $pdfData;
exit;