<?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']));
    }
}
if (!is_file($qrPath)) {
    $qrData = dc_http_get(dc_qr_api_url($verifyUrl, 320));
    if (dc_is_png_data($qrData) && strlen($qrData) > 100) {
        $qrPath = tempnam(sys_get_temp_dir(), 'dc_qr_') . '.png';
        file_put_contents($qrPath, $qrData);
    }
}

$ratingNumber = preg_replace('/\D+/', '', $door['fire_rating']);
if ($ratingNumber === '') {
    $ratingNumber = '120';
}

$tmp = tempnam(sys_get_temp_dir(), 'dc_label_');
$zip = new ZipArchive();
$zip->open($tmp, ZipArchive::OVERWRITE);
$zip->addFromString('[Content_Types].xml', '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Default Extension="jpeg" ContentType="image/jpeg"/><Default Extension="jpg" ContentType="image/jpeg"/><Default Extension="png" ContentType="image/png"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>');
$zip->addFromString('_rels/.rels', '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>');

$rels = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">';
$logoAsset = dc_preferred_logo_asset();
if ($logoAsset !== '') {
    $zip->addFile(dc_asset_path($logoAsset), 'word/media/logo.jpeg');
    $rels .= '<Relationship Id="rLogo" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/logo.jpeg"/>';
}
if (is_file($qrPath)) {
    $zip->addFile($qrPath, 'word/media/qr.png');
    $rels .= '<Relationship Id="rQr" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/qr.png"/>';
}
$rels .= '</Relationships>';
$zip->addFromString('word/_rels/document.xml.rels', $rels);

function dc_label_docx_p($text, $bold = false, $size = 22, $spaceAfter = 90) {
    $b = $bold ? '<w:b/>' : '';
    return '<w:p><w:pPr><w:jc w:val="center"/><w:spacing w:after="' . (int)$spaceAfter . '"/></w:pPr><w:r><w:rPr>' . $b . '<w:sz w:val="' . (int)$size . '"/></w:rPr><w:t>' . dc_h($text) . '</w:t></w:r></w:p>';
}

function dc_label_docx_rule() {
    return '<w:p><w:pPr><w:jc w:val="center"/><w:spacing w:after="120"/></w:pPr><w:r><w:t>____________________________</w:t></w:r></w:p>';
}

$xml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
$xml .= '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><w:body>';
$xml .= '<w:tbl><w:tblPr><w:tblW w:w="4300" w:type="dxa"/><w:jc w:val="center"/><w:tblCellMar><w:top w:w="260" w:type="dxa"/><w:left w:w="240" w:type="dxa"/><w:bottom w:w="260" w:type="dxa"/><w:right w:w="240" w:type="dxa"/></w:tblCellMar><w:tblBorders><w:top w:val="single" w:sz="18"/><w:left w:val="single" w:sz="18"/><w:bottom w:val="single" w:sz="18"/><w:right w:val="single" w:sz="18"/></w:tblBorders></w:tblPr><w:tr><w:tc><w:tcPr><w:tcW w:w="4300" w:type="dxa"/></w:tcPr>';
if ($logoAsset !== '') {
    $xml .= dc_docx_image('rLogo', 2300000, 810000, 'SAMCON Associates Pvt Ltd Logo');
}
$xml .= dc_label_docx_p('Attested by PCSIR', true, 20, 120);
$xml .= dc_label_docx_rule();
$xml .= dc_label_docx_p('AS PER', true, 24, 140);
$xml .= dc_label_docx_p(dc_display_standards($door['standards']), true, 20, 160);
$xml .= dc_label_docx_p('MFG DATE ' . dc_format_date($door['manufacture_date']), true, 20, 180);
$xml .= dc_label_docx_p($door['category_code'], true, 34, 120);
$xml .= dc_label_docx_p($ratingNumber, true, 60, 180);
$xml .= dc_label_docx_p('Link to Full Info', true, 20, 100);
if (is_file($qrPath)) {
    $xml .= dc_docx_image('rQr', 1700000, 1700000, 'QR Code');
} else {
    $xml .= dc_label_docx_p('QR image could not be generated. Use Download Label Artwork.', false, 16, 90);
}
$xml .= dc_label_docx_p($door['door_id'], true, 17, 70);
$xml .= dc_label_docx_p('@ ' . DC_COMPANY_EMAIL, true, 16, 40);
$xml .= dc_label_docx_p('TEL ' . DC_COMPANY_PHONE, true, 16, 40);
$xml .= dc_label_docx_p('WA ' . DC_COMPANY_PHONE, true, 16, 40);
$xml .= dc_label_docx_p('WEB ' . dc_company_website_label(), true, 16, 40);
$xml .= '</w:tc></w:tr></w:tbl>';
$xml .= '<w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="720" w:right="720" w:bottom="720" w:left="720"/></w:sectPr>';
$xml .= '</w:body></w:document>';

$zip->addFromString('word/document.xml', $xml);
$zip->close();

header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Disposition: attachment; filename="' . $door['door_id'] . '-label.docx"');
header('Content-Length: ' . filesize($tmp));
readfile($tmp);
unlink($tmp);
