<?php
declare(strict_types=1);

define('APP_ROOT', dirname(__DIR__, 2));
if (session_status() === PHP_SESSION_NONE) session_start();

require_once APP_ROOT . '/includes/admin_auth.php';
require_once APP_ROOT . '/includes/db.php';

$mysqli = $mysqli ?? ($conn ?? null);
if (!$mysqli instanceof mysqli) exit('DB connection failed');

$submission_id = (int)($_GET['submission_id'] ?? 0);
$assessment_id = (int)($_GET['assessment_id'] ?? 0);
$batch_id      = (int)($_GET['batch_id'] ?? 0);

if ($submission_id <= 0) exit('Invalid submission');

$stmt = $mysqli->prepare("
    SELECT 
        s.id,
        s.file_path,
        s.corrected_file_path,
        s.final_score,
        s.feedback,
        s.workflow_status,
        st.full_name,
        st.center_reg_no
    FROM lms_submissions s
    LEFT JOIN studentss st ON st.id = s.student_id
    WHERE s.id = ?
    LIMIT 1
");
$stmt->bind_param('i', $submission_id);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$row || empty($row['file_path'])) exit('PDF not found');

$sourcePath = !empty($row['corrected_file_path']) ? $row['corrected_file_path'] : $row['file_path'];
$pdfUrl = '/elms/' . ltrim((string)$sourcePath, '/');

$backUrl = 'submissions.php?assessment_id=' . $assessment_id . '&batch_id=' . $batch_id;

