<?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_svg_lines($text, $x, $startY, $fontSize, $weight, $maxChars, $lineHeight) {
    $lines = function_exists('dc_pdf_wrap_text') ? dc_pdf_wrap_text($text, $maxChars) : dc_label_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_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_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>';
    }
    if ($type === 'whatsapp') {
        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>';
    }
    return '';
}

function dc_label_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_download_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, '.');
}

$standardsText = dc_display_standards($door['standards']);
list($standardsSvg, $standardsLines) = dc_label_svg_lines($standardsText, 160, 224, 13, '700', 30, 18);
$afterStandardsY = 224 + max(1, $standardsLines) * 18;

$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="320" height="660" viewBox="0 0 320 660">' . "\n";
$svg .= '<rect width="320" height="660" fill="#fff"/>';
$svg .= '<rect x="18" y="18" width="284" height="624" fill="#fff" stroke="#cc1111" stroke-width="2"/>';
if ($logo) {
    $svg .= dc_label_svg_image($logo, 40, 34, 240, 80, ' preserveAspectRatio="xMidYMid meet"');
} else {
    $svg .= '<text x="160" 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="160" 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="160" 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="160" y="' . (int)($afterStandardsY + 24) . '" 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="160" y="' . (int)($afterStandardsY + 62) . '" 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="160" cy="' . (int)($afterStandardsY + 110) . '" r="42" fill="#fff" stroke="#cc1111" stroke-width="5"/>';
$svg .= '<text x="160" y="' . (int)($afterStandardsY + 125) . '" font-family="Arial, Helvetica, sans-serif" font-size="34" font-weight="900" fill="#cc1111" text-anchor="middle">' . dc_h($ratingNumber) . '</text>';
$svg .= '<text x="160" y="' . (int)($afterStandardsY + 178) . '" font-family="Arial, Helvetica, sans-serif" font-size="13" font-weight="700" text-anchor="middle">Link to Full Info</text>';
if ($qr) {
    $svg .= '<rect x="90" y="' . (int)($afterStandardsY + 192) . '" width="140" height="140" fill="#fff" stroke="#d8dee6" stroke-width="1"/>';
    $svg .= dc_label_svg_image($qr, 96, $afterStandardsY + 198, 128, 128);
} else {
    $svg .= '<rect x="96" y="' . (int)($afterStandardsY + 194) . '" width="128" height="128" fill="#fff" stroke="#111" stroke-width="2"/>';
}
$svg .= '<text x="160" y="572" 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 = 592 + ($i * 28);
    $svg .= dc_label_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>';

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