<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <a href="<?= base_url('documents/' . $doc['id']) ?>" class="btn btn-sm btn-outline-secondary">
      <i class="bi bi-arrow-left me-1"></i>Kembali
    </a>
  </div>
  <h6 class="mb-0 text-muted small d-none d-md-block"><?= esc(character_limiter($doc['title'], 70)) ?></h6>
  <a href="<?= base_url('documents/' . $doc['id'] . '/download') ?>" class="btn btn-sm btn-primary">
    <i class="bi bi-download me-1"></i>Unduh
  </a>
</div>

<div id="pdfViewerWrap" oncontextmenu="return false;">
  <div id="pdfWatermark"></div>
  <canvas id="pdfCanvas" class="w-100 rounded shadow-sm"></canvas>
</div>

<div class="d-flex justify-content-center align-items-center gap-3 mt-3">
  <button id="btnPrev" class="btn btn-sm btn-outline-secondary" disabled>
    <i class="bi bi-chevron-left"></i> Sebelumnya
  </button>
  <span class="small text-muted">Hal <span id="pageNum">1</span> / <span id="pageCount">—</span></span>
  <button id="btnNext" class="btn btn-sm btn-outline-secondary">
    Berikutnya <i class="bi bi-chevron-right"></i>
  </button>
</div>

<?= $this->endSection() ?>
<?= $this->section('scripts') ?>
<script src="https://cdn.jsdelivr.net/npm/pdfjs-dist@3.11.174/build/pdf.min.js"></script>
<script>
(function () {
  'use strict';

  const streamUrl = <?= json_encode(base_url('documents/' . $doc['id'] . '/stream')) ?>;
  const userName  = <?= json_encode(esc($profile['name'] ?? auth()->user()->username ?? 'Pengguna')) ?>;
  const userNim   = <?= json_encode(esc($profile['identity_number'] ?? '')) ?>;
  const today     = new Date().toLocaleDateString('id-ID', {day:'2-digit', month:'long', year:'numeric'});
  const watermark = userName + (userNim ? ' / ' + userNim : '') + ' — ' + today;

  pdfjsLib.GlobalWorkerOptions.workerSrc =
    'https://cdn.jsdelivr.net/npm/pdfjs-dist@3.11.174/build/pdf.worker.min.js';

  let pdfDoc = null, pageNum = 1;

  const canvas  = document.getElementById('pdfCanvas');
  const ctx     = canvas.getContext('2d');
  const wrap    = document.getElementById('pdfViewerWrap');
  const wmEl    = document.getElementById('pdfWatermark');

  function renderPage(num) {
    pdfDoc.getPage(num).then(page => {
      const vp     = page.getViewport({ scale: canvas.parentElement.clientWidth / page.getViewport({scale:1}).width });
      canvas.width  = vp.width;
      canvas.height = vp.height;
      wrap.style.height = vp.height + 'px';

      page.render({ canvasContext: ctx, viewport: vp });

      // Watermark overlay
      wmEl.innerHTML = '';
      const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
      svg.setAttribute('width', '100%');
      svg.setAttribute('height', '100%');
      for (let y = 80; y < vp.height; y += 120) {
        for (let x = 0; x < vp.width; x += 400) {
          const t = document.createElementNS('http://www.w3.org/2000/svg', 'text');
          t.setAttribute('x', x); t.setAttribute('y', y);
          t.setAttribute('transform', `rotate(-30, ${x}, ${y})`);
          t.setAttribute('font-size', '16');
          t.setAttribute('fill', '#2c353d');
          t.textContent = watermark;
          svg.appendChild(t);
        }
      }
      wmEl.appendChild(svg);

      document.getElementById('pageNum').textContent  = num;
      document.getElementById('btnPrev').disabled     = num <= 1;
      document.getElementById('btnNext').disabled     = num >= pdfDoc.numPages;
    });
  }

  pdfjsLib.getDocument(streamUrl).promise.then(doc => {
    pdfDoc = doc;
    document.getElementById('pageCount').textContent = doc.numPages;
    renderPage(1);
  });

  document.getElementById('btnPrev').addEventListener('click', () => {
    if (pageNum > 1) renderPage(--pageNum);
  });
  document.getElementById('btnNext').addEventListener('click', () => {
    if (pageNum < pdfDoc.numPages) renderPage(++pageNum);
  });
})();
</script>
<?= $this->endSection() ?>
