<?php
// modules/google_drive_frame.php
error_reporting(E_ALL);
ini_set('display_errors', 1);

if (!function_exists('e')) {
    function e($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

// Ganti dengan URL Web App Apps Script kamu
$appsScriptUrl = 'https://script.google.com/macros/s/AKfycbxG3ayJHkH8Wm36uMOG-J9rI_0jdROZs-F7FWXF7hXRrepQIUPr0SO-5f7EAzzz1rqthA/exec';

// Shortcut folder untuk frame.
// SPO Keperawatan memakai URL Apps Script default.
// PPI memakai query folder_id agar Apps Script membuka folder PPI.
$ppiFolderId = '1NMzW1tMFj838-P0QVYq1xRbmS4wEd6dL';

function driveFrameUrl(string $baseUrl, string $folderId = ''): string
{
    if (trim($baseUrl) === '') {
        return '';
    }

    if ($folderId === '') {
        return $baseUrl;
    }

    $separator = str_contains($baseUrl, '?') ? '&' : '?';
    return $baseUrl . $separator . http_build_query(['folder_id' => $folderId]);
}

$driveFrameSources = [
    [
        'title' => 'SPO Keperawatan',
        'subtitle' => 'Folder utama SPO Keperawatan',
        'url' => driveFrameUrl($appsScriptUrl),
        'icon' => 'fa-book-medical',
        'class' => 'from-blue-600 to-indigo-700',
    ],
    [
        'title' => 'PPI',
        'subtitle' => 'Folder PPI / Pencegahan dan Pengendalian Infeksi',
        'url' => driveFrameUrl($appsScriptUrl, $ppiFolderId),
        'icon' => 'fa-shield-virus',
        'class' => 'from-emerald-600 to-teal-700',
    ],
];

$defaultDriveFrameUrl = $driveFrameSources[0]['url'];
?>

<div class="w-full">
    <div class="bg-white rounded-3xl shadow-xl overflow-hidden border border-slate-200">
        <div class="px-5 py-4 border-b border-slate-200 bg-gradient-to-r from-slate-50 to-blue-50 flex items-center justify-between gap-3 flex-wrap">
            <div class="flex items-center gap-3">
                <div class="w-11 h-11 rounded-2xl bg-gradient-to-br from-blue-600 to-indigo-600 text-white flex items-center justify-center shadow-lg">
                    <i class="fas fa-folder-open"></i>
                </div>
                <div>
                    <h2 class="text-lg font-bold text-slate-800">Google Drive Reader</h2>
                    <p class="text-sm text-slate-500">SPO Keperawatan dan PPI ditampilkan dari Apps Script di dalam frame portal</p>
                </div>
            </div>

            <div class="flex items-center gap-2 flex-wrap">
                <button
                    type="button"
                    onclick="refreshDriveFrame()"
                    class="inline-flex items-center gap-2 px-4 py-2 rounded-xl bg-slate-100 text-slate-700 hover:bg-slate-200 text-sm font-medium"
                >
                    <i class="fas fa-rotate-right"></i>
                    Refresh
                </button>

                <a
                    id="driveOpenFullPage"
                    href="<?= e($defaultDriveFrameUrl) ?>"
                    target="_blank"
                    rel="noopener noreferrer"
                    class="inline-flex items-center gap-2 px-4 py-2 rounded-xl bg-blue-600 text-white hover:bg-blue-700 text-sm font-medium"
                >
                    <i class="fas fa-up-right-from-square"></i>
                    Buka Full Page
                </a>
            </div>
        </div>

        <div class="p-5 grid grid-cols-1 md:grid-cols-2 gap-4 border-b border-slate-100 bg-slate-50/60">
            <?php foreach ($driveFrameSources as $index => $source): ?>
                <button
                    type="button"
                    onclick="switchDriveSource('<?= e($source['url']) ?>', '<?= e(addslashes((string)$source['title'])) ?>', this)"
                    class="drive-source-card text-left rounded-3xl border <?= $index === 0 ? 'border-blue-300 ring-4 ring-blue-100 bg-white' : 'border-slate-200 bg-white' ?> shadow-sm hover:shadow-md transition p-4"
                    data-drive-source="<?= $index ?>"
                >
                    <div class="flex items-center gap-4">
                        <div class="w-12 h-12 rounded-2xl bg-gradient-to-br <?= e($source['class']) ?> text-white flex items-center justify-center shadow">
                            <i class="fas <?= e($source['icon']) ?>"></i>
                        </div>
                        <div class="flex-1">
                            <div class="font-bold text-slate-800"><?= e($source['title']) ?></div>
                            <div class="text-sm text-slate-500"><?= e($source['subtitle']) ?></div>
                        </div>
                        <i class="fas fa-arrow-right text-slate-300"></i>
                    </div>
                </button>
            <?php endforeach; ?>
        </div>

        <?php if ($appsScriptUrl === 'ISI_URL_WEB_APP_APPS_SCRIPT_KAMU' || trim($appsScriptUrl) === ''): ?>
            <div class="p-6">
                <div class="bg-red-50 border-l-4 border-red-500 text-red-700 p-4 rounded-xl">
                    URL Apps Script belum diisi di <strong>modules/google_drive_frame.php</strong>
                </div>
            </div>
        <?php else: ?>
            <div class="relative bg-slate-100">
                <div
                    id="driveFrameLoader"
                    class="absolute inset-0 z-10 flex items-center justify-center bg-white/80 backdrop-blur-sm"
                >
                    <div class="text-center">
                        <div class="w-14 h-14 mx-auto mb-4 rounded-full border-4 border-blue-200 border-t-blue-600 animate-spin"></div>
                        <div class="text-slate-700 font-semibold">Memuat Google Drive Reader...</div>
                        <div class="text-sm text-slate-500 mt-1">Mohon tunggu sebentar</div>
                    </div>
                </div>

                <iframe
                    id="driveAppFrame"
                    src="<?= e($defaultDriveFrameUrl) ?>"
                    class="w-full border-0 bg-white"
                    style="height: calc(100vh - 220px); min-height: 780px;"
                    allow="fullscreen"
                    loading="lazy"
                    onload="hideDriveFrameLoader()"
                ></iframe>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
function hideDriveFrameLoader() {
    const loader = document.getElementById('driveFrameLoader');
    if (loader) {
        loader.style.display = 'none';
    }
}

function showDriveFrameLoader() {
    const loader = document.getElementById('driveFrameLoader');
    if (loader) {
        loader.style.display = 'flex';
    }
}

function switchDriveSource(url, title, sourceButton) {
    const frame = document.getElementById('driveAppFrame');
    const openFullPage = document.getElementById('driveOpenFullPage');

    if (openFullPage) {
        openFullPage.href = url;
    }

    document.querySelectorAll('.drive-source-card').forEach(function(card) {
        card.classList.remove('border-blue-300', 'ring-4', 'ring-blue-100');
        card.classList.add('border-slate-200');
    });

    if (sourceButton) {
        sourceButton.classList.remove('border-slate-200');
        sourceButton.classList.add('border-blue-300', 'ring-4', 'ring-blue-100');
    }

    if (!frame) {
        window.open(url, '_blank', 'noopener,noreferrer');
        return;
    }

    showDriveFrameLoader();
    frame.src = url;
}

function refreshDriveFrame() {
    const frame = document.getElementById('driveAppFrame');
    if (!frame) return;

    showDriveFrameLoader();
    frame.src = frame.src;
}

// fallback jaga-jaga kalau onload telat / gagal trigger cepat
window.addEventListener('load', function () {
    setTimeout(function () {
        hideDriveFrameLoader();
    }, 4000);
});
</script>