function h($v): string {
    return htmlspecialchars((string)$v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Mark / Grade PDF</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>
<script src="https://unpkg.com/pdf-lib/dist/pdf-lib.min.js"></script>

<style>
*{box-sizing:border-box}
body{
    margin:0;
    background:#0f172a;
    font-family:Arial, sans-serif;
    color:#111827;
}
.topbar{
    position:sticky;
    top:0;
    z-index:50;
    background:#fff;
    border-bottom:1px solid #e5e7eb;
    padding:12px 16px;
    display:grid;
    grid-template-columns:1fr auto;
    gap:12px;
    align-items:center;
}
.title{
    font-weight:900;
    font-size:16px;
}
.sub{
    font-size:12px;
    color:#64748b;
    margin-top:2px;
}
.tools{
    display:flex;
    gap:8px;
    flex-wrap:wrap;
    justify-content:flex-end;
    align-items:center;
}
.btn{
    border:0;
    border-radius:999px;
    padding:10px 15px;
    font-weight:800;
    cursor:pointer;
}
.btn-dark{background:#111827;color:#fff}
.btn-red{background:#dc2626;color:#fff}
.btn-green{background:#16a34a;color:#fff}
.btn-light{background:#e5e7eb;color:#111827}
.btn-blue{background:#2563eb;color:#fff}
.btn-yellow{background:#f59e0b;color:#111827}
.btn.active{outline:3px solid rgba(37,99,235,.25)}
.input,.select{
    border:1px solid #d1d5db;
    border-radius:12px;
    padding:9px 10px;
    font-weight:700;
}
.input.small{width:90px}
.input.feedback{width:260px}
.wrap{
    padding:22px;
    text-align:center;
}
.pageBox{
    position:relative;
    display:inline-block;
    background:#fff;
    margin:0 auto 22px;
    box-shadow:0 18px 45px rgba(0,0,0,.35);
}
.pdfCanvas{display:block}
.drawLayer{
    position:absolute;
    left:0;
    top:0;
    z-index:10;
    cursor:crosshair;
}
.textBox{
    position:absolute;
    z-index:20;
    min-width:80px;
    min-height:26px;
    border:1px dashed #dc2626;
    color:#dc2626;
    background:rgba(255,255,255,.55);
    font-size:18px;
    font-weight:700;
    padding:3px 5px;
    outline:none;
}
.status{
    position:fixed;
    right:18px;
    bottom:18px;
    z-index:80;
    background:#111827;
    color:#fff;
    padding:12px 16px;
    border-radius:16px;
    display:none;
}
@media(max-width:900px){
    .topbar{grid-template-columns:1fr}
    .tools{justify-content:flex-start}
    .input.feedback{width:100%}
}
</style>
</head>

<body>

<div class="topbar">
    <div>
        <div class="title">Mark / Grade PDF</div>
        <div class="sub">
            <?= h($row['full_name'] ?? 'Student') ?> · <?= h($row['center_reg_no'] ?? '') ?>
        </div>
    </div>

    <div class="tools">
        <a class="btn btn-light" href="<?= h($backUrl) ?>" style="text-decoration:none;">Back</a>

        <button class="btn btn-red active" id="penBtn" onclick="setTool('pen')">Pen</button>
        <button class="btn btn-yellow" id="textBtn" onclick="setTool('text')">Text</button>
        <button class="btn btn-light" onclick="clearMarks()">Clear</button>

        <input id="scoreInput" class="input small" type="number" step="0.01" min="0"
               placeholder="Marks" value="<?= h($row['final_score'] ?? '') ?>">

        <select id="statusInput" class="select">
            <?php
            $statuses = [
                'submitted' => 'Submitted',
                'under_review' => 'Under Review',
                'needs_correction' => 'Needs Correction',
                'marked' => 'Marked',
                'coord_approved' => 'Coordinator Approved',
                'released' => 'Released',
            ];
            $cur = (string)($row['workflow_status'] ?? 'marked');
            foreach ($statuses as $k => $v):
            ?>
                <option value="<?= h($k) ?>" <?= $cur === $k ? 'selected' : '' ?>><?= h($v) ?></option>
            <?php endforeach; ?>
        </select>

        <input id="feedbackInput" class="input feedback" type="text"
               placeholder="Feedback" value="<?= h($row['feedback'] ?? '') ?>">

        <button class="btn btn-green" onclick="saveMarkedPdf()">Save Marked PDF</button>
    </div>
</div>

<div class="wrap" id="pdfWrap"></div>
<div class="status" id="statusBox">Saving...</div>

<script>
const pdfUrl = <?= json_encode($pdfUrl) ?>;
const submissionId = <?= (int)$submission_id ?>;
const assessmentId = <?= (int)$assessment_id ?>;
const batchId = <?= (int)$batch_id ?>;

pdfjsLib.GlobalWorkerOptions.workerSrc =
  "https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js";

let drawCanvases = [];
let pageBoxes = [];
let drawing = false;
let currentTool = 'pen';

function showStatus(msg) {
    const box = document.getElementById('statusBox');
    box.textContent = msg;
    box.style.display = 'block';
}

function hideStatus() {
    document.getElementById('statusBox').style.display = 'none';
}

function setTool(tool) {
    currentTool = tool;
    document.getElementById('penBtn').classList.toggle('active', tool === 'pen');
    document.getElementById('textBtn').classList.toggle('active', tool === 'text');
}

async function loadPdf() {
    showStatus('Loading PDF...');
    const pdf = await pdfjsLib.getDocument(pdfUrl).promise;
    const wrap = document.getElementById('pdfWrap');

    for (let p = 1; p <= pdf.numPages; p++) {
        const page = await pdf.getPage(p);
        const viewport = page.getViewport({ scale: 1.6 });

        const box = document.createElement('div');
        box.className = 'pageBox';
        box.dataset.pageIndex = String(p - 1);

        const pdfCanvas = document.createElement('canvas');
        pdfCanvas.className = 'pdfCanvas';
        pdfCanvas.width = viewport.width;
        pdfCanvas.height = viewport.height;

        const ctx = pdfCanvas.getContext('2d');
        await page.render({ canvasContext: ctx, viewport }).promise;

        const drawCanvas = document.createElement('canvas');
        drawCanvas.className = 'drawLayer';
        drawCanvas.width = viewport.width;
        drawCanvas.height = viewport.height;

        setupCanvas(drawCanvas, box);

        box.appendChild(pdfCanvas);
        box.appendChild(drawCanvas);
        wrap.appendChild(box);

        drawCanvases.push(drawCanvas);
        pageBoxes.push(box);
    }

    hideStatus();
}

function setupCanvas(canvas, box) {
    const ctx = canvas.getContext('2d');
    ctx.strokeStyle = 'red';
    ctx.lineWidth = 4;
    ctx.lineCap = 'round';
    ctx.lineJoin = 'round';

    canvas.addEventListener('mousedown', e => {
        if (currentTool === 'text') {
            addTextBox(box, e);
            return;
        }

        drawing = true;
        const r = canvas.getBoundingClientRect();
        ctx.beginPath();
        ctx.moveTo(e.clientX - r.left, e.clientY - r.top);
    });

    canvas.addEventListener('mousemove', e => {
        if (!drawing || currentTool !== 'pen') return;
        const r = canvas.getBoundingClientRect();
        ctx.lineTo(e.clientX - r.left, e.clientY - r.top);
        ctx.stroke();
    });

    window.addEventListener('mouseup', () => drawing = false);
}

function addTextBox(box, e) {
    const r = box.getBoundingClientRect();
    const text = document.createElement('div');
    text.className = 'textBox';
    text.contentEditable = 'true';
    text.innerText = 'Type here';
    text.style.left = (e.clientX - r.left) + 'px';
    text.style.top = (e.clientY - r.top) + 'px';

    text.addEventListener('dblclick', ev => {
        ev.stopPropagation();
        text.remove();
    });

    box.appendChild(text);
    text.focus();

    const range = document.createRange();
    range.selectNodeContents(text);
    const sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
}

function clearMarks() {
    drawCanvases.forEach(c => c.getContext('2d').clearRect(0, 0, c.width, c.height));
    document.querySelectorAll('.textBox').forEach(el => el.remove());
}

async function saveMarkedPdf() {
    try {
        showStatus('Saving marked PDF...');

        const existingPdfBytes = await fetch(pdfUrl).then(r => r.arrayBuffer());
        const pdfDoc = await PDFLib.PDFDocument.load(existingPdfBytes);
        const pages = pdfDoc.getPages();

        for (let i = 0; i < drawCanvases.length; i++) {
            const canvas = drawCanvases[i];
            const page = pages[i];
            const { width, height } = page.getSize();

            const pngDataUrl = canvas.toDataURL('image/png');
            const pngImage = await pdfDoc.embedPng(pngDataUrl);

            page.drawImage(pngImage, {
                x: 0,
                y: 0,
                width: width,
                height: height
            });

            const box = pageBoxes[i];
            const boxRect = box.getBoundingClientRect();
            const canvasRect = canvas.getBoundingClientRect();
            const scaleX = width / canvas.width;
            const scaleY = height / canvas.height;

            const textBoxes = box.querySelectorAll('.textBox');

            for (const tb of textBoxes) {
                const text = tb.innerText.trim();
                if (!text) continue;

                const left = parseFloat(tb.style.left || '0');
                const top = parseFloat(tb.style.top || '0');

                const fontSizePx = parseFloat(window.getComputedStyle(tb).fontSize || '18');
                const pdfFontSize = fontSizePx * scaleY;

                page.drawText(text, {
                    x: left * scaleX,
                    y: height - ((top + fontSizePx + 4) * scaleY),
                    size: pdfFontSize,
                    color: PDFLib.rgb(0.86, 0.04, 0.04),
                    maxWidth: width - (left * scaleX) - 20,
                    lineHeight: pdfFontSize + 4
                });
            }
        }

        const pdfBytes = await pdfDoc.save();

        const form = new FormData();
        form.append('submission_id', submissionId);
        form.append('assessment_id', assessmentId);
        form.append('batch_id', batchId);
        form.append('score', document.getElementById('scoreInput').value);
        form.append('workflow_status', document.getElementById('statusInput').value);
        form.append('feedback', document.getElementById('feedbackInput').value);
        form.append('pdf', new Blob([pdfBytes], {type:'application/pdf'}), 'marked.pdf');

        const res = await fetch('save_marked_pdf.php', {
            method: 'POST',
            body: form
        });

        const data = await res.json();

        if (data.ok) {
            showStatus('Saved successfully.');
            setTimeout(() => {
                window.location.href = 'submissions.php?assessment_id=' + assessmentId + '&batch_id=' + batchId;
            }, 700);
        } else {
            hideStatus();
            alert(data.message || 'Save failed');
        }
    } catch (err) {
        hideStatus();
        alert('Save failed: ' + err.message);
    }
}

loadPdf();
</script>

</body>
</html>