<?php
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/config/auth.php';

requireLogin();

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$db = getDB();

$stmt = $db->prepare("SELECT b.*, a.nama as nama_anggota FROM berkas_pinjaman b 
                      JOIN anggota a ON b.anggota_id = a.id 
                      WHERE b.id = ?");
$stmt->execute([$id]);
$berkas = $stmt->fetch();

if (!$berkas) {
    die("Berkas tidak ditemukan.");
}

$filePath = 'uploads/berkas_pinjaman/' . $berkas['file_path'];
if (!file_exists($filePath)) {
    die("File fisik tidak ditemukan di server.");
}

$ext = strtolower(pathinfo($berkas['file_path'], PATHINFO_EXTENSION));
$isImage = in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp']);
$isPdf = ($ext === 'pdf');
$isWord = in_array($ext, ['docx', 'doc']);

include __DIR__ . '/includes/header.php';
?>

<div class="content">
    <div class="card">
        <div class="card-header">
            <div class="d-flex align-items-center gap-3">
                <a href="<?= APP_URL ?>/includes/upload_berkas.php" class="btn btn-icon btn-outline" title="Kembali">
                    <i class="fas fa-arrow-left"></i>
                </a>
                <div>
                    <h2 class="mb-0"><?= htmlspecialchars($berkas['nama_berkas']) ?></h2>
                    <p class="text-muted mb-0" style="font-size: 0.8rem;">
                        Milik: <strong><?= htmlspecialchars($berkas['nama_anggota']) ?></strong> | 
                        Tipe: <?= strtoupper($ext) ?> | 
                        Ukuran: <?= round($berkas['file_size'] / 1024, 2) ?> KB
                    </p>
                </div>
            </div>
            <div class="action-buttons">
                <a href="<?= $filePath ?>" download="<?= htmlspecialchars($berkas['nama_berkas']) ?>" class="btn btn-success btn-sm">
                    <i class="fas fa-download"></i> Download
                </a>
            </div>
        </div>
        <div class="card-body" style="background: #f8fafc; min-height: 600px; display: flex; flex-direction: column; align-items: center; padding: 20px;">
            
            <?php if ($isImage): ?>
                <div class="viewer-container" style="background: white; padding: 10px; border-radius: 8px; box-shadow: 0 4px 15px rgba(0,0,0,0.1); max-width: 100%;">
                    <img src="<?= $filePath ?>" alt="Pratinjau Berkas" style="max-width: 100%; height: auto; display: block; border-radius: 4px;">
                </div>

            <?php elseif ($isPdf): ?>
                <iframe src="<?= $filePath ?>" style="width: 100%; height: 800px; border: none; border-radius: 8px; box-shadow: 0 4px 15px rgba(0,0,0,0.1);"></iframe>

            <?php elseif ($isWord && $ext === 'docx'): ?>
                <div id="word-viewer" style="width: 100%; max-width: 850px; background: white; padding: 40px; border-radius: 4px; box-shadow: 0 4px 15px rgba(0,0,0,0.1); font-family: 'Georgia', serif; line-height: 1.6;">
                    <div id="output" style="min-height: 400px;">
                        <div class="text-center py-5">
                            <i class="fas fa-circle-notch fa-spin fa-2x text-primary mb-3"></i>
                            <p>Mempersiapkan pratinjau dokumen...</p>
                        </div>
                    </div>
                </div>
                <!-- Word Rendering Library -->
                <script src="https://cdnjs.cloudflare.com/ajax/libs/mammoth/1.4.21/mammoth.browser.min.js"></script>
                <script>
                    const fileUrl = '<?= $filePath ?>';
                    fetch(fileUrl)
                        .then(response => response.arrayBuffer())
                        .then(arrayBuffer => {
                            if (arrayBuffer.byteLength === 0) throw new Error("File kosong");
                            return mammoth.convertToHtml({arrayBuffer: arrayBuffer});
                        })
                        .then(result => {
                            document.getElementById('output').innerHTML = result.value;
                            if (result.messages.length > 0) {
                                console.log('Mammoth messages:', result.messages);
                            }
                        })
                        .catch(err => {
                            console.error('Error viewing docx:', err);
                            document.getElementById('output').innerHTML = `
                                <div class="alert alert-danger">
                                    <i class="fas fa-exclamation-triangle"></i> Gagal menampilkan pratinjau Word. <br>
                                    Silakan gunakan tombol <strong>Download</strong> untuk melihat berkas ini.
                                </div>
                            `;
                        });
                </script>

            <?php else: ?>
                <div class="text-center py-5" style="max-width: 500px;">
                    <div style="width: 80px; height: 80px; background: var(--gray-100); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 20px;">
                        <i class="fas fa-file-alt fa-3x text-gray-400"></i>
                    </div>
                    <h3>Pratinjau Tidak Tersedia</h3>
                    <p class="text-muted">Maaf, pratinjau langsung tidak tersedia untuk format file <strong>.<?= $ext ?></strong>. Silakan unduh berkas untuk melihat isinya.</p>
                    <a href="<?= $filePath ?>" download class="btn btn-primary mt-3">
                        <i class="fas fa-download"></i> Klik untuk Download
                    </a>
                </div>
            <?php endif; ?>

            <?php if ($berkas['keterangan']): ?>
                <div style="width: 100%; max-width: 850px; margin-top: 20px; padding: 15px; background: rgba(59, 130, 246, 0.05); border-left: 4px solid var(--primary-500); border-radius: 0 8px 8px 0;">
                    <h5 style="margin-bottom: 5px; color: var(--primary-700); font-weight: 700;">Keterangan Berkas:</h5>
                    <p style="margin-bottom: 0; color: var(--gray-700); font-style: italic;"><?= nl2br(htmlspecialchars($berkas['keterangan'])) ?></p>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<style>
/* Style adjustments for Word output */
#output h1, #output h2, #output h3 {
    margin-top: 1.5em;
    margin-bottom: 0.5em;
    color: #1e293b;
}
#output p {
    margin-bottom: 1em;
}
#output table {
    width: 100%;
    border-collapse: collapse;
    margin: 1.5em 0;
}
#output table td, #output table th {
    border: 1px solid #e2e8f0;
    padding: 8px 12px;
}
</style>

<?php include __DIR__ . '/includes/footer.php'; ?>
