<?php
require_once '../config.php';

// Validasi input
$file = isset($_GET['f']) ? $_GET['f'] : '';
if (empty($file)) {
    die("Akses ditolak.");
}

// Hanya ambil basename untuk mencegah directory traversal
$filename = basename($file);
$filepath = '../uploads/' . $filename;

if (!file_exists($filepath)) {
    die("File tidak ditemukan di server.");
}

$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
$allowed_preview = ['pdf', 'jpg', 'jpeg', 'png'];

if (!in_array($ext, $allowed_preview)) {
    // Jika format tidak didukung untuk preview, paksakan download
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Content-Length: ' . filesize($filepath));
    readfile($filepath);
    exit;
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Preview Dokumen - <?= htmlspecialchars($filename) ?></title>
    <!-- Favicon agar logo aplikasi muncul di tab browser -->
    <link rel="icon" type="image/png" href="<?= base_url('logo/logo.png?v='.time()) ?>">
    <style>
        body, html {
            margin: 0;
            padding: 0;
            height: 100%;
            background-color: #333; /* Warna gelap agar fokus ke dokumen */
            display: flex;
            justify-content: center;
            align-items: center;
            font-family: sans-serif;
        }
        .container {
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
            box-shadow: 0 0 20px rgba(0,0,0,0.5);
        }
        iframe {
            width: 100%;
            height: 100%;
            border: none;
        }
        .error-msg {
            color: white;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="container">
        <?php if($ext === 'pdf'): ?>
            <iframe src="<?= htmlspecialchars($filepath) ?>"></iframe>
        <?php else: ?>
            <img src="<?= htmlspecialchars($filepath) ?>" alt="Preview Dokumen">
        <?php endif; ?>
    </div>
</body>
</html>
