\
<?php
/**
 * PDF engine minimalista (1 página) con:
 * - Textos: UTF-8 -> Windows-1252 (WinAnsi) para acentos
 * - Símbolo € (Differences 128 /Euro)
 * - Imagen JPEG (logo) como XObject
 */

function pdf_to_win1252(string $s): string {
  $s = str_replace(["\r\n","\r"], "\n", $s);
  if (function_exists('iconv')) {
    $converted = @iconv('UTF-8', 'Windows-1252//TRANSLIT', $s);
    if ($converted !== false) $s = $converted;
  }
  return $s;
}

function pdf_escape(string $s): string {
  $s = pdf_to_win1252($s);
  return str_replace(['\\','(',')'], ['\\\\','\(','\)'], $s);
}

function pdf_text($x,$y,$text,$size=11): string {
  $t=pdf_escape((string)$text);
  return "BT /F1 $size Tf $x $y Td ($t) Tj ET\n";
}

function pdf_line($x1,$y1,$x2,$y2,$w=0.5): string {
  return "$w w $x1 $y1 m $x2 $y2 l S\n";
}

function pdf_image_do($name,$x,$y,$w,$h): string {
  // matriz: [w 0 0 h x y] cm
  return "q $w 0 0 $h $x $y cm /$name Do Q\n";
}

function pdf_build_onepage(string $content, ?array $jpeg=null): string {
  // $jpeg: ['name'=>'Im1','bytes'=>..., 'w'=>..., 'h'=>...]
  $objects=[];

  $resources = "/Resources << /Font << /F1 4 0 R >>";
  $xobject_ref = "";
  if ($jpeg) {
    $resources .= " /XObject << /".$jpeg['name']." 6 0 R >>";
    $xobject_ref = "6 0 obj << /Type /XObject /Subtype /Image /Width ".$jpeg['w']." /Height ".$jpeg['h']." /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length ".strlen($jpeg['bytes'])." >> stream\n".$jpeg['bytes']."\nendstream endobj\n";
  }
  $resources .= " >>";

  $objects[]="1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n";
  $objects[]="2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n";
  $objects[]="3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] $resources /Contents 5 0 R >> endobj\n";

  // Helvetica con WinAnsi + Euro
  $objects[]="4 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding << /Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences [128 /Euro] >> >> endobj\n";

  $objects[]="5 0 obj << /Length ".strlen($content)." >> stream\n".$content."endstream endobj\n";
  if ($jpeg) $objects[]=$xobject_ref;

  $pdf="%PDF-1.4\n";
  $offsets=[];
  foreach($objects as $obj){ $offsets[]=strlen($pdf); $pdf.=$obj; }
  $xref=strlen($pdf);
  $pdf.="xref\n0 ".(count($objects)+1)."\n";
  $pdf.="0000000000 65535 f \n";
  foreach($offsets as $o){ $pdf.=str_pad((string)$o,10,'0',STR_PAD_LEFT)." 00000 n \n"; }
  $pdf.="trailer << /Size ".(count($objects)+1)." /Root 1 0 R >>\n";
  $pdf.="startxref\n$xref\n%%EOF";
  return $pdf;
}

function pdf_load_jpeg(string $absPath, string $name='Im1'): ?array {
  if (!is_file($absPath)) return null;
  $info = @getimagesize($absPath);
  if (!$info || ($info[2] ?? 0) !== IMAGETYPE_JPEG) return null;
  $bytes = file_get_contents($absPath);
  if ($bytes === false) return null;
  return ['name'=>$name,'bytes'=>$bytes,'w'=>$info[0],'h'=>$info[1]];
}
