<?php
// ============================================================
// HumidityLabCertificate  — implements ILabCertificate
// Generates the GSA Humidity Lab calibration certificate.
// Mirrors the save_to_pdf / save_to_xml Python functions.
// ============================================================

require_once __DIR__ . '/../HumidityUncertaintyEngine.php';
require_once __DIR__ . '/../form/HumidityLabForm.php';

class HumidityLabCertificate implements ILabCertificate {

    // ── Signature helper ─────────────────────────────────────
    public function renderSignature(array $officer): string {
        if (!empty($officer['signature'])) {
            $path = SIGNATURE_PATH . $officer['signature'];
            if (file_exists($path)) {
                $data = base64_encode(file_get_contents($path));
                $ext  = strtolower(pathinfo($path, PATHINFO_EXTENSION));
                $mime = $ext === 'png' ? 'image/png' : 'image/jpeg';
                return '<img src="data:' . $mime . ';base64,' . $data
                     . '" style="max-height:65px;max-width:220px;display:block;" alt="Signature">';
            }
        }
        return '<div style="height:55px;border-bottom:1px solid #000;width:220px;margin-bottom:4px;"></div>';
    }

    // ── HTML Certificate ─────────────────────────────────────
    public function generateHTML(
        array $request,
        array $formData,
        array $officer,
        string $certNum,
        string $issueDate
    ): string {
        $e      = fn($v) => htmlspecialchars((string)($v ?? ''), ENT_QUOTES, 'UTF-8');
        $f      = $formData;
        $r      = $request;
        $sig    = $this->renderSignature($officer);
        $fmtD   = fn($v) => $v ? date('d M Y', strtotime($v)) : '';
        $results = HumidityLabForm::buildResults($f);

        // ── RH results table rows ────────────────────────────
        $rh_rows = '';
        foreach ($results as $res) {
            $rh_rows .= '<tr>
              <td style="text-align:center;">'  . $e($res['setpoint'])           . '</td>
              <td style="text-align:center;">'  . $e(number_format((float)$res['corrected_ref_temp'], 2)) . '</td>
              <td style="text-align:center;">'  . $e(number_format((float)$res['corrected_ref_rh'],  2)) . '</td>
              <td style="text-align:center;">'  . $e(number_format((float)$res['avg_eut_rh'],        2)) . '</td>
              <td style="text-align:center;">'  . $e(number_format((float)$res['rh_deviation'],      4)) . '</td>
              <td style="text-align:center;">'  . $e(number_format((float)$res['rh_uncertainty'],    3)) . '</td>
            </tr>';
        }

        // ── Temperature results table rows (only where include_temp) ──
        $temp_rows = '';
        foreach ($results as $res) {
            if ($res['include_temp']) {
                $temp_rows .= '<tr>
                  <td style="text-align:center;">' . $e($res['setpoint'])                                       . '</td>
                  <td style="text-align:center;">' . $e(number_format((float)$res['corrected_ref_temp'], 2))    . '</td>
                  <td style="text-align:center;">' . $e(number_format((float)$res['avg_eut_temp'],       2))    . '</td>
                  <td style="text-align:center;">' . $e(number_format((float)$res['temp_deviation'],     4))    . '</td>
                  <td style="text-align:center;">' . $e(number_format((float)$res['temp_uncertainty'],   3))    . '</td>
                </tr>';
            }
        }
        if (!$temp_rows) {
            $temp_rows = '<tr><td colspan="5" style="text-align:center;color:#888;font-size:9pt;">Temperature results included only at ~50 %RH setpoints.</td></tr>';
        }

        $css = '<style>
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:Arial,Helvetica,sans-serif;font-size:10pt;color:#212529;background:#fff}
.page{max-width:210mm;margin:0 auto;padding:14mm 18mm}
.page-break{page-break-before:always;padding-top:14mm}
table{width:100%;border-collapse:collapse;margin-bottom:.5rem}
th,td{padding:4px 7px;border:1px solid #dee2e6;font-size:9.5pt;vertical-align:middle}
.nb td,.nb th{border:none!important;padding:3px 5px}
thead th{background:#f0f3f8;font-weight:600;text-align:center}
h4{font-weight:700;font-size:12pt;margin:.4rem 0 .2rem}
h5{font-size:10.5pt;font-weight:700;margin:.5rem 0 .3rem}
p{margin:.25rem 0;line-height:1.5}
.row{display:flex;flex-wrap:wrap;margin:0 -8px}
.col-6{width:50%;padding:0 8px}
.col-4{width:33.33%;padding:0 8px}
.box{border:1px solid #aaa;padding:2px 10px;display:inline-block;min-width:150px;font-size:9pt;text-align:center}
hr{border:none;border-top:1px solid #bbb;margin:.7rem 0}
.tj{text-align:justify}
.tc{text-align:center}
.small{font-size:8.5pt;color:#444}
.italic{font-style:italic}
.bold{font-weight:700}
@media print{@page{size:A4;margin:14mm 18mm}body{font-size:9.5pt}.no-print{display:none!important}}
</style>';

        // ════════════════════════════════════════════════════
        // PAGE 1 — Cover
        // ════════════════════════════════════════════════════
        $page1 = '
<div class="page">
  <div class="row" style="margin-bottom:.8rem">
    <div class="col-6">
      <h4>Calibration Certificate</h4>
      <p class="italic small">Certificat d\'&eacute;talonnage</p>
      <p class="small" style="margin-top:4px;">issued by the calibration laboratory</p>
      <p class="small italic">d&eacute;livr&eacute; par le laboratoire d\'&eacute;talonnage</p>
    </div>
    <div class="col-6" style="text-align:right;">
      <div style="border:1px solid #ccc;padding:6px 12px;display:inline-block;font-size:8.5pt;text-align:center;">
        <strong>D-K-15209-01-00</strong><br>Accredited Calibration Laboratory
      </div>
    </div>
  </div>

  <div class="row" style="margin-bottom:.8rem">
    <div class="col-6">
      <h5>Ghana Standards Authority</h5>
      <p>P. O. Box MB 245, Accra, Ghana</p>
      <p><strong>TEL:</strong> +233-302-500065/6 &nbsp; <strong>Fax:</strong> +233-302-500092</p>
      <p><strong>E-Mail:</strong> scientificmetrology@gsa.gov.gh</p>
    </div>
    <div class="col-6" style="text-align:right;">
      <table class="nb" style="width:auto;margin-left:auto;">
        <tr><td class="nb" style="font-size:8.5pt;text-align:right;">Certificate number</td>
            <td class="nb"><span class="box"><strong>' . $e($certNum) . '</strong></span></td></tr>
        <tr><td class="nb" style="font-size:8.5pt;text-align:right;">Calibration mark</td>
            <td class="nb"><span class="box">D-K-15209-01-00</span></td></tr>
        <tr><td class="nb" style="font-size:8.5pt;text-align:right;">&nbsp;</td>
            <td class="nb"><span class="box">' . $e(date('Y-m', strtotime($issueDate))) . '</span></td></tr>
      </table>
    </div>
  </div>
  <hr>

  <div class="row" style="margin-bottom:.8rem">
    <div class="col-6">
      <table class="nb">
        <tr><th style="text-align:left;width:44%;font-size:9pt;">Object / <em>Objet</em></th>
            <td><strong>' . $e($r['equipment_name']) . '</strong></td></tr>
        <tr><th style="text-align:left;font-size:9pt;">Manufacturer / <em>Fabricant</em></th>
            <td><strong>' . $e($r['manufacturer']) . '</strong></td></tr>
        <tr><th style="text-align:left;font-size:9pt;">Type / <em>Type</em></th>
            <td><strong>' . $e($r['model']) . '</strong></td></tr>
        <tr><th style="text-align:left;font-size:9pt;">Serial number</th>
            <td><strong>' . $e($r['serial_number']) . '</strong></td></tr>
        <tr><th style="text-align:left;font-size:9pt;">Customer / <em>Client</em></th>
            <td><strong>' . $e($r['company_name']) . '</strong></td></tr>
        <tr><th style="text-align:left;font-size:9pt;">Order number</th>
            <td><strong>' . $e($r['request_number']) . '</strong></td></tr>
        <tr><th style="text-align:left;font-size:9pt;">Number of pages</th>
            <td><strong>2</strong></td></tr>
        <tr><th style="text-align:left;font-size:9pt;">Calibration date</th>
            <td><strong>' . $e($f['calibration_date'] ?? '') . '</strong></td></tr>
        <tr><th style="text-align:left;font-size:9pt;">Date of issue</th>
            <td><strong>' . $e($fmtD($f['date_of_issue'] ?? $issueDate)) . '</strong></td></tr>
        <tr><th style="text-align:left;font-size:9pt;">Due date</th>
            <td><strong>' . $e($fmtD($f['due_date'] ?? '')) . '</strong></td></tr>
      </table>
    </div>
    <div class="col-6" style="padding-left:16px;">
      <p class="small tj italic" style="margin-bottom:6px;">This calibration certificate documents the metrological traceability to national standards, which realize the units of measurement according to the International System of Units (SI).</p>
      <p class="small tj italic" style="margin-bottom:6px;">The DAkkS is signatory to the multilateral agreements of the European co-operation for Accreditation (EA) and of the International Laboratory Accreditation Cooperation (ILAC) for the mutual recognition of calibration certificates.</p>
      <p class="small tj italic">The user is obliged to have the object recalibrated at appropriate intervals.</p>
      <hr>
      <p class="small tj italic">Ce certificat d\'&eacute;talonnage documente la tra&ccedil;abilit&eacute; m&eacute;trologique des grandeurs mesur&eacute;es par raccordement aux &eacute;talons nationaux en conformit&eacute; avec le SI.</p>
    </div>
  </div>

  <div style="margin-bottom:.8rem">
    <p class="small tj">This calibration certificate may not be reproduced other than in full except with the permission of the issuing laboratory.</p>
    <p class="small tj italic">Ce certificat d\'&eacute;talonnage ne peut &ecirc;tre reproduit que dans son int&eacute;gralit&eacute;.</p>
  </div>
  <hr>

  <div class="row" style="margin-top:10px;">
    <div class="col-6">
      <p class="small">Date of issue / <em>Date</em></p>
      <p><strong>' . $e($issueDate) . '</strong></p>
    </div>
    <div class="col-6">
      <p class="small">Approved by / <em>Approuv&eacute; par</em></p>
      <div style="margin-top:8px;">' . $sig . '</div>
      <p style="border-top:1px solid #000;padding-top:4px;font-size:9pt;margin-top:4px;">
        <strong>' . $e($f['checked_by'] ?? $officer['officer_name']) . '</strong><br>
        <span style="font-size:8.5pt;color:#555;">Laboratory Officer &mdash; Temperature &amp; Humidity Laboratory</span>
      </p>
    </div>
  </div>
</div>';

        // ════════════════════════════════════════════════════
        // PAGE 2 — Results
        // ════════════════════════════════════════════════════
        $page2 = '
<div class="page page-break">
  <!-- Repeat header -->
  <div class="row" style="margin-bottom:.8rem">
    <div class="col-6">
      <span style="font-size:8.5pt;">Page</span> <span class="box">2</span>
    </div>
    <div class="col-6" style="text-align:right;">
      <table class="nb" style="width:auto;margin-left:auto;">
        <tr><td class="nb"><span class="box"><strong>' . $e($certNum) . '</strong></span></td></tr>
        <tr><td class="nb"><span class="box">D-K-15209-01-00</span></td></tr>
        <tr><td class="nb"><span class="box">' . $e(date('Y-m', strtotime($issueDate))) . '</span></td></tr>
      </table>
    </div>
  </div>

  <h5>Calibration Procedure</h5>
  <p class="small">' . $e($f['procedure'] ?? 'DKD-R 5-8:2019 (Humidity) / DKD R-5-1:2018 (Temperature)') . '</p>
  <p class="small"><strong>Place of test:</strong> ' . $e($f['place_of_test'] ?? '') . '</p>
  <hr>

  <!-- RH Results -->
  <h5>Relative Humidity Measurement Results</h5>
  <table style="margin-top:6px;">
    <thead>
      <tr>
        <th>Setpoint</th>
        <th>Ref Temp (°C)</th>
        <th>Ref RH (%RH)</th>
        <th>EUT RH (%RH)</th>
        <th>Deviation (%RH)</th>
        <th>Expanded Uncertainty U (%RH)</th>
      </tr>
    </thead>
    <tbody>' . $rh_rows . '</tbody>
  </table>

  <!-- Temperature Results -->
  <h5 style="margin-top:12px;">Temperature Measurement Results <span style="font-size:8.5pt;font-weight:normal;color:#555;">(at ~50 %RH setpoints only)</span></h5>
  <table style="margin-top:6px;">
    <thead>
      <tr>
        <th>Setpoint</th>
        <th>Ref Temp (°C)</th>
        <th>EUT Temp (°C)</th>
        <th>Deviation (°C)</th>
        <th>Expanded Uncertainty U (K)</th>
      </tr>
    </thead>
    <tbody>' . $temp_rows . '</tbody>
  </table>

  <!-- Uncertainty Statement -->
  <div style="margin-top:14px;">
    <h5>Uncertainty of Measurement</h5>
    <p class="small tj bold">The uncertainty stated is the expanded uncertainty obtained by multiplying the standard uncertainty by the coverage factor k = 2. It has been determined in accordance with DKD-R 5-8:2019 and EA-4/02 M:2022. The value of the measurand lies within the assigned range with a probability of approximately 95%.</p>
    <p class="small tj" style="margin-top:6px;">Uncertainty contributions include: reference standards, chamber spatial inhomogeneity, temporal instability, radiation influence, EUT resolution, repeatability, and self-heating effects.</p>
  </div>

  <!-- Additional Info -->
  <div style="margin-top:10px;">
    <h5>Additional Information</h5>
    <p class="small italic tj">The results of calibration are valid at the time of calibration.</p>
    <p class="small italic tj">This certificate complies with ISO/IEC 17025 requirements.</p>
    <p class="small italic tj">Issued by the GSA Temperature and Humidity Laboratory.</p>
    <p class="small bold" style="margin-top:6px;">End of calibration certificate.</p>
  </div>
  <hr>
  <p class="tc small" style="margin-top:8px;color:#666;">
    Ghana Standards Authority &mdash; Temperature &amp; Humidity Laboratory &bull;
    Cert. No. ' . $e($certNum) . ' &bull; Issued: ' . $e($issueDate) . '
  </p>
</div>';

        return '<!DOCTYPE html><html lang="en"><head>'
             . '<meta charset="UTF-8">'
             . '<title>Calibration Certificate ' . $e($certNum) . '</title>'
             . $css
             . '</head><body>'
             . $page1 . $page2
             . '</body></html>';
    }

    // ── DCC XML (mirrors save_to_xml Python function) ─────────
    public function generateXML(
        array $request,
        array $formData,
        array $officer,
        string $certNum,
        string $issueDate
    ): string {
        $f       = $formData;
        $r       = $request;
        $e       = fn($v) => htmlspecialchars(trim((string)($v ?? '')), ENT_XML1, 'UTF-8');
        $results = HumidityLabForm::buildResults($f);

        $resultXml = '';
        foreach ($results as $idx => $res) {
            $n = $idx + 1;
            $resultXml .= '
        <dcc:result refType="humidity_setpoint_' . $n . '">
          <dcc:name><dcc:content lang="en">Setpoint ' . $e($res['setpoint']) . '</dcc:content></dcc:name>
          <dcc:data>
            <dcc:quantity refType="basic_refTemperature">
              <dcc:name><dcc:content lang="en">Reference Temperature</dcc:content></dcc:name>
              <si:real><si:value>' . $e($res['corrected_ref_temp']) . '</si:value><si:unit>\degC</si:unit></si:real>
            </dcc:quantity>
            <dcc:quantity refType="basic_refHumidity">
              <dcc:name><dcc:content lang="en">Reference Relative Humidity</dcc:content></dcc:name>
              <si:real><si:value>' . $e($res['corrected_ref_rh']) . '</si:value><si:unit>%</si:unit></si:real>
            </dcc:quantity>
            <dcc:quantity refType="basic_eutHumidity">
              <dcc:name><dcc:content lang="en">EUT Mean Relative Humidity</dcc:content></dcc:name>
              <si:real><si:value>' . $e($res['avg_eut_rh']) . '</si:value><si:unit>%</si:unit></si:real>
            </dcc:quantity>
            <dcc:quantity refType="basic_rhDeviation">
              <dcc:name><dcc:content lang="en">RH Deviation</dcc:content></dcc:name>
              <si:real><si:value>' . $e($res['rh_deviation']) . '</si:value><si:unit>%</si:unit></si:real>
            </dcc:quantity>
            <dcc:quantity refType="basic_rhExpandedUncertainty">
              <dcc:name><dcc:content lang="en">Expanded Uncertainty U (k=2, ~95%)</dcc:content></dcc:name>
              <si:real><si:value>' . $e($res['rh_uncertainty']) . '</si:value><si:unit>%</si:unit></si:real>
            </dcc:quantity>'
            . ($res['include_temp'] ? '
            <dcc:quantity refType="basic_eutTemperature">
              <dcc:name><dcc:content lang="en">EUT Mean Temperature</dcc:content></dcc:name>
              <si:real><si:value>' . $e($res['avg_eut_temp']) . '</si:value><si:unit>\degC</si:unit></si:real>
            </dcc:quantity>
            <dcc:quantity refType="basic_tempDeviation">
              <dcc:name><dcc:content lang="en">Temperature Deviation</dcc:content></dcc:name>
              <si:real><si:value>' . $e($res['temp_deviation']) . '</si:value><si:unit>\degC</si:unit></si:real>
            </dcc:quantity>
            <dcc:quantity refType="basic_tempExpandedUncertainty">
              <dcc:name><dcc:content lang="en">Expanded Uncertainty U (k=2, ~95%)</dcc:content></dcc:name>
              <si:real><si:value>' . $e($res['temp_uncertainty']) . '</si:value><si:unit>K</si:unit></si:real>
            </dcc:quantity>' : '') . '
          </dcc:data>
        </dcc:result>';
        }

        return '<?xml version="1.0" encoding="UTF-8"?>
<dcc:digitalCalibrationCertificate
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:dcc="https://ptb.de/dcc"
  xmlns:si="https://ptb.de/si"
  xsi:schemaLocation="https://ptb.de/dcc https://ptb.de/dcc/v3.2.1/dcc.xsd"
  schemaVersion="3.2.1">

  <dcc:administrativeData>
    <dcc:dccSoftware>
      <dcc:software>
        <dcc:name>MetLAB — Ghana Standards Authority</dcc:name>
        <dcc:release>v1.0</dcc:release>
      </dcc:software>
    </dcc:dccSoftware>

    <dcc:coreData>
      <dcc:countryCodeISO3166_1>GH</dcc:countryCodeISO3166_1>
      <dcc:usedLangCodeISO639_1>en</dcc:usedLangCodeISO639_1>
      <dcc:mandatoryLangCodeISO639_1>en</dcc:mandatoryLangCodeISO639_1>
      <dcc:uniqueIdentifier>' . $e($certNum) . '</dcc:uniqueIdentifier>
      <dcc:identifications>
        <dcc:identification>
          <dcc:issuer>calibrationLaboratory</dcc:issuer>
          <dcc:value>' . $e($f['certificate_number'] ?? $certNum) . '</dcc:value>
          <dcc:name><dcc:content lang="en">Certificate No.</dcc:content></dcc:name>
        </dcc:identification>
        <dcc:identification>
          <dcc:issuer>calibrationLaboratory</dcc:issuer>
          <dcc:value>' . $e($r['request_number']) . '</dcc:value>
          <dcc:name><dcc:content lang="en">Order No.</dcc:content></dcc:name>
        </dcc:identification>
      </dcc:identifications>
      <dcc:receiptDate>' . $e($r['request_date']) . '</dcc:receiptDate>
      <dcc:beginPerformanceDate>' . $e($f['calibration_date'] ?? $r['request_date']) . '</dcc:beginPerformanceDate>
      <dcc:endPerformanceDate>' . $e($issueDate) . '</dcc:endPerformanceDate>
      <dcc:performanceLocation>laboratory</dcc:performanceLocation>
    </dcc:coreData>

    <dcc:items>
      <dcc:item>
        <dcc:name><dcc:content lang="en">' . $e($r['equipment_name']) . '</dcc:content></dcc:name>
        <dcc:manufacturer><dcc:name>' . $e($r['manufacturer']) . '</dcc:name></dcc:manufacturer>
        <dcc:model>' . $e($r['model']) . '</dcc:model>
        <dcc:identifications>
          <dcc:identification>
            <dcc:value>' . $e($r['serial_number']) . '</dcc:value>
            <dcc:name><dcc:content lang="en">Serial No.</dcc:content></dcc:name>
          </dcc:identification>
          <dcc:identification>
            <dcc:issuer>client</dcc:issuer>
            <dcc:value>' . $e($r['company_name']) . '</dcc:value>
            <dcc:name><dcc:content lang="en">Customer</dcc:content></dcc:name>
          </dcc:identification>
        </dcc:identifications>
      </dcc:item>
    </dcc:items>

    <dcc:calibrationLaboratory>
      <dcc:calibrationLaboratoryCode>THL</dcc:calibrationLaboratoryCode>
      <dcc:contact>
        <dcc:name>Ghana Standards Authority — Temperature and Humidity Laboratory</dcc:name>
        <dcc:eMail>scientificmetrology@gsa.gov.gh</dcc:eMail>
        <dcc:phone>+233-302-500065</dcc:phone>
        <dcc:location>
          <dcc:city>Accra</dcc:city>
          <dcc:countryCode>GH</dcc:countryCode>
          <dcc:postCode>P.O. Box MB 245</dcc:postCode>
        </dcc:location>
      </dcc:contact>
    </dcc:calibrationLaboratory>

    <dcc:respPersons>
      <dcc:respPerson>
        <dcc:person><dcc:name>' . $e($officer['officer_name']) . '</dcc:name></dcc:person>
        <dcc:mainSigner>true</dcc:mainSigner>
      </dcc:respPerson>
    </dcc:respPersons>

    <dcc:statements>
      <dcc:statement>
        <dcc:declaration>
          <dcc:content lang="en">Calibration procedure: ' . $e($f['procedure'] ?? 'DKD-R 5-8:2019 / DKD R-5-1:2018') . '</dcc:content>
        </dcc:declaration>
      </dcc:statement>
    </dcc:statements>
  </dcc:administrativeData>

  <dcc:measurementResults>
    <dcc:measurementResult>
      <dcc:name><dcc:content lang="en">Thermohygrometer Calibration Results</dcc:content></dcc:name>
      <dcc:usedMethods>
        <dcc:usedMethod>
          <dcc:name><dcc:content lang="en">Humidity Calibration</dcc:content></dcc:name>
          <dcc:norm>DKD-R 5-8:2019</dcc:norm>
        </dcc:usedMethod>
        <dcc:usedMethod>
          <dcc:name><dcc:content lang="en">Temperature Calibration</dcc:content></dcc:name>
          <dcc:norm>DKD R-5-1:2018</dcc:norm>
        </dcc:usedMethod>
        <dcc:usedMethod>
          <dcc:name><dcc:content lang="en">Uncertainty Evaluation</dcc:content></dcc:name>
          <dcc:norm>EA-4/02 M:2022</dcc:norm>
        </dcc:usedMethod>
      </dcc:usedMethods>
      <dcc:results>' . $resultXml . '
      </dcc:results>
    </dcc:measurementResult>
  </dcc:measurementResults>

</dcc:digitalCalibrationCertificate>';
    }
}
