<?php
function encodeFile($filename) {
    return rtrim(strtr(base64_encode($filename), '+/', '-_'), '=');
}
function decodeFile($encoded) {
    return base64_decode(strtr($encoded, '-_', '+/'));
}

// MODE STREAM PDF (supaya URL asli tidak kelihatan)
if (isset($_GET['pdfstream'])) {
    $file = decodeFile($_GET['pdfstream']);
    if (!file_exists($file) || pathinfo($file, PATHINFO_EXTENSION) !== 'pdf') {
        http_response_code(404);
        exit("File tidak ditemukan.");
    }
    header('Content-Type: application/pdf');
    header('Content-Disposition: inline; filename="'.basename($file).'"');
    readfile($file);
    exit;
}

// MODE VIEWER
if (isset($_GET['view'])) {
    $file = decodeFile($_GET['view']);
    if (!file_exists($file) || pathinfo($file, PATHINFO_EXTENSION) !== 'pdf') {
        die("File tidak ditemukan.");
    }
    $pdfStreamUrl = '?pdfstream=' . encodeFile($file);
    ?>
    <!DOCTYPE html>
    <html lang="id">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Baca E-Paper</title>
        <style>
            body { margin: 0; font-family: Arial, sans-serif; background: #000; }
            .topbar {
                position: fixed;
                top: 0; left: 0; right: 0;
                background: #0077b6;
                color: white;
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 8px 12px;
                box-shadow: 0 2px 6px rgba(0,0,0,0.2);
                z-index: 1000;
                transition: top 0.3s;
            }
            .topbar button {
                background: rgba(255,255,255,0.2);
                border: none;
                color: white;
                padding: 6px 12px;
                border-radius: 4px;
                font-size: 14px;
                cursor: pointer;
            }
            #viewerContainer {
                position: absolute;
                top: 48px; bottom: 0; left: 0; right: 0;
                overflow-y: auto;
                background: #444;
            }
            canvas {
                display: block;
                margin: 10px auto;
                max-width: 100%;
                height: auto;
                background: #fff;
            }
            /* Loading overlay */
            #loadingOverlay {
                position: fixed;
                top: 0; left: 0; right: 0; bottom: 0;
                background: rgba(0,0,0,0.6);
                display: flex;
                justify-content: center;
                align-items: center;
                z-index: 2000;
                color: white;
                font-size: 18px;
                flex-direction: column;
            }
            .loader {
                border: 6px solid #f3f3f3;
                border-top: 6px solid #3498db;
                border-radius: 50%;
                width: 50px;
                height: 50px;
                animation: spin 1s linear infinite;
                margin-bottom: 10px;
            }
            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
        </style>
    </head>
    <body>
        <div class="topbar" id="topbar">
            <button onclick="window.location='./'">← Kembali</button>
        </div>

        <div id="viewerContainer"></div>

        <div id="loadingOverlay">
            <div class="loader"></div>
            Memuat PDF...
        </div>

        <!-- PDF.js -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>
        <script>
            const url = "<?php echo $pdfStreamUrl; ?>";
            const container = document.getElementById('viewerContainer');

            let pdfDoc = null;
            pdfjsLib.getDocument({ url }).promise.then(function(pdf) {
                pdfDoc = pdf;
                for (let i = 1; i <= pdfDoc.numPages; i++) {
                    renderPage(i);
                }
            }).then(() => {
                document.getElementById('loadingOverlay').style.display = 'none';
            });

            function renderPage(num) {
                pdfDoc.getPage(num).then(function(page) {
                    const viewport = page.getViewport({ scale: 1.3 });
                    const canvas = document.createElement('canvas');
                    const ctx = canvas.getContext('2d');
                    canvas.height = viewport.height;
                    canvas.width = viewport.width;
                    container.appendChild(canvas);
                    page.render({ canvasContext: ctx, viewport: viewport });
                });
            }

            // Sembunyikan topbar saat scroll ke bawah
            let prevScroll = 0;
            container.addEventListener('scroll', () => {
                const topbar = document.getElementById('topbar');
                let currScroll = container.scrollTop;
                if (currScroll > prevScroll) {
                    topbar.style.top = "-60px";
                } else {
                    topbar.style.top = "0";
                }
                prevScroll = currScroll;
            });
        </script>
    </body>
    </html>
    <?php
    exit;
}

