<?php
require_once 'includes/config.php';
requireLogin();
$uid = $_SESSION['user_id'];

// ── AJAX: save / load annotations ────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    $action = $_POST['action'] ?? '';
    $fileId = (int)($_POST['file_id'] ?? 0);

    // Verify ownership every time
    $chk = $pdo->prepare("SELECT id FROM subject_files WHERE id=? AND user_id=? AND file_type='pdf'");
    $chk->execute([$fileId, $uid]);
    if (!$chk->fetch()) jsonResponse(['success' => false, 'message' => 'File not found.']);

    if ($action === 'save_annotation') {
        $page = (int)($_POST['page'] ?? 1);
        $data = $_POST['data'] ?? '[]';
        json_decode($data);
        if (json_last_error() !== JSON_ERROR_NONE) jsonResponse(['success' => false, 'message' => 'Bad annotation data.']);
        $pdo->prepare("INSERT INTO pdf_annotations (file_id,user_id,page_number,annotation_data)
                       VALUES (?,?,?,?)
                       ON DUPLICATE KEY UPDATE annotation_data=VALUES(annotation_data), updated_at=NOW()")
            ->execute([$fileId, $uid, $page, $data]);
        jsonResponse(['success' => true]);
    }

    if ($action === 'load_annotation') {
        $page = (int)($_POST['page'] ?? 1);
        $stmt = $pdo->prepare("SELECT annotation_data FROM pdf_annotations WHERE file_id=? AND page_number=?");
        $stmt->execute([$fileId, $page]);
        $data = $stmt->fetchColumn();
        jsonResponse(['success' => true, 'data' => $data ?: '[]']);
    }

    if ($action === 'clear_page') {
        $page = (int)($_POST['page'] ?? 1);
        $pdo->prepare("DELETE FROM pdf_annotations WHERE file_id=? AND page_number=?")->execute([$fileId, $page]);
        jsonResponse(['success' => true]);
    }

    jsonResponse(['success' => false, 'message' => 'Unknown action.']);
}

// ── Page load ──────────────────────────────────────────────────────────
$fileId = (int)($_GET['file'] ?? 0);
$stmt = $pdo->prepare("SELECT f.*, s.name AS subject_name FROM subject_files f JOIN subjects s ON s.id=f.subject_id WHERE f.id=? AND f.user_id=?");
$stmt->execute([$fileId, $uid]);
$file = $stmt->fetch();

if (!$file || $file['file_type'] !== 'pdf') {
    require_once 'includes/header.php';
    renderHeader('PDF Annotate', 'subject-files');
    echo '<div class="empty-state"><div class="empty-icon">📕</div><h3>PDF not found</h3><p>This file doesn\'t exist or isn\'t a PDF.</p><a href="subject-files.php" class="btn btn-primary" style="margin-top:12px;display:inline-block">Back to Files</a></div>';
    require_once 'includes/footer.php'; renderFooter();
    exit;
}

$fileUrl = SITE_URL . '/' . $file['file_path'];

require_once 'includes/header.php';
renderHeader('Annotate: ' . $file['file_name'], 'subject-files');
?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf_viewer.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>

<div style="display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:18px;flex-wrap:wrap">
  <div>
    <div style="font-size:20px;font-weight:800;font-family:'Sora',sans-serif">✏️ <?= htmlspecialchars($file['file_name']) ?></div>
    <div style="font-size:12px;color:var(--text-muted);margin-top:3px"><?= htmlspecialchars($file['subject_name']) ?> · Annotations save automatically per page</div>
  </div>
  <a href="subject-files.php" class="btn btn-secondary btn-sm">← Back to Files</a>
</div>

