<?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>html,body{margin:0;padding: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;overflow:hidden;background:#fff;line-height:0}.dc-label-pdf-source img{display:block;width:' . (int)$width . 'px;height:' . (int)$height . 'px}</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 waitForLabelImage() {
    var image = source ? source.querySelector("img") : null;
    if (!image) {
      return Promise.resolve();
    }
    if (image.complete && image.naturalWidth > 0) {
      if (image.decode) {
        return image.decode().catch(function(){});
      }
      return Promise.resolve();
    }
    return new Promise(function(resolve) {
      var done = function() {
        image.removeEventListener("load", done);
        image.removeEventListener("error", done);
        if (image.decode) {
          image.decode().catch(function(){}).then(resolve);
        } else {
          resolve();
        }
      };
      image.addEventListener("load", done);
      image.addEventListener("error", done);
      window.setTimeout(done, 5000);
    });
  }
  function start() {
    if (typeof html2pdf === "undefined") {
      fail("PDF library could not be loaded.");
      return;
    }
    waitForLabelImage().then(function(){
      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).toPdf().get("pdf").then(function(pdf){
      var pageCount = pdf && pdf.internal && pdf.internal.getNumberOfPages ? pdf.internal.getNumberOfPages() : 1;
      for (var page = pageCount; page > 1; page--) {
        pdf.deletePage(page);
      }
    }).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;