// MODE HOME
$files = glob("*.jpg");
$firstFile = $files[0] ?? '';
preg_match('/_(\d{8})/', $firstFile, $match);
$dateStr = $match[1] ?? date('Ymd');
$timestamp = DateTime::createFromFormat('Ymd', $dateStr);
$hari = [
    'Sunday' => 'MINGGU', 'Monday' => 'SENIN', 'Tuesday' => 'SELASA',
    'Wednesday' => 'RABU', 'Thursday' => 'KAMIS', 'Friday' => 'JUMAT', 'Saturday' => 'SABTU'
];
$bulan = [
    1 => 'JANUARI', 2 => 'FEBRUARI', 3 => 'MARET', 4 => 'APRIL',
    5 => 'MEI', 6 => 'JUNI', 7 => 'JULI', 8 => 'AGUSTUS',
    9 => 'SEPTEMBER', 10 => 'OKTOBER', 11 => 'NOVEMBER', 12 => 'DESEMBER'
];
$titleDate = $hari[$timestamp->format('l')] . ", " . $timestamp->format('d') . " " .
             $bulan[(int)$timestamp->format('m')] . " " . $timestamp->format('Y');
$pageTitle = "EPAPER EDISI: $titleDate";
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo $pageTitle; ?></title>
<meta property="og:title" content="<?php echo $pageTitle; ?>">
<meta property="og:type" content="website">
<meta property="og:image" content="<?php echo htmlspecialchars($files[0] ?? ''); ?>">
<meta property="og:description" content="Baca e-paper edisi ini dengan mudah dan cepat.">
<style>
    body { font-family: Arial, sans-serif; margin: 0; background: #f5f5f5; }
    h1 {
        text-align: center;
        padding: 15px;
        background: #0077b6;
        color: white;
        margin: 0;
        font-size: 16px;
    }
    .container {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
        gap: 15px;
        padding: 15px;
    }
    @media (max-width: 600px) {
        .container { grid-template-columns: 1fr; }
        .thumb { height: auto !important; object-fit: contain !important; }
    }
    .card {
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 6px rgba(0,0,0,0.1);
        overflow: hidden;
        transition: transform 0.2s ease;
    }
    .card:hover { transform: scale(1.03); }
    .thumb {
        width: 100%;
        height: 200px;
        object-fit: cover;
    }
    .title {
        padding: 10px;
        font-size: 14px;
        text-align: center;
        background: #fafafa;
    }
    .btn {
        display: block;
        background: #0077b6;
        color: white;
        text-decoration: none;
        padding: 8px;
        text-align: center;
        font-size: 14px;
        border-radius: 0 0 8px 8px;
    }
    .btn:hover { background: #023e8a; }
</style>
</head>
<body>

<h1><?php echo $pageTitle; ?></h1>
<div class="container">
<?php foreach($files as $jpg): 
    $pdf = str_replace(".jpg", ".pdf", $jpg);
    $title = strtoupper(str_replace("_", " ", pathinfo($jpg, PATHINFO_FILENAME)));
?>
    <div class="card">
        <img src="<?php echo htmlspecialchars($jpg); ?>" alt="<?php echo $title; ?>" class="thumb" loading="lazy">
        <div class="title"><?php echo $title; ?></div>
        <?php if (file_exists($pdf)): ?>
            <a class="btn" href="?view=<?php echo encodeFile($pdf); ?>">Baca PDF</a>
        <?php else: ?>
            <div style="padding:8px; text-align:center; color:#888;">PDF Tidak Ada</div>
        <?php endif; ?>
    </div>
<?php endforeach; ?>
</div>

</body>
</html>
