<?php
// ============================================================
// GenericLabCertificate  — backward-compatible fallback
// Used for all labs that don't have a specific implementation.
// ============================================================
class GenericLabCertificate implements ILabCertificate {

    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:60px;max-width:200px;" alt="Signature">';
            }
        }
        return '<div style="height:50px;border-bottom:1px solid #000;width:200px;"></div>';
    }

    public function generateHTML(array $request, array $formData, array $officer, string $certNum, string $issueDate): string {
        $measData = json_decode($formData['measurement_data'] ?? '{}', true);
        $refEquip = json_decode($formData['reference_equipment'] ?? '[]', true);
        $e        = fn($v) => htmlspecialchars((string)($v ?? ''), ENT_QUOTES, 'UTF-8');

        $rows = '';
        foreach ($measData['rows'] ?? [] as $i => $row) {
            $rows .= '<tr><td>' . ($i+1) . '</td><td>' . $e($row['name'] ?? '') . '</td>'
                   . '<td>' . $e($row['nominal'] ?? '') . '</td><td>' . $e($row['measured'] ?? '') . '</td>'
                   . '<td>' . $e($row['error'] ?? '') . '</td><td>' . $e($row['uncertainty'] ?? '') . '</td>'
                   . '<td>' . $e($row['unit'] ?? '') . '</td></tr>';
        }
        $refHtml = '';
        foreach ($refEquip as $ref) {
            $refHtml .= '<tr><td>' . $e($ref['name'] ?? '') . '</td>'
                      . '<td>' . $e($ref['serial'] ?? '') . '</td>'
                      . '<td>' . $e($ref['cert'] ?? '') . '</td></tr>';
        }

        return '<!DOCTYPE html><html><head><meta charset="UTF-8">
<title>Certificate ' . $e($certNum) . '</title>
<style>
  body{font-family:Arial,sans-serif;font-size:10pt;color:#000;}
  table{width:100%;border-collapse:collapse;}
  th,td{border:1px solid #ccc;padding:4px 6px;}
  thead th{background:#003366;color:#fff;}
  .nb td,.nb th{border:none;}
  h2{color:#003366;font-size:14pt;}
  @media print{.no-print{display:none}}
</style>
</head><body>
<h2>Ghana Standards Authority — Calibration Certificate</h2>
<p><strong>Certificate No.:</strong> ' . $e($certNum) . '
   &nbsp;&nbsp; <strong>Date Issued:</strong> ' . $e($issueDate) . '</p>
<hr>
<table class="nb">
  <tr><td><strong>Company:</strong> ' . $e($request['company_name']) . '</td>
      <td><strong>Laboratory:</strong> ' . $e($request['lab_name']) . '</td></tr>
  <tr><td><strong>Equipment:</strong> ' . $e($request['equipment_name']) . '</td>
      <td><strong>Manufacturer:</strong> ' . $e($request['manufacturer'] ?? '') . '</td></tr>
  <tr><td><strong>Model:</strong> ' . $e($request['model'] ?? '') . '</td>
      <td><strong>Serial No.:</strong> ' . $e($request['serial_number'] ?? '') . '</td></tr>
  <tr><td><strong>Place of Test:</strong> ' . $e($formData['place_of_test'] ?? '') . '</td>
      <td><strong>Procedure:</strong> ' . $e($formData['procedure_used'] ?? '') . '</td></tr>
</table>
<hr>
' . (!empty($refHtml) ? '<h4>Reference Standards</h4>
<table><thead><tr><th>Equipment</th><th>Serial No.</th><th>Certificate No.</th></tr></thead>
<tbody>' . $refHtml . '</tbody></table><hr>' : '') . '
<h4>Measurement Results</h4>
<table><thead><tr><th>#</th><th>Point</th><th>Nominal</th><th>Measured</th><th>Error</th><th>Uncertainty</th><th>Unit</th></tr></thead>
<tbody>' . ($rows ?: '<tr><td colspan="7" style="text-align:center;color:#888;">No measurement data recorded.</td></tr>') . '</tbody></table>
<hr>
<p><strong>Uncertainty Statement:</strong> ' . $e($formData['uncertainty_statement'] ?? '') . '</p>
<p>Coverage factor k = <strong>' . $e($formData['coverage_factor'] ?? '2') . '</strong>,
   Confidence level: <strong>' . $e($formData['confidence_level'] ?? '95%') . '</strong></p>
' . (!empty($formData['remarks']) ? '<p><strong>Remarks:</strong> ' . $e($formData['remarks']) . '</p>' : '') . '
<div style="margin-top:30px;text-align:right;padding-right:40px;">
  ' . $this->renderSignature($officer) . '
  <p style="border-top:1px solid #000;display:inline-block;min-width:200px;text-align:center;padding-top:4px;font-size:9pt;">
    <strong>' . $e($officer['officer_name'] ?? '') . '</strong><br>
    Laboratory Officer
  </p>
</div>
<hr>
<p style="font-size:8.5pt;text-align:center;color:#555;">
  Ghana Standards Authority &mdash; ' . $e($request['lab_name']) . ' &bull;
  Certificate No. ' . $e($certNum) . ' &bull; Issued: ' . $e($issueDate) . '
</p>
</body></html>';
    }

    public function generateXML(array $request, array $formData, array $officer, string $certNum, string $issueDate): string {
        $measData = json_decode($formData['measurement_data'] ?? '{}', true);
        $e        = fn($v) => htmlspecialchars(trim((string)$v), ENT_XML1, 'UTF-8');
        $rows     = '';
        foreach ($measData['rows'] ?? [] as $i => $row) {
            $n = $i + 1;
            $rows .= '<dcc:result refType="gp_result' . $n . '">'
                   . '<dcc:name><dcc:content lang="en">' . $e($row['name'] ?? "Result $n") . '</dcc:content></dcc:name>'
                   . '<dcc:data><dcc:quantity refType="basic_measuredValue">'
                   . '<si:real><si:value>' . $e($row['measured'] ?? '0') . '</si:value>'
                   . '<si:unit>' . $e($row['unit'] ?? '') . '</si:unit></si:real>'
                   . '</dcc:quantity></dcc:data></dcc:result>';
        }
        return '<?xml version="1.0" encoding="UTF-8"?>'
             . '<dcc:digitalCalibrationCertificate xmlns:dcc="https://ptb.de/dcc" xmlns:si="https://ptb.de/si" schemaVersion="3.2.1">'
             . '<dcc:administrativeData><dcc:coreData>'
             . '<dcc:uniqueIdentifier>' . $e($certNum) . '</dcc:uniqueIdentifier>'
             . '<dcc:endPerformanceDate>' . $e($issueDate) . '</dcc:endPerformanceDate>'
             . '</dcc:coreData><dcc:items><dcc:item>'
             . '<dcc:name><dcc:content lang="en">' . $e($request['equipment_name']) . '</dcc:content></dcc:name>'
             . '</dcc:item></dcc:items>'
             . '<dcc:respPersons><dcc:respPerson><dcc:person><dcc:name>' . $e($officer['officer_name'] ?? '') . '</dcc:name></dcc:person></dcc:respPerson></dcc:respPersons>'
             . '</dcc:administrativeData>'
             . '<dcc:measurementResults><dcc:measurementResult><dcc:results>' . $rows . '</dcc:results></dcc:measurementResult></dcc:measurementResults>'
             . '</dcc:digitalCalibrationCertificate>';
    }
}
