<?php
/**
 * Balance Laboratory — Certificate View & Preview
 * Variables provided by CertificateController:
 *   $cert     — certificates row (+ issued_by_name, signature, lab_code)
 *   $request  — full request row with joined company/equipment/lab data
 *   $formData — balance_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/balance/certificate/BalanceLabCertificate.php';

$handler = new BalanceLabCertificate();

// Re-render the certificate HTML for the live preview (inline, not for download)
$previewHtml = $handler->generateHTML(
    $request,
    $formData,
    $officer,
    $cert['cert_number'],
    $cert['issue_date']
);

// Extract just the <body> content for inline embedding
preg_match('/<body[^>]*>(.*?)<\/body>/si', $previewHtml, $bodyMatch);
$bodyContent = $bodyMatch[1] ?? $previewHtml;

// Inline CSS from the cert (extract from <style>)
preg_match_all('/<style[^>]*>(.*?)<\/style>/si', $previewHtml, $styleMatches);
$inlineStyles = implode("\n", $styleMatches[1] ?? []);
?>

<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>

<!-- Quick 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;">LABORATORY</div>
      <div class="fw-bold small"><?= e($cert['lab_name']) ?></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 NUMBER</div>
      <button id="copyCertBtn" data-cert="<?= e($cert['cert_number']) ?>"
              class="btn btn-link btn-sm p-0 fw-bold" style="font-size:11px;">
        <code><?= e($cert['cert_number']) ?></code>
        <i class="bi bi-clipboard ms-1"></i>
      </button>
    </div>
  </div>
</div>

<!-- ── Certificate preview frame ── -->
<div class="card no-print mb-3">
  <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</span>
    <span class="badge bg-success">3 Pages</span>
  </div>
  <div class="card-body p-0">
    <iframe id="certFrame"
            style="width:100%;height:900px;border:none;"
            srcdoc=""
            title="Certificate Preview"></iframe>
  </div>
</div>

<!-- ── Print-only area (renders directly when printing) ── -->
<div id="printArea" style="display:none;">
  <?= $bodyContent ?>
</div>

<style>
/* Scope the cert CSS so it doesn't bleed into the portal UI */
#certFrame { background: #fff; }

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

<script>
// Load the full cert HTML into the iframe for a clean scoped preview
const certHTML = <?= json_encode($previewHtml) ?>;
const iframe   = document.getElementById('certFrame');
iframe.addEventListener('load', function() {}, false);
// Use srcdoc via JS to avoid Content-Security-Policy issues
iframe.srcdoc = certHTML;

// Copy cert number
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'; ?>