<!-- Toolbar -->
<div class="card" style="margin-bottom:14px;position:sticky;top:8px;z-index:20">
  <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap">
    <div style="display:flex;gap:4px;background:var(--bg-secondary);padding:4px;border-radius:10px">
      <button class="btn btn-sm tool-btn active" data-tool="pen" onclick="setTool('pen',this)" title="Pen">✏️</button>
      <button class="btn btn-sm tool-btn" data-tool="highlight" onclick="setTool('highlight',this)" title="Highlighter">🖍️</button>
      <button class="btn btn-sm tool-btn" data-tool="eraser" onclick="setTool('eraser',this)" title="Eraser">🧹</button>
    </div>
    <input type="color" id="penColor" value="#ff3b3b" style="width:36px;height:32px;border:none;border-radius:8px;cursor:pointer;background:none">
    <select id="penWidth" class="form-input" style="width:auto;padding:6px 10px">
      <option value="2">Thin</option>
      <option value="4" selected>Medium</option>
      <option value="8">Thick</option>
    </select>
    <button class="btn btn-secondary btn-sm" onclick="clearPage()">🗑️ Clear Page</button>
    <div style="flex:1"></div>
    <button class="btn btn-secondary btn-sm" onclick="prevPage()">‹ Prev</button>
    <span id="pageInfo" style="font-size:13px;font-weight:600;color:var(--text-secondary)">Page 1 / 1</span>
    <button class="btn btn-secondary btn-sm" onclick="nextPage()">Next ›</button>
    <span id="saveStatus" style="font-size:11px;color:var(--text-muted)"></span>
  </div>
</div>

<div class="card" style="display:flex;justify-content:center;padding:20px;overflow:auto">
  <div id="pdfWrap" style="position:relative;box-shadow:0 4px 24px rgba(0,0,0,.25);">
    <canvas id="pdfCanvas"></canvas>
    <canvas id="drawCanvas" style="position:absolute;top:0;left:0;cursor:crosshair;touch-action:none"></canvas>
  </div>
</div>

