<?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.');
}

$verifyUrl = dc_verify_url($door);
$qrPath = !empty($door['qr_image_path']) ? __DIR__ . '/../' . $door['qr_image_path'] : '';
if (!is_file($qrPath)) {
    $saved = dc_save_qr($door['door_id'], $verifyUrl);
    $qrPath = $saved ? __DIR__ . '/../' . $saved : '';
    if ($saved) {
        $update = dc_db()->prepare('UPDATE door_cert_doors SET qr_image_path=? WHERE id=?');
        $update->execute(array($saved, $door['id']));
    }
}

$logoAsset = dc_preferred_logo_asset();
$logo = $logoAsset !== '' ? dc_file_data_uri(dc_asset_path($logoAsset)) : '';
$qr = dc_file_data_uri($qrPath);
if (!$qr) {
    $qr = dc_qr_api_url($verifyUrl, 220);
}
$ratingNumber = preg_replace('/\D+/', '', $door['fire_rating']);
if ($ratingNumber === '') {
    $ratingNumber = '120';
}

function dc_label_dl_wrap_text($text, $maxChars)
{
    $words = preg_split('/\s+/', trim((string) $text));
    $lines = array();
    $line = '';
    foreach ($words as $word) {
        if ($word === '') {
            continue;
        }
        $candidate = $line === '' ? $word : $line . ' ' . $word;
        if (strlen($candidate) > $maxChars && $line !== '') {
            $lines[] = $line;
            $line = $word;
        } else {
            $line = $candidate;
        }
    }
    if ($line !== '') {
        $lines[] = $line;
    }
    return $lines ?: array('');
}

function dc_label_dl_svg_lines($text, $x, $startY, $fontSize, $weight, $maxChars, $lineHeight)
{
    $lines = dc_label_dl_wrap_text($text, $maxChars);
    $svg = '';
    foreach ($lines as $i => $line) {
        $svg .= '<text x="' . (int) $x . '" y="' . (int) ($startY + ($i * $lineHeight)) . '" font-family="Arial, Helvetica, sans-serif" font-size="' . (int) $fontSize . '" font-weight="' . dc_h($weight) . '" text-anchor="middle">' . dc_h($line) . '</text>';
    }
    return array($svg, count($lines));
}

function dc_label_dl_svg_contact_icon($type, $x, $y)
{
    $tx = (int) $x;
    $ty = (int) $y;
    if ($type === 'email') {
        return '<g transform="translate(' . $tx . ' ' . $ty . ')"><circle cx="11" cy="11" r="11" fill="#cc1111"/><g transform="translate(4 4) scale(.58)"><path d="M2 6a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v.01L12 13 2 6.01V6z" fill="#fff"/><path d="M2 8.5V18a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V8.5l-10 6.5L2 8.5z" fill="#fff"/></g></g>';
    }
    return '<g transform="translate(' . $tx . ' ' . $ty . ')"><circle cx="11" cy="11" r="11" fill="#cc1111"/><g transform="translate(4 4) scale(.58)"><path fill-rule="evenodd" clip-rule="evenodd" d="M12 2C6.477 2 2 6.477 2 12c0 1.89.525 3.66 1.438 5.168L2 22l4.832-1.438A9.956 9.956 0 0 0 12 22c5.523 0 10-4.477 10-10S17.523 2 12 2zm-2.965 5.545c-.18.04-.43.16-.67.4-.24.24-.92.9-.92 2.19s.94 2.54 1.07 2.72c.13.17 1.83 2.93 4.52 3.99.63.27 1.12.43 1.5.55.63.2 1.2.17 1.66.1.51-.075 1.56-.64 1.78-1.26.22-.62.22-1.15.155-1.26-.065-.11-.24-.175-.5-.305-.26-.13-1.56-.77-1.8-.855-.24-.09-.415-.13-.59.13-.175.26-.675.855-.825 1.03-.15.175-.3.195-.56.065-.26-.13-1.095-.405-2.085-1.285-.77-.685-1.29-1.53-1.44-1.79-.15-.26-.015-.4.115-.53.115-.115.26-.3.39-.45.13-.15.175-.26.26-.435.085-.175.04-.325-.02-.455-.065-.13-.59-1.42-.81-1.94-.21-.5-.425-.43-.59-.44-.2-.005-.4.003-.58.043z" fill="#fff"/></g></g>';
}

function dc_label_dl_svg_image($href, $x, $y, $width, $height, $extra = '')
{
    $href = dc_h($href);
    return '<image href="' . $href . '" xlink:href="' . $href . '" x="' . (int) $x . '" y="' . (int) $y . '" width="' . (int) $width . '" height="' . (int) $height . '"' . $extra . '/>';
}

function dc_label_dl_filename($door, $extension)
{
    $base = preg_replace('/[^A-Za-z0-9_-]+/', '-', (string) $door['door_id']);
    $base = trim($base, '-_');
    if ($base === '') {
        $base = 'door';
    }
    return $base . '-label.' . ltrim((string) $extension, '.');
}

