<?php
// ============================================================
// BalanceLabCertificate  — implements ILabCertificate
//
// All read-only fields (item_calibrated, manufacturer, serial,
// customer, laboratory_number/type) are pulled from $request
// which carries the joined equipment/companies/requests data.
// Only balance-specific calibration data comes from $formData.
// ============================================================
class BalanceLabCertificate 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">';
            }
        }
        // Empty signature line if no image
        return '<div style="height:55px;border-bottom:1px solid #000;width:220px;"></div>';
    }

    // ── HTML Certificate (3 pages) ───────────────────────────
    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);

        // Date formatters
        $fmtDate = fn($v) => $v ? date('d M Y', strtotime($v)) : '';
        $fmtYM   = fn($v) => $v ? date('Y-m', strtotime($v)) : date('Y-m');

        // Checkbox renderer: tick if value matches
        $chk = fn(string $field, string $val) =>
            ($f[$field] ?? '') === $val ? '&#10003;' : '&nbsp;';

        // Pull source-of-truth fields from $request (not $formData)
        $itemCalibrated  = $r['equipment_name']   ?? '';
        $manufacturer    = $r['manufacturer']     ?? '';
        $typeModel       = $r['model']            ?? '';
        $serialNumber    = $r['serial_number']    ?? '';
        $customerDetails = $r['company_name']     ?? '';
        $labOrderNumber  = $r['request_number']   ?? '';

        $css = '
