<?php
// /smproduce/utils/pdf_page_png.php?pdf=/smproduce/pdf/templates/bill_of_lading_template.pdf&page=1
$pdfRel = $_GET['pdf'] ?? '';
$page = max(1, (int)($_GET['page'] ?? 1));

if (!preg_match('#^/smproduce/pdf/templates/[a-zA-Z0-9_\-\/]+\.pdf$#', $pdfRel)) {
  http_response_code(400); echo "Invalid pdf path"; exit;
}

$pdfAbs = __DIR__ . '/..' . $pdfRel;
if (!file_exists($pdfAbs)) { http_response_code(404); echo "PDF not found"; exit; }

$cacheDir = __DIR__ . '/../cache/pdf_pages';
if (!is_dir($cacheDir)) @mkdir($cacheDir, 0775, true);

$hash = md5($pdfRel);
$outAbs = $cacheDir . "/{$hash}_p{$page}.png";
$outWeb = "/smproduce/cache/pdf_pages/{$hash}_p{$page}.png";

if (file_exists($outAbs)) {
  header("Location: $outWeb");
  exit;
}

if (!extension_loaded('imagick')) {
  http_response_code(500); echo "Imagick not enabled"; exit;
}

$img = new Imagick();
$img->setResolution(200, 200);
$img->readImage($pdfAbs . '[' . ($page-1) . ']');
$img->setImageFormat('png');
$img->writeImage($outAbs);
$img->clear();

header("Location: $outWeb");
