<?php
declare(strict_types=1);
if(!isset($_SESSION)){
    session_start();
}

/* ===== Anti-corruption de flux ===== */
ini_set('zlib.output_compression', 'Off');
while (ob_get_level()) { ob_end_clean(); }

/* ===== Rôles autorisés ===== */
$AUTHORIZED = ['admin','ca','bureau'];

/* ===== Includes ===== */
require_once  './model/BDD.PHP';
require_once  './model/class/Ouvrage.php';
require_once  './model/class/Type.php';             // si séparé
require_once  './scripts/lib/fpdf/fpdf.php';        // https://www.fpdf.org/
require_once  './scripts/lib/phpqrcode/qrlib.php';  // https://sourceforge.net/projects/phpqrcode/

/* ===== Secure role check ===== */
$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, $AUTHORIZED, true)) {
    http_response_code(403);
    exit;
}

/* ===== Paramètre ===== */
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id <= 0) {
    http_response_code(400);
    exit;
}

/* ===== Récupération ouvrage ===== */
$ouvrage = Ouvrage::findById($id);
if (!$ouvrage) {
    http_response_code(404);
    exit;
}

/* ===== Helpers ===== */
function latin1(string $s): string {
    $x = @iconv('UTF-8','ISO-8859-1//TRANSLIT',$s);
    return $x !== false ? $x : utf8_decode($s);
}
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 ===== */
$numero    = (string)($ouvrage->getNumero() ?? '');
$titre     = (string)($ouvrage->getTitre() ?? '');
$typeObj   = $ouvrage->getId_type();
$typeLabel = ($typeObj instanceof Type) ? (string)($typeObj->getLibelle() ?? '-') : (string)$typeObj;

/* ===== QR (URL signée via Ouvrage::scanUrl) ===== */
$url = Ouvrage::scanUrl((int)$ouvrage->getId_ouvrage());
$tmp = tempnam(sys_get_temp_dir(), 'qr_') . '.png';
QRcode::png($url, $tmp, QR_ECLEVEL_M, 6);

/* ===== Mise en page : A6 portrait ===== */
/* A6 = 105 × 148 mm */
$pdf = new FPDF('P', 'mm', [105, 148]);
$pdf->SetTitle(latin1('QR Ouvrage'));
$pdf->SetAuthor(latin1('Ludothèque'));
$margin = 8;
$pdf->SetMargins($margin, $margin, $margin);
$pdf->AddPage();

/* Cadre + QR centré */
$qrSize = 60;                       // taille fixe ⇒ pas compressé
$usableW = 105 - 2*$margin;
$centerX = ($usableW - $qrSize) / 2 + $margin;
$y = $margin + 4;

$pdf->Rect($margin, $margin, 105 - 2*$margin, 148 - 2*$margin, 'D');
$pdf->Image($tmp, $centerX, $y, $qrSize, $qrSize, 'PNG');

/* Texte sous le QR */
$textW = 105 - 2*$margin - 8;       // un peu de marge interne
$yText = $y + $qrSize + 6;

$pdf->SetFont('Arial','B',12);
$pdf->SetXY($margin + 4, $yText);
$line1 = fitText($pdf, "N°: ".$numero, $textW);
$pdf->Cell($textW, 7, latin1($line1), 0, 2, 'C');

$pdf->SetFont('Arial','',11);
$pdf->SetX($margin + 4);
$line2 = fitText($pdf, $titre, $textW);
$pdf->Cell($textW, 6, latin1($line2), 0, 2, 'C');

if (!empty($typeLabel)) {
    $pdf->SetFont('Arial','I',9.5);
    $pdf->SetX($margin + 4);
    $line3 = fitText($pdf, (string)$typeLabel, $textW);
    $pdf->Cell($textW, 5, latin1($line3), 0, 2, 'C');
}

/* ===== Sortie ===== */
$pdfData = $pdf->Output('S');
@unlink($tmp);

while (ob_get_level()) { ob_end_clean(); }
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="qr_ouvrage_'.$id.'.pdf"');
header('Content-Length: ' . strlen($pdfData));
echo $pdfData;
exit;