$width = 320;
$center = 160;
$standardsText = dc_display_standards($door['standards']);
list($standardsSvg, $standardsLines) = dc_label_dl_svg_lines($standardsText, $center, 224, 13, '700', 30, 18);
$afterStandardsY = 224 + max(1, $standardsLines) * 18;
$mfgY = $afterStandardsY + 24;
$categoryY = $afterStandardsY + 62;
$ratingCy = $afterStandardsY + 110;
$linkY = $afterStandardsY + 178;
$qrY = $afterStandardsY + 198;
$qrSize = 128;
$doorY = $qrY + $qrSize + 30;
$firstContactY = $doorY + 24;
$height = $firstContactY + 56;

$svg = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
$svg .= '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="' . $width . '" height="' . (int) $height . '" viewBox="0 0 ' . $width . ' ' . (int) $height . '">' . "\n";
$svg .= '<rect width="' . $width . '" height="' . (int) $height . '" fill="#fff"/>';
$svg .= '<rect x="18" y="18" width="284" height="' . ((int) $height - 36) . '" fill="#fff" stroke="#cc1111" stroke-width="2"/>';
if ($logo) {
    $svg .= dc_label_dl_svg_image($logo, 40, 34, 240, 80, ' preserveAspectRatio="xMidYMid meet"');
} else {
    $svg .= '<text x="' . $center . '" y="76" font-family="Arial, Helvetica, sans-serif" font-size="18" font-weight="700" text-anchor="middle">' . dc_h(DC_COMPANY_NAME) . '</text>';
}
$svg .= '<text x="' . $center . '" y="126" font-family="Arial, Helvetica, sans-serif" font-size="12" font-weight="700" text-anchor="middle">Attested by PCSIR</text>';
$svg .= '<line x1="52" y1="146" x2="268" y2="146" stroke="#cc1111" stroke-width="1.5"/>';
$svg .= '<text x="' . $center . '" y="176" font-family="Arial, Helvetica, sans-serif" font-size="15" font-weight="700" text-anchor="middle">AS PER</text>';
$svg .= $standardsSvg;
$svg .= '<text x="' . $center . '" y="' . (int) $mfgY . '" font-family="Arial, Helvetica, sans-serif" font-size="13" font-weight="700" text-anchor="middle">MFG DATE ' . dc_h(dc_format_date($door['manufacture_date'])) . '</text>';
$svg .= '<text x="' . $center . '" y="' . (int) $categoryY . '" font-family="Arial, Helvetica, sans-serif" font-size="26" font-weight="700" fill="#cc1111" text-anchor="middle">' . dc_h($door['category_code']) . '</text>';
$svg .= '<circle cx="' . $center . '" cy="' . (int) $ratingCy . '" r="42" fill="#fff" stroke="#cc1111" stroke-width="5"/>';
$svg .= '<text x="' . $center . '" y="' . (int) ($ratingCy + 15) . '" font-family="Arial, Helvetica, sans-serif" font-size="34" font-weight="900" fill="#cc1111" text-anchor="middle">' . dc_h($ratingNumber) . '</text>';
$svg .= '<text x="' . $center . '" y="' . (int) $linkY . '" font-family="Arial, Helvetica, sans-serif" font-size="13" font-weight="700" text-anchor="middle">Link to Full Info</text>';
$svg .= '<rect x="90" y="' . (int) ($qrY - 6) . '" width="140" height="140" fill="#fff" stroke="#d8dee6" stroke-width="1"/>';
if ($qr) {
    $svg .= dc_label_dl_svg_image($qr, 96, $qrY, $qrSize, $qrSize);
}
$svg .= '<text x="' . $center . '" y="' . (int) $doorY . '" font-family="Arial, Helvetica, sans-serif" font-size="10" font-weight="700" text-anchor="middle">' . dc_h($door['door_id']) . '</text>';
$contacts = array(
    array('email', DC_COMPANY_EMAIL),
    array('whatsapp', DC_COMPANY_PHONE),
);
foreach ($contacts as $i => $contact) {
    $y = $firstContactY + ($i * 28);
    $svg .= dc_label_dl_svg_contact_icon($contact[0], 76, $y - 17);
    $svg .= '<text x="104" y="' . (int) $y . '" font-family="Arial, Helvetica, sans-serif" font-size="11" font-weight="700">' . dc_h($contact[1]) . '</text>';
}
$svg .= '</svg>';

if (isset($_GET['format']) && strtolower((string) $_GET['format']) === 'pdf') {
    $filename = dc_label_dl_filename($door, 'pdf');
    $pageWidthMm = round($width * 25.4 / 96, 4);
    $pageHeightMm = round($height * 25.4 / 96, 4);
    $pdfWidthMm = $pageWidthMm + 0.5;
    $pdfHeightMm = $pageHeightMm + 0.5;
    $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{display:block;width:' . (int) $width . 'px;height:' . (int) $height . 'px;overflow:hidden;background:#fff;font-size:0;line-height:0}.dc-label-pdf-source img{display:block;width:' . (int) $width . 'px;height:' . (int) $height . 'px;margin:0;padding:0;border:0}</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, scrollX: 0, scrollY: 0 },
      jsPDF: { unit: "mm", format: [' . $pdfWidthMm . ', ' . $pdfHeightMm . '], 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_dl_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;
