<?php
/**
 * Temperature & Humidity Laboratory — Certificate View & Preview
 * Variables from CertificateController:
 *   $cert      — certificates row
 *   $request   — full request row (joined company/equipment/lab)
 *   $formData  — humidity_lab_forms row
 *   $officer   — ['officer_name' => ..., 'signature' => ...]
 */
$pageTitle = 'Certificate — ' . e($cert['cert_number']);
include __DIR__ . '/../../shared/header.php';

require_once BASE_PATH . '/helpers/ILabCertificate.php';
require_once BASE_PATH . '/labs/humidity/HumidityUncertaintyEngine.php';
require_once BASE_PATH . '/labs/humidity/form/HumidityLabForm.php';
require_once BASE_PATH . '/labs/humidity/certificate/HumidityLabCertificate.php';

$handler     = new HumidityLabCertificate();
$previewHtml = $handler->generateHTML(
    $request,
    $formData,
    $officer,
    $cert['cert_number'],
    $cert['issue_date']
);

// Extract body and styles for scoped inline preview
preg_match('/<body[^>]*>(.*?)<\/body>/si', $previewHtml, $bodyMatch);
$bodyContent = $bodyMatch[1] ?? $previewHtml;
preg_match_all('/<style[^>]*>(.*?)<\/style>/si', $previewHtml, $styleMatches);
$inlineStyles = implode("\n", $styleMatches[1] ?? []);

$results = HumidityLabForm::buildResults($formData);
?>

<div class="page-header">
  <div>
    <div class="page-title"><i class="bi bi-award me-2"></i>Calibration Certificate</div>
    <div class="page-subtitle">
      <code><?= e($cert['cert_number']) ?></code> &mdash;
      <?= e($request['company_name']) ?> &mdash;
      <?= e($request['equipment_name']) ?>
    </div>
  </div>
  <div class="d-flex gap-2 flex-wrap">
    <a href="<?= APP_URL ?>/index.php?page=certificates&action=download&id=<?= $cert['cert_id'] ?>&type=pdf"
       class="btn btn-danger">
      <i class="bi bi-file-earmark-pdf me-1"></i>Download PDF
    </a>
    <a href="<?= APP_URL ?>/index.php?page=certificates&action=download&id=<?= $cert['cert_id'] ?>&type=xml"
       class="btn btn-outline-secondary">
      <i class="bi bi-file-earmark-code me-1"></i>Download DCC XML
    </a>
    <button onclick="window.print()" class="btn btn-outline-primary no-print">
      <i class="bi bi-printer me-1"></i>Print
    </button>
    <a href="<?= APP_URL ?>/index.php?page=certificates" class="btn btn-outline-secondary no-print">
      <i class="bi bi-arrow-left me-1"></i>Back
    </a>
  </div>
</div>

<!-- Meta bar -->
<div class="row g-2 mb-3 no-print">
  <div class="col-md-2">
    <div class="card text-center p-2">
      <div class="text-muted" style="font-size:10px;">ISSUED</div>
      <div class="fw-bold small"><?= date('d M Y', strtotime($cert['issue_date'])) ?></div>
    </div>
  </div>
  <div class="col-md-2">
    <div class="card text-center p-2">
      <div class="text-muted" style="font-size:10px;">SETPOINTS</div>
      <div class="fw-bold small"><?= count($results) ?></div>
    </div>
  </div>
  <div class="col-md-3">
    <div class="card text-center p-2">
      <div class="text-muted" style="font-size:10px;">ISSUED BY</div>
      <div class="fw-bold small"><?= e($cert['issued_by_name']) ?></div>
    </div>
  </div>
  <div class="col-md-3">
    <div class="card text-center p-2">
      <div class="text-muted" style="font-size:10px;">REQUEST NO.</div>
      <div class="fw-bold small"><code><?= e($cert['request_number']) ?></code></div>
    </div>
  </div>
  <div class="col-md-2">
    <div class="card text-center p-2">
      <div class="text-muted" style="font-size:10px;">CERT NO.</div>
      <button id="copyCertBtn" data-cert="<?= e($cert['cert_number']) ?>"
              class="btn btn-link btn-sm p-0 fw-bold" style="font-size:10px;">
        <code><?= e($cert['cert_number']) ?></code> <i class="bi bi-clipboard ms-1"></i>
      </button>
    </div>
  </div>
</div>

<!-- Quick results summary -->
<div class="card mb-3 no-print">
  <div class="card-header"><span class="card-title"><i class="bi bi-table me-2"></i>Results Summary</span></div>
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table table-sm table-hover mb-0">
        <thead class="table-light">
          <tr>
            <th>Setpoint</th>
            <th>Ref Temp (°C)</th>
            <th>Ref RH (%RH)</th>
            <th>EUT RH (%RH)</th>
            <th>RH Dev (%RH)</th>
            <th>U(RH) (%RH)</th>
            <th>EUT Temp (°C)</th>
            <th>Temp Dev (°C)</th>
            <th>U(T) (K)</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($results as $res): ?>
          <tr>
            <td><?= e($res['setpoint']) ?></td>
            <td><?= e(number_format((float)$res['corrected_ref_temp'], 2)) ?></td>
            <td><?= e(number_format((float)$res['corrected_ref_rh'],  2)) ?></td>
            <td><?= e(number_format((float)$res['avg_eut_rh'],        2)) ?></td>
            <td><?= e(number_format((float)$res['rh_deviation'],      4)) ?></td>
            <td class="text-success fw-semibold"><?= e(number_format((float)$res['rh_uncertainty'], 3)) ?></td>
            <td><?= $res['include_temp'] ? e(number_format((float)$res['avg_eut_temp'], 2)) : '<span class="text-muted">—</span>' ?></td>
            <td><?= $res['include_temp'] ? e(number_format((float)$res['temp_deviation'], 4)) : '<span class="text-muted">—</span>' ?></td>
            <td class="text-primary fw-semibold"><?= $res['include_temp'] ? e(number_format((float)$res['temp_uncertainty'], 3)) : '<span class="text-muted">—</span>' ?></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- Certificate preview via iframe -->
<div class="card no-print">
  <div class="card-header d-flex justify-content-between align-items-center">
    <span class="card-title"><i class="bi bi-file-text me-2"></i>Certificate Preview (2 Pages)</span>
  </div>
  <div class="card-body p-0">
    <iframe id="certFrame" style="width:100%;height:860px;border:none;" title="Certificate Preview"></iframe>
  </div>
</div>

<div id="printArea" style="display:none;"><?= $bodyContent ?></div>

<style>
@media print {
  .sidebar,.topbar,.page-header,.no-print,.alert,.card-header { display:none!important; }
  .main-content { margin-left:0!important; }
  .content-area { padding:0!important; }
  #printArea { display:block!important; }
  <?= $inlineStyles ?>
}
</style>

<script>
document.getElementById('certFrame').srcdoc = <?= json_encode($previewHtml) ?>;

document.getElementById('copyCertBtn')?.addEventListener('click', function() {
    navigator.clipboard.writeText(this.dataset.cert).then(() => {
        this.innerHTML = '<code><?= e($cert['cert_number']) ?></code> <i class="bi bi-check text-success"></i>';
        setTimeout(() => {
            this.innerHTML = '<code><?= e($cert['cert_number']) ?></code> <i class="bi bi-clipboard ms-1"></i>';
        }, 2000);
    });
});
</script>

<?php include __DIR__ . '/../../shared/footer.php'; ?>
