@extends('layouts.app')
@section('content')
<div class="container py-4">
    <h4 class="mb-3">PDF Viewer</h4>
    @if (!isset($pdfUrl) || empty($pdfUrl))
        <div class="alert alert-danger">PDF URL is not set. Please check your controller logic.</div>
    @else
        <div class="alert alert-info small">PDF Source: <code>{{ $pdfUrl }}</code></div>
    @endif
    <div id="pdf-viewer-container" style="border:1px solid #ccc; min-height:600px; background:#f8f9fa;">
        <canvas id="pdf-canvas" style="width:100%; max-width:900px;"></canvas>
    </div>
    <div class="mt-3">
        <button id="prev-page" class="btn btn-outline-primary btn-sm">Previous</button>
        <span id="page-info" class="mx-2">Page <span id="page-num">1</span> / <span id="page-count">1</span></span>
        <button id="next-page" class="btn btn-outline-primary btn-sm">Next</button>
    </div>
</div>
@endsection
@section('scripts')
<script src="{{ asset('assets/libs/pdfjs/pdf.min.js') }}"></script>
<script>
    pdfjsLib.GlobalWorkerOptions.workerSrc = '{{ asset('assets/libs/pdfjs/pdf.worker.min.js') }}';
    const url = "{{ $pdfUrl }}";
    let pdfDoc = null, pageNum = 1, pageRendering = false, pageNumPending = null;
    const scale = 1.2;
    const canvas = document.getElementById('pdf-canvas');
    const ctx = canvas.getContext('2d');
    function renderPage(num) {
        pageRendering = true;
        pdfDoc.getPage(num).then(function(page) {
            const viewport = page.getViewport({ scale: scale });
            canvas.height = viewport.height;
            canvas.width = viewport.width;
            const renderContext = {
                canvasContext: ctx,
                viewport: viewport
            };
            const renderTask = page.render(renderContext);
            renderTask.promise.then(function() {
                pageRendering = false;
                if (pageNumPending !== null) {
                    renderPage(pageNumPending);
                    pageNumPending = null;
                }
            });
        });
        document.getElementById('page-num').textContent = num;
    }
    function queueRenderPage(num) {
        if (pageRendering) {
            pageNumPending = num;
        } else {
            renderPage(num);
        }
    }
    function onPrevPage() {
        if (pageNum <= 1) return;
        pageNum--;
        queueRenderPage(pageNum);
    }
    function onNextPage() {
        if (pageNum >= pdfDoc.numPages) return;
        pageNum++;
        queueRenderPage(pageNum);
    }
    pdfjsLib.getDocument(url).promise.then(function(pdfDoc_) {
        pdfDoc = pdfDoc_;
        document.getElementById('page-count').textContent = pdfDoc.numPages;
        renderPage(pageNum);
    });
    document.getElementById('prev-page').addEventListener('click', onPrevPage);
    document.getElementById('next-page').addEventListener('click', onNextPage);
</script>
@endsection
