<?php
declare(strict_types=1);

/**
 * viewer.php
 * Opens a PDF (PDF.js) or MP4 (HTML5 video) and logs:
 * - open time / close time
 * - pages read (unique pages visited)
 * - watched seconds (forward-play deltas)
 */

require __DIR__ . '/auth.php';
require __DIR__ . '/db.php';

$fileId = (int)($_GET['file_id'] ?? 0);
if ($fileId <= 0) { http_response_code(400); exit("Bad request"); }

$stmt = $pdo->prepare("SELECT id, title, type FROM files WHERE id = :id AND is_active = 1 LIMIT 1");
$stmt->execute([':id' => $fileId]);
$file = $stmt->fetch();
if (!$file) { http_response_code(404); exit("Not found"); }
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title><?= htmlspecialchars($file['title']) ?></title>
  <style>
    body { font-family: Arial, sans-serif; margin: 16px; }
    #pdfWrap, #videoWrap { display:none; }
    .btn { padding: 7px 12px; border:1px solid #333; cursor:pointer; margin-right:8px; display:inline-block; border-radius: 8px; }
    canvas { border:1px solid #ddd; max-width:100%; }
  </style>

  <?php if ($file['type'] === 'pdf'): ?>
    <script src="assets/pdfjs/pdf.min.js"></script>

  <?php endif; ?>
</head>
<body>
  <h3><?= htmlspecialchars($file['title']) ?> (<?= htmlspecialchars($file['type']) ?>)</h3>

  <?php if ($file['type'] === 'pdf'): ?>
    <div id="pdfWrap">
      <div style="margin:10px 0;">
        <span class="btn" id="prevBtn">Prev</span>
        <span class="btn" id="nextBtn">Next</span>
        <span>Page <span id="pageNum">1</span> / <span id="pageCount">?</span></span>
      </div>
      <canvas id="theCanvas"></canvas>
    </div>
  <?php else: ?>
    <div id="videoWrap">
      <video id="video" controls playsinline style="max-width:100%; width:900px;">
        <source src="file_serve.php?file_id=<?= (int)$file['id'] ?>" type="video/mp4">
      </video>
    </div>
  <?php endif; ?>

<script>
(() => {
  const fileId = <?= (int)$file['id'] ?>;
  const fileType = <?= json_encode($file['type']) ?>;

  let sessionId = null;

  const pagesSeen = new Set();
  let watchedSeconds = 0;
  let lastVideoTime = 0;

  async function logStart() {
    const res = await fetch('api/log_start.php', {
      method: 'POST',
      headers: {'Content-Type':'application/json'},
      body: JSON.stringify({ file_id: fileId })
    });
    const data = await res.json();
    if (!data.ok) throw new Error(data.error || 'log_start failed');
    sessionId = data.session_id;
  }

  function beacon(url, payload) {
    if (!sessionId) return;
    payload.session_id = sessionId;
    const blob = new Blob([JSON.stringify(payload)], {type:'application/json'});
    navigator.sendBeacon(url, blob);
  }

  function logProgress() {
    beacon('api/log_progress.php', {
      pages_read: pagesSeen.size,
      watched_seconds: Math.floor(watchedSeconds)
    });
  }

  function logEnd() {
    beacon('api/log_end.php', {
      pages_read: pagesSeen.size,
      watched_seconds: Math.floor(watchedSeconds)
    });
  }

  // flush every 15 seconds (helps if user closes tab abruptly)
  setInterval(logProgress, 15000);

  window.addEventListener('beforeunload', logEnd);
  window.addEventListener('pagehide', logEnd);

  (async function init() {
    await logStart();

    if (fileType === 'pdf') {
      document.getElementById('pdfWrap').style.display = 'block';

      const url = 'file_serve.php?file_id=' + fileId;
      pdfjsLib.GlobalWorkerOptions.workerSrc = "assets/pdfjs/pdf.worker.min.js";

      const pdf = await pdfjsLib.getDocument(url).promise;

      let pageNum = 1;
      document.getElementById('pageCount').textContent = pdf.numPages;

      const canvas = document.getElementById('theCanvas');
      const ctx = canvas.getContext('2d');

      async function renderPage(num) {
        const page = await pdf.getPage(num);
        const viewport = page.getViewport({ scale: 1.25 });
        canvas.width = viewport.width;
        canvas.height = viewport.height;
        await page.render({ canvasContext: ctx, viewport }).promise;

        document.getElementById('pageNum').textContent = num;
        pagesSeen.add(num);
      }

      document.getElementById('prevBtn').onclick = async () => {
        if (pageNum <= 1) return;
        pageNum--;
        await renderPage(pageNum);
      };

      document.getElementById('nextBtn').onclick = async () => {
        if (pageNum >= pdf.numPages) return;
        pageNum++;
        await renderPage(pageNum);
      };

      await renderPage(pageNum);
    }

    if (fileType === 'mp4') {
      document.getElementById('videoWrap').style.display = 'block';

      const video = document.getElementById('video');
      video.addEventListener('timeupdate', () => {
        const t = video.currentTime || 0;
        const delta = t - lastVideoTime;

        // count only forward playback deltas (ignore seeking)
        if (!video.paused && !video.seeking && delta > 0 && delta < 2.5) {
          watchedSeconds += delta;
        }
        lastVideoTime = t;
      });
    }
  })().catch(err => {
  console.error(err);
  alert('Unable to open viewer: ' + (err?.message || err));
});
})();
</script>
</body>
</html>
