<?php
require_once __DIR__ . '/../lib/core.php';
dc_require_login();

$stmt = dc_db()->prepare('SELECT d.*, c.code category_code, c.name category_name, p.project_number, p.client_name, p.site_location
    FROM door_cert_doors d
    JOIN door_cert_categories c ON c.id = d.category_id
    JOIN door_cert_projects p ON p.id = d.project_id
    WHERE d.id = ?');
$stmt->execute(array((int)$_GET['id']));
$door = $stmt->fetch();
if (!$door) {
    http_response_code(404);
    exit('Door not found.');
}

$svg = dc_label_svg($door, $width, $height);

if (isset($_GET['format']) && strtolower((string)$_GET['format']) === 'pdf') {
    $filename = dc_label_download_filename($door, 'pdf');
    $pageWidthMm = round($width * 25.4 / 96, 4);
    $pageHeightMm = round($height * 25.4 / 96, 4);
    $svgDataUri = 'data:image/svg+xml;base64,' . base64_encode($svg);
    $libraryScript = dc_pdf_export_library_script();
    header('Content-Type: text/html; charset=utf-8');
    header('Cache-Control: no-store, max-age=0');
    echo '<!doctype html><html><head><meta charset="utf-8"><title>Download Label PDF</title>';
    echo '<style>body{margin:0;background:#f5f7fa;font-family:Arial,Helvetica,sans-serif;color:#13243a}.dc-export-status{padding:20px;font-weight:bold}.dc-label-pdf-source{width:' . (int)$width . 'px;height:' . (int)$height . 'px;background:#fff}</style>';
    echo '</head><body><div class="dc-export-status" id="status">Preparing label PDF...</div>';
    echo '<div id="label-pdf-source" class="dc-label-pdf-source"><img src="' . dc_h($svgDataUri) . '" width="' . (int)$width . '" height="' . (int)$height . '" alt="Door label artwork"></div>';
    echo $libraryScript;
    echo '<script>
(function(){
  var status = document.getElementById("status");
  var source = document.getElementById("label-pdf-source");
  function fail(message) {
    status.textContent = message + " Use Download Label Artwork as a fallback.";
  }
  function start() {
    if (typeof html2pdf === "undefined") {
      fail("PDF library could not be loaded.");
      return;
    }
    html2pdf().set({
      filename: ' . json_encode($filename) . ',
      margin: 0,
      image: { type: "jpeg", quality: 1 },
      html2canvas: { scale: 3, backgroundColor: "#ffffff", useCORS: true },
      jsPDF: { unit: "mm", format: [' . $pageWidthMm . ', ' . $pageHeightMm . '], orientation: "portrait" }
    }).from(source).save().then(function(){
      status.textContent = "Label PDF downloaded.";
    }).catch(function(error){
      fail(error && error.message ? error.message : "PDF generation failed.");
    });
  }
  if (document.readyState === "complete") {
    start();
  } else {
    window.addEventListener("load", start);
  }
})();
</script>';
    echo '</body></html>';
    exit;
}

$filename = dc_label_download_filename($door, 'svg');
header('Content-Type: image/svg+xml; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: no-store, max-age=0');
header('Content-Length: ' . strlen($svg));
echo $svg;