<style>
.tool-btn { background:transparent; border:none; }
.tool-btn.active { background:var(--gradient); color:#fff; border-radius:7px; }
</style>

<script>
const FILE_ID = <?= (int)$file['id'] ?>;
const PDF_URL = <?= json_encode($fileUrl) ?>;
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';

let pdfDoc = null, pageNum = 1, currentTool = 'pen';
let strokes = [];   // committed strokes for current page
let curStroke = null, drawing = false;
const pdfCanvas = document.getElementById('pdfCanvas');
const drawCanvas = document.getElementById('drawCanvas');
const pdfCtx = pdfCanvas.getContext('2d');
const drawCtx = drawCanvas.getContext('2d');

async function post(data) {
  const fd = new FormData();
  Object.entries(data).forEach(([k,v]) => fd.append(k, v));
  const r = await fetch(location.href, { method:'POST', headers:{'X-Requested-With':'XMLHttpRequest'}, body: fd });
  return r.json();
}

function setTool(tool, el) {
  currentTool = tool;
  document.querySelectorAll('.tool-btn').forEach(b => b.classList.remove('active'));
  el.classList.add('active');
  drawCanvas.style.cursor = tool === 'eraser' ? 'cell' : 'crosshair';
}

function redrawStrokes() {
  drawCtx.clearRect(0, 0, drawCanvas.width, drawCanvas.height);
  strokes.forEach(s => {
    drawCtx.globalAlpha = s.tool === 'highlight' ? 0.35 : 1;
    drawCtx.strokeStyle = s.color;
    drawCtx.lineWidth = s.width;
    drawCtx.lineCap = 'round'; drawCtx.lineJoin = 'round';
    drawCtx.beginPath();
    s.points.forEach((p, i) => i === 0 ? drawCtx.moveTo(p[0], p[1]) : drawCtx.lineTo(p[0], p[1]));
    drawCtx.stroke();
  });
  drawCtx.globalAlpha = 1;
}

function getPos(e) {
  const rect = drawCanvas.getBoundingClientRect();
  const cx = (e.touches ? e.touches[0].clientX : e.clientX) - rect.left;
  const cy = (e.touches ? e.touches[0].clientY : e.clientY) - rect.top;
  return [cx * (drawCanvas.width / rect.width), cy * (drawCanvas.height / rect.height)];
}

function startDraw(e) {
  e.preventDefault();
  drawing = true;
  const [x, y] = getPos(e);
  if (currentTool === 'eraser') {
    eraseAt(x, y);
    return;
  }
  curStroke = {
    tool: currentTool,
    color: document.getElementById('penColor').value,
    width: parseInt(document.getElementById('penWidth').value),
    points: [[x, y]]
  };
}

function moveDraw(e) {
  if (!drawing) return;
  e.preventDefault();
  const [x, y] = getPos(e);
  if (currentTool === 'eraser') { eraseAt(x, y); return; }
  curStroke.points.push([x, y]);
  redrawStrokes();
  strokes.push(curStroke);
  drawCtx.globalAlpha = curStroke.tool === 'highlight' ? 0.35 : 1;
  drawCtx.strokeStyle = curStroke.color; drawCtx.lineWidth = curStroke.width;
  drawCtx.lineCap = 'round'; drawCtx.lineJoin = 'round';
  drawCtx.beginPath();
  curStroke.points.forEach((p,i) => i===0 ? drawCtx.moveTo(p[0],p[1]) : drawCtx.lineTo(p[0],p[1]));
  drawCtx.stroke();
  drawCtx.globalAlpha = 1;
  strokes.pop();
}

function endDraw() {
  if (drawing && curStroke) { strokes.push(curStroke); curStroke = null; savePage(); }
  drawing = false;
}

function eraseAt(x, y) {
  const before = strokes.length;
  strokes = strokes.filter(s => !s.points.some(p => Math.hypot(p[0]-x, p[1]-y) < 18));
  if (strokes.length !== before) { redrawStrokes(); savePage(); }
}

let saveTimer = null;
function savePage() {
  clearTimeout(saveTimer);
  const status = document.getElementById('saveStatus');
  status.textContent = 'Saving…';
  saveTimer = setTimeout(async () => {
    await post({ action:'save_annotation', file_id: FILE_ID, page: pageNum, data: JSON.stringify(strokes) });
    status.textContent = 'Saved ✓';
    setTimeout(() => status.textContent = '', 1500);
  }, 400);
}

async function clearPage() {
  if (!(await stConfirm('Clear all annotations on this page?'))) return;
  strokes = [];
  redrawStrokes();
  await post({ action:'clear_page', file_id: FILE_ID, page: pageNum });
}

async function renderPage(num) {
  const page = await pdfDoc.getPage(num);
  const viewport = page.getViewport({ scale: 1.4 });
  pdfCanvas.width = drawCanvas.width = viewport.width;
  pdfCanvas.height = drawCanvas.height = viewport.height;
  document.getElementById('pdfWrap').style.width = viewport.width + 'px';
  document.getElementById('pdfWrap').style.height = viewport.height + 'px';
  await page.render({ canvasContext: pdfCtx, viewport }).promise;

  const res = await post({ action:'load_annotation', file_id: FILE_ID, page: num });
  strokes = JSON.parse(res.data || '[]');
  redrawStrokes();

  document.getElementById('pageInfo').textContent = `Page ${num} / ${pdfDoc.numPages}`;
}

function prevPage() { if (pageNum > 1) { pageNum--; renderPage(pageNum); } }
function nextPage() { if (pdfDoc && pageNum < pdfDoc.numPages) { pageNum++; renderPage(pageNum); } }

drawCanvas.addEventListener('mousedown', startDraw);
drawCanvas.addEventListener('mousemove', moveDraw);
window.addEventListener('mouseup', endDraw);
drawCanvas.addEventListener('touchstart', startDraw, { passive:false });
drawCanvas.addEventListener('touchmove', moveDraw, { passive:false });
drawCanvas.addEventListener('touchend', endDraw);

pdfjsLib.getDocument(PDF_URL).promise.then(doc => {
  pdfDoc = doc;
  renderPage(1);
}).catch(err => {
  document.getElementById('pdfWrap').innerHTML = '<div class="alert alert-error">Could not load PDF: ' + err.message + '</div>';
});
</script>

<?php require_once 'includes/footer.php'; renderFooter(); ?>
