<?php
require_once __DIR__ . '/lib/core.php';

$id = isset($_GET['id']) ? trim($_GET['id']) : '';
$key = isset($_GET['key']) ? trim($_GET['key']) : '';
$door = ($id !== '' && $key !== '') ? dc_find_public_door($id, $key) : null;

dc_public_header('Fire Door Certificate Verification');
?>
<div class="dc-card">
  <div class="dc-verify-title">
    <h1><?php echo dc_h(DC_COMPANY_NAME); ?></h1>
    <p>Fire Door Certificate Verification</p>
  </div>

  <?php if (!$door): ?>
    <h2>Certificate not found</h2>
    <p>Please scan a valid <?php echo dc_h(DC_COMPANY_NAME); ?> QR code or check that the full verification link was opened.</p>
  <?php else: ?>
    <?php $status = dc_status_for_door($door); ?>
    <h2><?php echo dc_h($door['door_id']); ?></h2>
    <p><span class="dc-status <?php echo dc_h($status); ?>"><?php echo dc_h(strtoupper($status)); ?></span></p>
    <table>
      <tr><th>Category</th><td><?php echo dc_h($door['category_name']); ?></td></tr>
      <tr><th>Client</th><td><?php echo dc_h($door['client_name']); ?></td></tr>
      <tr><th>Address</th><td><?php echo dc_h($door['site_location']); ?></td></tr>
      <tr><th>Area / Site</th><td><?php echo dc_h($door['area_location']); ?></td></tr>
      <?php if (!empty($door['po_number'])): ?><tr><th>PO Number</th><td><?php echo dc_h($door['po_number']); ?></td></tr><?php endif; ?>
      <tr><th>Fire Rating</th><td><?php echo dc_h($door['fire_rating']); ?></td></tr>
      <tr><th>Standards</th><td><?php echo dc_h(dc_display_standards($door['standards'])); ?></td></tr>
      <tr><th>Manufacturing Date</th><td><?php echo dc_h(dc_format_date($door['manufacture_date'])); ?></td></tr>
      <tr><th>Valid From</th><td><?php echo dc_h(dc_format_date($door['valid_from'])); ?></td></tr>
      <tr><th>Valid To</th><td><?php echo dc_h(dc_format_date($door['valid_to'])); ?></td></tr>
    </table>
    <?php $standardCertificates = dc_company_certificates_for_standards($door['standards']); ?>
    <?php $certificateUrl = 'download.php?type=certificate&id=' . rawurlencode($door['door_id']) . '&key=' . rawurlencode($door['qr_token']); ?>
    <?php $certificatePdfUrl = 'download.php?type=pdf&id=' . rawurlencode($door['door_id']) . '&key=' . rawurlencode($door['qr_token']); ?>
    <?php $certificatePdfFilename = dc_certificate_download_filename($door, 'pdf'); ?>
    <div class="dc-actions">
      <button type="button" class="dc-btn" id="door-certificate-toggle">View Certificate</button>
      <button
        type="button"
        class="dc-btn secondary dc-download-certificate-pdf"
        data-fallback-url="<?php echo dc_h($certificatePdfUrl); ?>"
        data-filename="<?php echo dc_h($certificatePdfFilename); ?>">
        Download PDF
      </button>
      <?php if ($standardCertificates): ?>
        <button type="button" class="dc-btn secondary" id="company-certificate-toggle">View PCSIR Report</button>
      <?php endif; ?>
    </div>
    <div class="dc-modal" id="door-certificate-modal" aria-hidden="true" hidden>
      <div class="dc-modal-panel dc-certificate-modal-panel" role="dialog" aria-modal="true" aria-labelledby="door-certificate-title">
        <div class="dc-modal-header">
          <div>
            <h2 id="door-certificate-title">Certificate</h2>
            <p><?php echo dc_h($door['door_id']); ?></p>
          </div>
          <button type="button" class="dc-icon-btn" id="door-certificate-close">Close</button>
        </div>
        <div class="dc-certificate-toolbar">
          <strong><?php echo dc_h($door['door_id']); ?></strong>
          <button
            type="button"
            class="dc-btn light dc-download-certificate-pdf"
            data-fallback-url="<?php echo dc_h($certificatePdfUrl); ?>"
            data-filename="<?php echo dc_h($certificatePdfFilename); ?>">
            Download PDF
          </button>
        </div>
        <iframe title="Door certificate" id="door-certificate-frame" data-src="<?php echo dc_h($certificateUrl); ?>"></iframe>
      </div>
    </div>
    <div class="dc-pdf-status" id="door-certificate-pdf-status" role="status" aria-live="polite"></div>
    <?php if ($standardCertificates): ?>
      <div class="dc-modal" id="company-certificate-modal" aria-hidden="true" hidden>
        <div class="dc-modal-panel" role="dialog" aria-modal="true" aria-labelledby="company-certificate-title">
          <div class="dc-modal-header">
            <div>
              <h2 id="company-certificate-title">Applicable Standards</h2>
              <p><?php echo dc_h(dc_display_standards($door['standards'])); ?></p>
            </div>
            <button type="button" class="dc-icon-btn" id="company-certificate-close">Close</button>
          </div>
          <div class="dc-standard-cert-tabs">
            <?php foreach ($standardCertificates as $index => $certificate): ?>
              <button
                type="button"
                class="<?php echo $index === 0 ? 'active' : ''; ?>"
                data-src="<?php echo dc_h(dc_company_certificate_viewer_url($door, $certificate['slug'])); ?>"
                data-download="<?php echo dc_h(dc_company_certificate_url($door, true, $certificate['slug'])); ?>">
                <?php echo dc_h($certificate['name']); ?>
              </button>
            <?php endforeach; ?>
          </div>
          <div class="dc-certificate-toolbar">
            <strong id="company-certificate-name"><?php echo dc_h($standardCertificates[0]['name']); ?></strong>
            <a class="dc-btn light" id="company-certificate-download" href="<?php echo dc_h(dc_company_certificate_url($door, true, $standardCertificates[0]['slug'])); ?>">Download Standard</a>
          </div>
          <iframe title="Applicable standard certificate" id="company-certificate-frame" src="<?php echo dc_h(dc_company_certificate_viewer_url($door, $standardCertificates[0]['slug'])); ?>"></iframe>
        </div>
      </div>
      <script>
      (function () {
        var toggle = document.getElementById('company-certificate-toggle');
        var modal = document.getElementById('company-certificate-modal');
        var close = document.getElementById('company-certificate-close');
        var frame = document.getElementById('company-certificate-frame');
        var download = document.getElementById('company-certificate-download');
        var name = document.getElementById('company-certificate-name');
        var tabs = modal ? modal.querySelectorAll('.dc-standard-cert-tabs button') : [];
        if (!toggle || !modal) {
          return;
        }
        function openModal() {
          modal.className = 'dc-modal open';
          modal.removeAttribute('hidden');
          modal.setAttribute('aria-hidden', 'false');
        }
        function closeModal() {
          modal.className = 'dc-modal';
          modal.setAttribute('hidden', 'hidden');
          modal.setAttribute('aria-hidden', 'true');
        }
        toggle.addEventListener('click', function () {
          openModal();
        });
        close.addEventListener('click', closeModal);
        modal.addEventListener('click', function (event) {
          if (event.target === modal) {
            closeModal();
          }
        });
        document.addEventListener('keydown', function (event) {
          if (event.key === 'Escape') {
            closeModal();
          }
        });
        tabs.forEach(function (tab) {
          tab.addEventListener('click', function () {
            tabs.forEach(function (other) { other.className = ''; });
            tab.className = 'active';
            frame.src = tab.getAttribute('data-src');
            download.href = tab.getAttribute('data-download');
            name.textContent = tab.textContent.replace(/\s+/g, ' ').trim();
          });
        });
      })();
      </script>
    <?php endif; ?>
    <script>
    (function () {
      var toggle = document.getElementById('door-certificate-toggle');
      var modal = document.getElementById('door-certificate-modal');
      var close = document.getElementById('door-certificate-close');
      var frame = document.getElementById('door-certificate-frame');
      if (!toggle || !modal || !frame) {
        return;
      }
      function certificateSrc() {
        var source = frame.getAttribute('data-src');
        if (window.innerWidth > 860) {
          return source;
        }
        var separator = source.indexOf('?') === -1 ? '?' : '&';
        var frameBox = frame.getBoundingClientRect ? frame.getBoundingClientRect() : null;
        var width = Math.floor((frameBox && frameBox.width) || modal.clientWidth || window.innerWidth);
        return source + separator + 'fit_width=' + encodeURIComponent(width);
      }
      function openModal() {
        modal.className = 'dc-modal open';
        modal.removeAttribute('hidden');
        modal.setAttribute('aria-hidden', 'false');
        var source = certificateSrc();
        if (frame.getAttribute('src') !== source) {
          frame.setAttribute('src', source);
        }
      }
      function closeModal() {
        modal.className = 'dc-modal';
        modal.setAttribute('hidden', 'hidden');
        modal.setAttribute('aria-hidden', 'true');
      }
      toggle.addEventListener('click', openModal);
      close.addEventListener('click', closeModal);
      modal.addEventListener('click', function (event) {
        if (event.target === modal) {
          closeModal();
        }
      });
      document.addEventListener('keydown', function (event) {
        if (event.key === 'Escape') {
          closeModal();
        }
      });
    })();
    </script>
    <script>
    (function () {
      var status = document.getElementById('door-certificate-pdf-status');
      var buttons = document.querySelectorAll('.dc-download-certificate-pdf');
      if (!buttons.length) {
        return;
      }

      function setStatus(message, isError) {
        if (!status) {
          return;
        }
        status.textContent = message || '';
        status.className = isError ? 'dc-pdf-status error' : 'dc-pdf-status';
      }

      function setBusy(button, busy) {
        button.disabled = busy;
        button.className = busy
          ? button.className.replace(/\s*is-loading/g, '') + ' is-loading'
          : button.className.replace(/\s*is-loading/g, '');
      }

      function downloadPdf(button) {
        var exportUrl = button.getAttribute('data-fallback-url');
        if (!exportUrl) {
          setStatus('Certificate export link is missing.', true);
          return;
        }
        setBusy(button, true);
        setStatus('Opening certificate PDF export...');
        window.location.href = exportUrl;
      }

      Array.prototype.forEach.call(buttons, function (button) {
        button.addEventListener('click', function () {
          downloadPdf(button);
        });
      });

      window.addEventListener('pageshow', function () {
        Array.prototype.forEach.call(buttons, function (button) {
          setBusy(button, false);
        });
      });
    })();
    </script>
  <?php endif; ?>
</div>
<?php dc_footer(); ?>