<style>
  *{box-sizing:border-box;margin:0;padding:0}
  body{font-family:Arial,"Helvetica Neue",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:.4rem}
  th,td{padding:4px 6px;border:1px solid #dee2e6;font-size:9.5pt;vertical-align:middle}
  .no-border td,.no-border th{border:none!important;padding:3px 5px}
  thead th{background:#f0f0f0;font-weight:600}
  h4{font-weight:700;margin:.5rem 0 .2rem}
  h5{font-size:10.5pt;font-weight:700;margin:.6rem 0 .3rem}
  p{margin:.25rem 0;line-height:1.5}
  .row{display:flex;flex-wrap:wrap;margin:0 -6px}
  .col-6{width:50%;padding:0 6px}
  .col-4{width:33.33%;padding:0 6px}
  .col-8{width:66.66%;padding:0 6px}
  .mb-2{margin-bottom:.5rem}
  .mb-3{margin-bottom:.8rem}
  .mt-3{margin-top:.8rem}
  hr{border:none;border-top:1px solid #bbb;margin:.7rem 0}
  .box{border:1px solid #aaa;padding:2px 8px;display:inline-block;min-width:140px;font-size:9pt;text-align:center}
  .box-label{font-size:8.5pt;color:#666;display:block}
  .text-right{text-align:right}
  .text-center{text-align:center}
  .text-justify{text-align:justify}
  .italic{font-style:italic}
  .small{font-size:8.5pt;color:#555}
  @media print{
    @page{size:A4;margin:14mm 18mm}
    body{font-size:9.5pt}
    .no-print{display:none!important}
  }
</style>';

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

  <div class="row mb-3">
    <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 text-right">
      <table class="no-border" style="width:auto;margin-left:auto;">
        <tr>
          <td class="no-border" style="text-align:right;font-size:8.5pt;">Certificate number<br><em>Num&eacute;ro du certificat</em></td>
          <td class="no-border"><span class="box"><strong>' . $e($certNum) . '</strong></span></td>
        </tr>
        <tr>
          <td class="no-border" style="text-align:right;font-size:8.5pt;">Calibration mark<br><em>Marque d\'&eacute;talonnage</em></td>
          <td class="no-border"><span class="box">D-K-15209-01-00</span></td>
        </tr>
        <tr>
          <td class="no-border" style="text-align:right;font-size:8.5pt;">&nbsp;</td>
          <td class="no-border"><span class="box">' . $e($fmtYM($f['date_checked'] ?? $issueDate)) . '</span></td>
        </tr>
      </table>
    </div>
  </div>
  <hr>

  <div class="row mb-3">
    <div class="col-6">
      <table class="no-border">
        <tr><th style="width:44%;text-align:left;font-weight:600;font-size:9pt;">Object / <em>Objet</em></th>
            <td><strong>' . $e($itemCalibrated) . '</strong></td></tr>
        <tr><th style="text-align:left;font-weight:600;font-size:9pt;">Manufacturer / <em>Fabricant</em></th>
            <td><strong>' . $e($manufacturer) . '</strong></td></tr>
        <tr><th style="text-align:left;font-weight:600;font-size:9pt;">Type / <em>Type</em></th>
            <td><strong>' . $e($typeModel) . '</strong></td></tr>
        <tr><th style="text-align:left;font-weight:600;font-size:9pt;">Serial number / <em>Num&eacute;ro de s&eacute;rie</em></th>
            <td><strong>' . $e($serialNumber) . '</strong></td></tr>
        <tr><th style="text-align:left;font-weight:600;font-size:9pt;">Customer / <em>Client</em></th>
            <td><strong>' . $e($customerDetails) . '</strong></td></tr>
        <tr><th style="text-align:left;font-weight:600;font-size:9pt;">Order number / <em>Num&eacute;ro de commande</em></th>
            <td><strong>' . $e($labOrderNumber) . '</strong></td></tr>
        <tr><th style="text-align:left;font-weight:600;font-size:9pt;">Number of pages / <em>Nombre de pages</em></th>
            <td><strong>3</strong></td></tr>
        <tr><th style="text-align:left;font-weight:600;font-size:9pt;">Date of calibration / <em>Date d\'&eacute;talonnage</em></th>
            <td><strong>' . $e($fmtDate($f['calibration_date'])) . '</strong></td></tr>
        <tr><th style="text-align:left;font-weight:600;font-size:9pt;">Due date</th>
            <td><strong>' . $e($fmtDate($f['due_date'] ?? '')) . '</strong></td></tr>
      </table>
    </div>
    <div class="col-6" style="padding-left:16px;">
      <p class="text-justify mb-2 small italic">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="text-justify mb-2 small italic">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="text-justify mb-2 small italic">The user is obliged to have the object recalibrated at appropriate intervals.</p>
      <hr>
      <p class="text-justify small 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 Syst&egrave;me international d\'unit&eacute;s (SI).</p>
      <p class="text-justify small italic">L\'utilisateur est tenu de faire &eacute;talonner le mat&eacute;riel r&eacute;f&eacute;renc&eacute; ci-dessus &agrave; des intervalles appropri&eacute;s.</p>
    </div>
  </div>

  <div class="mb-3">
    <p class="text-justify small">This calibration certificate may not be reproduced other than in full except with the permission of the issuing laboratory. Calibration certificates with the full name of the approval responsible person are valid without signature.</p>
    <p class="text-justify small italic">Ce certificat d\'&eacute;talonnage ne peut &ecirc;tre reproduit que dans son int&eacute;gralit&eacute;, sauf avec l\'autorisation du laboratoire &eacute;metteur.</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">Approval of the certificate by / <em>Approbation du certificat par</em></p>
      <div style="margin-top:6px;">' . $sig . '</div>
      <p style="margin-top:5px;border-top:1px solid #000;padding-top:4px;font-size:9pt;">
        <strong>' . $e($f['checked_by'] ?? $officer['officer_name']) . '</strong>
      </p>
    </div>
  </div>
</div>';

        // ════════════════════════════════════════════════════
        // PAGE 2 — Technical details & conditions
        // ════════════════════════════════════════════════════
        $page2 = '
<div class="page page-break">
  <!-- Page header repeats cert number -->
  <div class="row mb-3">
    <div class="col-6">
      <table class="no-border" style="width:auto;">
        <tr><td class="no-border box-label">Page</td><td class="no-border"><span class="box">2</span></td></tr>
      </table>
    </div>
    <div class="col-6 text-right">
      <table class="no-border" style="width:auto;margin-left:auto;">
        <tr><td class="no-border"><span class="box"><strong>' . $e($certNum) . '</strong></span></td></tr>
        <tr><td class="no-border"><span class="box">D-K-15209-01-00</span></td></tr>
        <tr><td class="no-border"><span class="box">' . $e($fmtYM($f['date_checked'] ?? $issueDate)) . '</span></td></tr>
      </table>
    </div>
  </div>

  <p class="text-justify mb-3 small italic">The French version of the calibration certificate is not a binding translation. If any matter gives rise to controversy, the English original text must be used.</p>

  <div class="mb-3">
    <h5>Calibration object &nbsp; <strong>' . $e($itemCalibrated) . '</strong></h5>
    <table style="width:auto;" class="no-border">
      <tr>
        <td class="no-border" style="min-width:200px">
          <p>Type: <strong>' . $e($typeModel) . '</strong></p>
          <p>Serial No.: <strong>' . $e($serialNumber) . '</strong></p>
          <p>Accuracy Class: <strong>II</strong></p>
        </td>
        <td class="no-border" style="min-width:220px">
          <p>Max. Capacity: <strong>' . $e($f['max_capacity'] ?? '') . ' ' . $e($f['unit'] ?? '') . '</strong></p>
          <p>Scale Division (d): <strong>5 ' . $e($f['unitsec'] ?? '') . '</strong></p>
          <p>Min. Capacity: <strong>' . $e($f['min_capacity'] ?? '') . ' ' . $e($f['unitsec'] ?? '') . '</strong></p>
        </td>
      </tr>
    </table>
  </div>
  <hr>

  <div class="mb-3">
    <h5>Calibration procedure</h5>
    <p>The calibration was done according to guideline <strong>EURAMET/cg-18</strong>.</p>
    <p class="mt-3">The calibration comprised:</p>
    <ul style="margin-left:20px;margin-top:4px;font-size:9.5pt;">
      <li>Repeatability</li>
      <li>Test of errors of indication</li>
      <li>Eccentricity test</li>
    </ul>
  </div>
  <hr>

  <div class="mb-3">
    <h5>Standards used</h5>
    <p>Set of weights of class <strong>F1</strong> &nbsp; Serial Nos.: <strong>14K57</strong> and <strong>ABT</strong></p>
    <p>Calibration: <strong>ML-0186/D-K-15209-01-00/24-11</strong> and <strong>ML-0189/D-K-15209-01-00/24-11</strong></p>
  </div>
  <hr>

  <div class="mb-3">
    <h5>Measuring conditions</h5>
    <table class="no-border" style="width:auto;">
      <tr><th style="text-align:left;font-weight:600;">Place of test / <em>Lieu des essais</em></th>
          <td style="padding-left:16px;"><strong>' . $e($f['place_of_test'] ?? '') . '</strong></td></tr>
    </table>

    <p class="mt-3"><strong>Environmental conditions</strong></p>
    <p>Temperature during calibration &mdash;
       Start: <strong>' . $e($f['temp_during_cal_start'] ?? '') . '&nbsp;&deg;C</strong>
       &nbsp;&nbsp;&nbsp; End: <strong>' . $e($f['temp_during_cal_end'] ?? '') . '&nbsp;&deg;C</strong>
    </p>
    <p>
      High air circulation: &nbsp;
      Yes&nbsp;[' . $chk('high_air_circulation', 'Yes') . '] &nbsp;
      No&nbsp;[' . $chk('high_air_circulation', 'No') . ']
    </p>
    <p>
      High vibration: &nbsp;
      Yes&nbsp;[' . $chk('high_vibration', 'Yes') . '] &nbsp;
      No&nbsp;[' . $chk('high_vibration', 'No') . ']
    </p>
  </div>
</div>';

        // ════════════════════════════════════════════════════
        // PAGE 3 — Measuring results
        // ════════════════════════════════════════════════════

        // Build repeatability row
        $repCells = '';
        for ($i = 1; $i <= 5; $i++) {
            $repCells .= '<td style="text-align:center;">' . $e($f["repeatability{$i}"] ?? '') . '</td>';
        }

        // Build error-of-indication rows
        $errRows = '';
        $points = [
            ['0',   '0 / min'],
            ['25',  '25'],
            ['50',  '50'],
            ['75',  '75'],
            ['100', '100'],
        ];
        foreach ($points as $idx => [$pct, $label]) {
            $col = $idx + 1;
            $errRows .= '
            <tr>
              <td style="text-align:center;">' . $label . '</td>
              <td style="text-align:center;">' . $e($f["nominal_value_{$pct}"] ?? '') . '</td>
              <td style="text-align:center;">' . $e($f["indication_{$pct}"] ?? '') . '</td>
              <td style="text-align:center;">' . $e($f["deviation_of_indication_{$pct}"] ?? '') . '</td>
              <td style="text-align:center;">' . $e($f["K_value_{$col}"] ?? '') . '</td>
              <td style="text-align:center;">' . $e($f["U_value_{$col}"] ?? '') . '</td>
            </tr>';
        }

        // Build eccentricity rows
        $eccDef = [
            ['CENTRE',      'EC_Indication1_Centre', 'EC_Deviation_Centre'],
            ['FRONT LEFT',  'EC_Indication_FL',      'EC_Deviation_FL'],
            ['BACK LEFT',   'EC_Indication_BL',      'EC_Deviation_BL'],
            ['BACK RIGHT',  'EC_Indication_BR',      'EC_Deviation_BR'],
            ['FRONT RIGHT', 'EC_Indication_FR',      'EC_Deviation_FR'],
        ];
        $eccRows = '';
        foreach ($eccDef as [$pos, $indKey, $devKey]) {
            $eccRows .= '
            <tr>
              <td>' . $pos . '</td>
              <td style="text-align:center;">' . $e($f[$indKey] ?? '') . '</td>
              <td style="text-align:center;">' . $e($f[$devKey] ?? '') . '</td>
            </tr>';
        }

        $unit = $e($f['unitsec'] ?? 'g');

        $page3 = '
<div class="page page-break">
  <!-- Page header -->
  <div class="row mb-3">
    <div class="col-6">
      <table class="no-border" style="width:auto;">
        <tr><td class="no-border box-label">Page</td><td class="no-border"><span class="box">3</span></td></tr>
      </table>
    </div>
    <div class="col-6 text-right">
      <table class="no-border" style="width:auto;margin-left:auto;">
        <tr><td class="no-border"><span class="box"><strong>' . $e($certNum) . '</strong></span></td></tr>
        <tr><td class="no-border"><span class="box">D-K-15209-01-00</span></td></tr>
        <tr><td class="no-border"><span class="box">' . $e($fmtYM($f['date_checked'] ?? $issueDate)) . '</span></td></tr>
      </table>
    </div>
  </div>

  <h5 class="mb-2">Measuring Results</h5>

  <!-- A. Repeatability -->
  <div class="mb-3">
    <h5>A. REPEATABILITY TEST</h5>
    <p>Applied Load (L): <strong>' . $e($f['applied_load_rt'] ?? '') . ' ' . $unit . '</strong>
       &nbsp;&nbsp;&nbsp; Standard deviation: <strong>' . $e($f['standard_deviation'] ?? '') . ' ' . $unit . '</strong></p>
    <table style="margin-top:6px;">
      <thead>
        <tr>
          <th>No.</th><th>1</th><th>2</th><th>3</th><th>4</th><th>5</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Indication / ' . $unit . '</td>
          ' . $repCells . '
        </tr>
      </tbody>
    </table>
  </div>

  <!-- B. Test of Errors of Indication -->
  <div class="mb-3">
    <h5>B. TEST OF ERRORS OF INDICATION</h5>
    <table>
      <thead>
        <tr>
          <th>Applied Load / %</th>
          <th>Nominal Mass / ' . $unit . '</th>
          <th>Mean Scale Reading / ' . $unit . '</th>
          <th>Mean Deviation / ' . $unit . '</th>
          <th>Coverage Factor (k)</th>
          <th>Expanded Uncertainty / ' . $unit . '</th>
        </tr>
      </thead>
      <tbody>' . $errRows . '</tbody>
    </table>
  </div>

  <!-- C. Eccentricity Test -->
  <div class="mb-3">
    <h5>C. ECCENTRICITY TEST</h5>
    <p>Applied Load (L): <strong>' . $e($f['applied_load_et'] ?? '') . ' ' . $unit . '</strong></p>
    <table style="margin-top:6px;">
      <thead>
        <tr>
          <th>Load Position</th>
          <th>Scale Reading / ' . $unit . '</th>
          <th>Deviation referring to centre / ' . $unit . '</th>
        </tr>
      </thead>
      <tbody>' . $eccRows . '</tbody>
    </table>
  </div>

  <!-- Uncertainty Statement -->
  <div class="mb-3">
    <h5>Uncertainty of measurement</h5>
    <p class="text-justify small"><strong>The uncertainty stated is the expanded uncertainty obtained by multiplying the standard uncertainty by the calculated coverage factor k. It has been determined in accordance with EA-4/02 M:2022. The value of the measured quantity lies within the assigned range of values with a probability of approximately 95%.</strong></p>
    <p class="text-justify small" style="margin-top:6px;">The expanded uncertainty was calculated from the contributions of uncertainty originating from standards used, from the weighing and the air buoyancy corrections.</p>
  </div>

  <!-- Additional info -->
  <div class="mb-3">
    <h5>Additional information:</h5>
    <p class="text-justify small italic">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="text-justify small italic" style="margin-top:4px;">A calibration mark is affixed at the calibration object.</p>
    <p class="text-justify small italic" style="margin-top:4px;">The results of calibration are valid at the time of calibration.</p>
    <p class="text-justify small italic" style="margin-top:4px;"><strong>End of calibration certificate.</strong></p>
  </div>
  <hr>

  <!-- Footer -->
  <p class="text-center small" style="margin-top:8px;color:#666;">
    Ghana Standards Authority &mdash; Mass and Related Quantities 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 . $page3
            . '</body></html>';
    }

    // ── DCC XML ─────────────────────────────────────────────
    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');

        // Error-of-indication results
        $errResults = '';
        $points = [
            ['0',   '0_min'],
            ['25',  '25pct'],
            ['50',  '50pct'],
            ['75',  '75pct'],
            ['100', '100pct'],
        ];
        foreach ($points as $idx => [$pct, $refKey]) {
            $col = $idx + 1;
            $errResults .= '
        <dcc:result refType="balance_error_' . $refKey . '">
          <dcc:name><dcc:content lang="en">Load Point ' . $pct . '%</dcc:content></dcc:name>
          <dcc:data>
            <dcc:quantity refType="basic_nominalValue">
              <dcc:name><dcc:content lang="en">Nominal Mass</dcc:content></dcc:name>
              <si:real><si:value>' . $e($f["nominal_value_{$pct}"]) . '</si:value>
              <si:unit>' . $e($f['unitsec'] ?? 'g') . '</si:unit></si:real>
            </dcc:quantity>
            <dcc:quantity refType="basic_indication">
              <dcc:name><dcc:content lang="en">Mean Scale Reading</dcc:content></dcc:name>
              <si:real><si:value>' . $e($f["indication_{$pct}"]) . '</si:value>
              <si:unit>' . $e($f['unitsec'] ?? 'g') . '</si:unit></si:real>
            </dcc:quantity>
            <dcc:quantity refType="basic_deviation">
              <dcc:name><dcc:content lang="en">Mean Deviation</dcc:content></dcc:name>
              <si:real><si:value>' . $e($f["deviation_of_indication_{$pct}"]) . '</si:value>
              <si:unit>' . $e($f['unitsec'] ?? 'g') . '</si:unit></si:real>
            </dcc:quantity>
            <dcc:quantity refType="basic_coverageFactor">
              <dcc:name><dcc:content lang="en">Coverage Factor k</dcc:content></dcc:name>
              <si:real><si:value>' . $e($f["K_value_{$col}"]) . '</si:value></si:real>
            </dcc:quantity>
            <dcc:quantity refType="basic_expandedUncertainty">
              <dcc:name><dcc:content lang="en">Expanded Uncertainty U</dcc:content></dcc:name>
              <si:real><si:value>' . $e($f["U_value_{$col}"]) . '</si:value>
              <si:unit>' . $e($f['unitsec'] ?? 'g') . '</si:unit></si:real>
            </dcc:quantity>
          </dcc:data>
        </dcc:result>';
        }

        // Repeatability readings
        $repData = '';
        for ($i = 1; $i <= 5; $i++) {
            $repData .= '
            <dcc:quantity refType="repeatability_reading_' . $i . '">
              <dcc:name><dcc:content lang="en">Reading ' . $i . '</dcc:content></dcc:name>
              <si:real><si:value>' . $e($f["repeatability{$i}"]) . '</si:value>
              <si:unit>' . $e($f['unitsec'] ?? 'g') . '</si:unit></si:real>
            </dcc:quantity>';
        }

        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['certification_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">Laboratory / 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>MRQL</dcc:calibrationLaboratoryCode>
      <dcc:contact>
        <dcc:name>Ghana Standards Authority — Mass and Related Quantities 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">This calibration certificate documents the metrological traceability to national standards in accordance with the SI.</dcc:content>
        </dcc:declaration>
      </dcc:statement>
    </dcc:statements>
  </dcc:administrativeData>

  <dcc:measurementResults>
    <dcc:measurementResult>
      <dcc:name><dcc:content lang="en">Balance Calibration — EURAMET/cg-18</dcc:content></dcc:name>

      <dcc:usedMethods>
        <dcc:usedMethod>
          <dcc:name><dcc:content lang="en">Calibration Guideline</dcc:content></dcc:name>
          <dcc:norm>EURAMET/cg-18</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:influenceConditions>
        <dcc:influenceCondition refType="basic_environmentalConditions">
          <dcc:name><dcc:content lang="en">Environmental Conditions</dcc:content></dcc:name>
          <dcc:description>
            <dcc:content lang="en">Place: ' . $e($f['place_of_test'] ?? '') . '</dcc:content>
          </dcc:description>
          <dcc:data>
            <dcc:quantity refType="basic_temperatureStart">
              <dcc:name><dcc:content lang="en">Temperature at Start</dcc:content></dcc:name>
              <si:real><si:value>' . $e($f['temp_during_cal_start'] ?? '') . '</si:value>
              <si:unit>\degC</si:unit></si:real>
            </dcc:quantity>
            <dcc:quantity refType="basic_temperatureEnd">
              <dcc:name><dcc:content lang="en">Temperature at End</dcc:content></dcc:name>
              <si:real><si:value>' . $e($f['temp_during_cal_end'] ?? '') . '</si:value>
              <si:unit>\degC</si:unit></si:real>
            </dcc:quantity>
          </dcc:data>
        </dcc:influenceCondition>
      </dcc:influenceConditions>

      <dcc:results>

        <dcc:result refType="balance_repeatability">
          <dcc:name><dcc:content lang="en">A. Repeatability Test</dcc:content></dcc:name>
          <dcc:data>
            ' . $repData . '
            <dcc:quantity refType="basic_standardDeviation">
              <dcc:name><dcc:content lang="en">Standard Deviation</dcc:content></dcc:name>
              <si:real><si:value>' . $e($f['standard_deviation'] ?? '') . '</si:value>
              <si:unit>' . $e($f['unitsec'] ?? 'g') . '</si:unit></si:real>
            </dcc:quantity>
          </dcc:data>
        </dcc:result>

        ' . $errResults . '

        <dcc:result refType="balance_eccentricity">
          <dcc:name><dcc:content lang="en">C. Eccentricity Test</dcc:content></dcc:name>
          <dcc:data>
            <dcc:quantity refType="eccentricity_centre">
              <dcc:name><dcc:content lang="en">Centre</dcc:content></dcc:name>
              <si:real><si:value>' . $e($f['EC_Indication1_Centre'] ?? '') . '</si:value></si:real>
            </dcc:quantity>
            <dcc:quantity refType="eccentricity_frontLeft">
              <dcc:name><dcc:content lang="en">Front Left</dcc:content></dcc:name>
              <si:real><si:value>' . $e($f['EC_Indication_FL'] ?? '') . '</si:value></si:real>
            </dcc:quantity>
            <dcc:quantity refType="eccentricity_backLeft">
              <dcc:name><dcc:content lang="en">Back Left</dcc:content></dcc:name>
              <si:real><si:value>' . $e($f['EC_Indication_BL'] ?? '') . '</si:value></si:real>
            </dcc:quantity>
            <dcc:quantity refType="eccentricity_backRight">
              <dcc:name><dcc:content lang="en">Back Right</dcc:content></dcc:name>
              <si:real><si:value>' . $e($f['EC_Indication_BR'] ?? '') . '</si:value></si:real>
            </dcc:quantity>
            <dcc:quantity refType="eccentricity_frontRight">
              <dcc:name><dcc:content lang="en">Front Right</dcc:content></dcc:name>
              <si:real><si:value>' . $e($f['EC_Indication_FR'] ?? '') . '</si:value></si:real>
            </dcc:quantity>
            <dcc:quantity refType="eccentricity_maxDifference">
              <dcc:name><dcc:content lang="en">Max Difference</dcc:content></dcc:name>
              <si:real><si:value>' . $e($f['max_difference'] ?? '') . '</si:value></si:real>
            </dcc:quantity>
          </dcc:data>
        </dcc:result>

      </dcc:results>
    </dcc:measurementResult>
  </dcc:measurementResults>

</dcc:digitalCalibrationCertificate>';
    }
}
