<?php
/* ============================================================================
 *  staff/view_doc.php — view a staff member's own document (Contract or CV)
 *  with a Back button, so it isn't a dead-end. The path is looked up from the
 *  logged-in user's own record (never taken from the URL) for safety.
 *  Usage: view_doc.php?d=contract   or   view_doc.php?d=cv
 * ==========================================================================*/
session_start();
if (!isset($_SESSION["user_id"]) || empty($_SESSION["company_id"])) {
    header("Location: ../auth/login.php"); exit;
}
require_once '../config/database.php';

$userId    = (int)$_SESSION["user_id"];
$companyId = (int)$_SESSION["company_id"];
$which     = ($_GET['d'] ?? '') === 'cv' ? 'cv' : 'contract';

$col = $which === 'cv' ? 'cv_file' : 'contract_file';
$st = $pdo->prepare("SELECT $col AS f FROM company_staff WHERE user_id=? AND company_id=? LIMIT 1");
$st->execute([$userId, $companyId]);
$path = $st->fetchColumn();

$titleEn = $which === 'cv' ? 'CV / Resume' : 'Contract';
$titleLo = $which === 'cv' ? 'ປະຫວັດ (CV)' : 'ສັນຍາ';
$ext = $path ? strtolower(pathinfo($path, PATHINFO_EXTENSION)) : '';
$isImg = in_array($ext, ['jpg','jpeg','png','webp','gif']);
$isPdf = $ext === 'pdf';
$webPath = $path ? '../'.htmlspecialchars($path) : '';
?>
<!DOCTYPE html>
<html lang="lo">
<head>
    <?php $pwaTheme='#0f766e'; include __DIR__.'/../config/pwa_head.php'; ?>
    <title><?= htmlspecialchars($titleEn) ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Lao:wght@400;500;600;700;800&family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <script src="../assets/lang.js" defer></script>
    <style>
        *,*::before,*::after{box-sizing:border-box;margin:0;padding:0;}
        :root{--primary:#0f766e;--surface:#fff;--bg:#f0f4f8;--border:#e2e8f0;--text:#0f172a;--muted:#64748b;}
        html,body{height:100%;}
        body{font-family:"Noto Sans Lao","Inter",Arial,sans-serif;background:var(--bg);color:var(--text);display:flex;flex-direction:column;min-height:100vh;}
        .top-bar{background:var(--surface);border-bottom:1px solid var(--border);
            padding:calc(12px + env(safe-area-inset-top,0px)) 16px 12px;display:flex;justify-content:space-between;
            align-items:center;gap:10px;position:sticky;top:0;z-index:100;box-shadow:0 1px 6px rgba(15,23,42,.06);flex-shrink:0;}
        .back-link{display:inline-flex;align-items:center;gap:6px;background:var(--primary);color:#fff;
            padding:9px 16px;border-radius:9px;text-decoration:none;font-size:14px;font-weight:800;}
        .ttl{font-size:14px;font-weight:800;}
        .dl{background:#f1f5f9;color:var(--text);border:1.5px solid var(--border);padding:8px 13px;border-radius:8px;text-decoration:none;font-size:12px;font-weight:700;}
        .viewer{flex:1;display:flex;align-items:center;justify-content:center;padding:14px;overflow:auto;}
        .viewer img{max-width:100%;height:auto;border-radius:10px;box-shadow:0 2px 14px rgba(15,23,42,.12);}
        .empty{text-align:center;color:var(--muted);padding:40px 20px;}
        .empty .ic{font-size:54px;margin-bottom:12px;}
        .openbtn{display:inline-block;margin-top:16px;background:var(--primary);color:#fff;text-decoration:none;padding:12px 20px;border-radius:10px;font-weight:800;}
        /* PDF: vertically scrollable stack of all pages */
        .pdfscroll{flex:1;overflow:auto;padding:12px;display:flex;flex-direction:column;align-items:center;gap:12px;-webkit-overflow-scrolling:touch;}
        .pdfscroll canvas{width:100%;max-width:820px;height:auto;border-radius:8px;box-shadow:0 2px 12px rgba(15,23,42,.14);background:#fff;}
        .pdfmsg{color:var(--muted);font-size:13px;padding:20px;text-align:center;}
    </style>
</head>
<body>

<div class="top-bar">
    <a class="back-link" href="my_information.php">← <span data-lo="ກັບຄືນ" data-en="Back">Back</span></a>
    <span class="ttl" data-lo="<?= $titleLo ?>" data-en="<?= $titleEn ?>"><?= htmlspecialchars($titleEn) ?></span>
    <span></span>
</div>

<?php if ($isPdf): ?>
    <div id="pdfScroll" class="pdfscroll" data-url="<?= $webPath ?>">
        <div class="pdfmsg" data-lo="ກຳລັງໂຫລດ…" data-en="Loading…">Loading…</div>
    </div>
<?php else: ?>
<div class="viewer">
    <?php if (!$path): ?>
        <div class="empty">
            <div class="ic">📄</div>
            <div data-lo="ຍັງບໍ່ມີໄຟລ໌." data-en="No file uploaded yet.">No file uploaded yet.</div>
            <a class="openbtn" href="my_information.php" data-lo="ກັບຄືນ" data-en="Back">Back</a>
        </div>
    <?php elseif ($isImg): ?>
        <img src="<?= $webPath ?>" alt="">
    <?php else: ?>
        <div class="empty">
            <div class="ic">📎</div>
            <div data-lo="ໄຟລ໌ນີ້ບໍ່ສາມາດສະແດງໃນໜ້ານີ້." data-en="This file can't preview here.">This file can't preview here.</div>
            <a class="openbtn" href="<?= $webPath ?>" target="_blank" data-lo="ເປີດ / ດາວໂຫລດ" data-en="Open / Download">Open / Download</a>
        </div>
    <?php endif; ?>
</div>
<?php endif; ?>

<?php if ($isPdf): ?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>
<script>
(function(){
    var container = document.getElementById('pdfScroll');
    var url = container.dataset.url;
    if (!window.pdfjsLib) {
        container.innerHTML = '<div class="pdfmsg">Could not load PDF viewer. <a href="'+url+'" target="_blank">Open / Download</a></div>';
        return;
    }
    pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';
    var dpr = Math.min(window.devicePixelRatio || 1, 2);
    var maxW = Math.min((container.clientWidth || 360) - 24, 820);

    pdfjsLib.getDocument(url).promise.then(function(pdf){
        container.innerHTML = '';
        var chain = Promise.resolve();
        for (var i = 1; i <= pdf.numPages; i++) {
            (function(num){
                chain = chain.then(function(){
                    return pdf.getPage(num).then(function(page){
                        var base = page.getViewport({scale: 1});
                        var scale = (maxW / base.width) * dpr;
                        var vp = page.getViewport({scale: scale});
                        var canvas = document.createElement('canvas');
                        canvas.width = vp.width; canvas.height = vp.height;
                        canvas.style.width = maxW + 'px';
                        container.appendChild(canvas);
                        return page.render({canvasContext: canvas.getContext('2d'), viewport: vp}).promise;
                    });
                });
            })(i);
        }
        return chain;
    }).catch(function(e){
        container.innerHTML = '<div class="pdfmsg">Could not display PDF.<br><a class="openbtn" href="'+url+'" target="_blank">Open / Download</a></div>';
    });
})();
</script>
<?php endif; ?>

<?php require __DIR__ . '/../config/auto_update.php'; ?>
</body>
</html>