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

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/app.php';

checkAuth();

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

$gasUrl = 'https://script.google.com/macros/s/AKfycbxG3ayJHkH8Wm36uMOG-J9rI_0jdROZs-F7FWXF7hXRrepQIUPr0SO-5f7EAzzz1rqthA/exec';

$search   = trim((string)($_GET['search'] ?? ''));
$type     = trim((string)($_GET['type'] ?? ''));
$folderId = trim((string)($_GET['folder_id'] ?? ''));

// Shortcut folder tetap di dalam modul ini.
// SPO Keperawatan memakai folder default dari Apps Script saat folder_id kosong.
// PPI diarahkan ke folder Google Drive yang diminta.
$ppiFolderId = '1NMzW1tMFj838-P0QVYq1xRbmS4wEd6dL';
$driveShortcutFolders = [
    [
        'key' => 'spo',
        'title' => 'SPO Keperawatan',
        'subtitle' => 'Folder utama SPO Keperawatan',
        'folder_id' => '',
        'icon' => 'fa-book-medical',
        'color' => 'from-blue-600 to-indigo-700',
    ],
    [
        'key' => 'ppi',
        'title' => 'PPI',
        'subtitle' => 'Folder PPI / Pencegahan dan Pengendalian Infeksi',
        'folder_id' => $ppiFolderId,
        'icon' => 'fa-shield-virus',
        'color' => 'from-emerald-600 to-teal-700',
    ],
];

function driveReaderUrl(string $folderId, string $search = '', string $type = ''): string
{
    $params = [
        'module' => 'google_drive_reader',
    ];

    if ($folderId !== '') {
        $params['folder_id'] = $folderId;
    }

    if ($search !== '') {
        $params['search'] = $search;
    }

    if ($type !== '') {
        $params['type'] = $type;
    }

    return '?' . http_build_query($params);
}


function httpGetJson(string $url): array
{
    $ch = curl_init($url);

    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_FOLLOWLOCATION => true,
    ]);

    $response    = curl_exec($ch);
    $error       = curl_error($ch);
    $httpCode    = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $contentType = (string)curl_getinfo($ch, CURLINFO_CONTENT_TYPE);

    curl_close($ch);

    if ($response === false || $error) {
        return [
            'success' => false,
            'message' => 'GET gagal: ' . $error,
        ];
    }

    $json = json_decode($response, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        return [
            'success' => false,
            'message' => 'Response bukan JSON valid. HTTP ' . $httpCode .
                ' | Content-Type: ' . $contentType .
                ' | Preview: ' . substr(strip_tags($response), 0, 300),
        ];
    }

    if ($httpCode >= 400) {
        return [
            'success' => false,
            'message' => $json['message'] ?? ('HTTP Error ' . $httpCode),
        ];
    }

    return is_array($json)
        ? $json
        : [
            'success' => false,
            'message' => 'Response JSON tidak valid',
        ];
}

function httpPostJson(string $url, array $payload): array
{
    $ch = curl_init($url);

    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 90,
        CURLOPT_CONNECTTIMEOUT => 15,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
        ],
        CURLOPT_POSTFIELDS => json_encode($payload),
    ]);

    $response    = curl_exec($ch);
    $error       = curl_error($ch);
    $httpCode    = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $contentType = (string)curl_getinfo($ch, CURLINFO_CONTENT_TYPE);

    curl_close($ch);

    if ($response === false || $error) {
        return [
            'success' => false,
            'message' => 'POST gagal: ' . $error,
        ];
    }

    $json = json_decode($response, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        return [
            'success' => false,
            'message' => 'Response bukan JSON valid. HTTP ' . $httpCode .
                ' | Content-Type: ' . $contentType .
                ' | Preview: ' . substr(strip_tags($response), 0, 300),
        ];
    }

    if ($httpCode >= 400) {
        return [
            'success' => false,
            'message' => $json['message'] ?? ('HTTP Error ' . $httpCode),
        ];
    }

    return is_array($json)
        ? $json
        : [
            'success' => false,
            'message' => 'Response JSON tidak valid',
        ];
}

function formatBytes($bytes): string
{
    $bytes = (float)$bytes;

    if ($bytes <= 0) {
        return '-';
    }

    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $power = (int)floor(log($bytes, 1024));
    $power = min($power, count($units) - 1);
    $value = $bytes / (1024 ** $power);

    return number_format($value, $power === 0 ? 0 : 2, ',', '.') . ' ' . $units[$power];
}

function fileTypeBadgeClass(string $type): string
{
    return match ($type) {
        'folder'   => 'bg-amber-100 text-amber-700',
        'pdf'      => 'bg-red-100 text-red-700',
        'image'    => 'bg-emerald-100 text-emerald-700',
        'video'    => 'bg-purple-100 text-purple-700',
        'document' => 'bg-blue-100 text-blue-700',
        'sheet'    => 'bg-green-100 text-green-700',
        'slide'    => 'bg-orange-100 text-orange-700',
        default    => 'bg-gray-100 text-gray-700',
    };
}

$alert = [
    'type' => '',
    'message' => '',
];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_file'])) {
    $postFolderId = trim((string)($_POST['folder_id'] ?? ''));

    if ($gasUrl === 'ISI_URL_GOOGLEUSERCONTENT_FULL_KAMU' || trim($gasUrl) === '') {
        $alert = [
            'type' => 'error',
            'message' => 'URL Google Apps Script belum diisi.',
        ];
    } elseif (!isset($_FILES['drive_file']) || !is_uploaded_file($_FILES['drive_file']['tmp_name'])) {
        $alert = [
            'type' => 'error',
            'message' => 'File upload tidak ditemukan.',
        ];
    } else {
        $tmpPath  = $_FILES['drive_file']['tmp_name'];
        $fileName = $_FILES['drive_file']['name'] ?? 'file-upload';
        $mimeType = $_FILES['drive_file']['type'] ?? 'application/octet-stream';
        $base64   = base64_encode((string)file_get_contents($tmpPath));

        $payload = [
            'action'           => 'upload',
            'file_name'        => $fileName,
            'mime_type'        => $mimeType,
            'file_data_base64' => $base64,
        ];

        if ($postFolderId !== '') {
            $payload['folder_id'] = $postFolderId;
        }

        $uploadResult = httpPostJson($gasUrl, $payload);

        if (!empty($uploadResult['success'])) {
            $alert = [
                'type' => 'success',
                'message' => 'File berhasil diupload ke Google Drive.',
            ];
        } else {
            $alert = [
                'type' => 'error',
                'message' => (string)($uploadResult['message'] ?? 'Upload gagal.'),
            ];
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_folder'])) {
    $postFolderId = trim((string)($_POST['folder_id'] ?? ''));
    $folderName   = trim((string)($_POST['folder_name'] ?? ''));

    if ($folderName === '') {
        $alert = [
            'type' => 'error',
            'message' => 'Nama folder wajib diisi.',
        ];
    } else {
        $payload = [
            'action'      => 'create_folder',
            'folder_name' => $folderName,
        ];

        if ($postFolderId !== '') {
            $payload['folder_id'] = $postFolderId;
        }

        $createResult = httpPostJson($gasUrl, $payload);

        if (!empty($createResult['success'])) {
            $alert = [
                'type' => 'success',
                'message' => 'Folder berhasil dibuat.',
            ];
        } else {
            $alert = [
                'type' => 'error',
                'message' => (string)($createResult['message'] ?? 'Gagal membuat folder.'),
            ];
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_file'])) {
    $fileIdDelete = trim((string)($_POST['file_id'] ?? ''));

    $deleteResult = httpPostJson($gasUrl, [
        'action'  => 'delete_file',
        'file_id' => $fileIdDelete,
    ]);

    if (!empty($deleteResult['success'])) {
        $alert = [
            'type' => 'success',
            'message' => 'File berhasil dihapus.',
        ];
    } else {
        $alert = [
            'type' => 'error',
            'message' => (string)($deleteResult['message'] ?? 'Gagal menghapus file.'),
        ];
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_folder'])) {
    $folderIdDelete = trim((string)($_POST['delete_folder_id'] ?? ''));

    $deleteFolderResult = httpPostJson($gasUrl, [
        'action'    => 'delete_folder',
        'folder_id' => $folderIdDelete,
    ]);

    if (!empty($deleteFolderResult['success'])) {
        $alert = [
            'type' => 'success',
            'message' => 'Folder berhasil dihapus.',
        ];
    } else {
        $alert = [
            'type' => 'error',
            'message' => (string)($deleteFolderResult['message'] ?? 'Gagal menghapus folder.'),
        ];
    }
}

$data = [
    'currentFolder' => ['id' => '', 'name' => 'Folder', 'parentId' => ''],
    'breadcrumbs'   => [],
    'folders'       => [],
    'files'         => [],
];

if ($gasUrl === 'ISI_URL_GOOGLEUSERCONTENT_FULL_KAMU' || trim($gasUrl) === '') {
    if ($alert['message'] === '') {
        $alert = [
            'type' => 'error',
            'message' => 'URL Google Apps Script belum diisi.',
        ];
    }
} else {
    $params = [
        'action' => 'list',
        'search' => $search,
        'type'   => $type,
    ];

    if ($folderId !== '') {
        $params['folder_id'] = $folderId;
    }

    $query = http_build_query($params);
    $separator = (strpos($gasUrl, '?') !== false) ? '&' : '?';
    $result = httpGetJson($gasUrl . $separator . $query);

    if (!empty($result['success'])) {
        $data = $result['data'] ?? $data;
    } elseif ($alert['message'] === '') {
        $alert = [
            'type' => 'error',
            'message' => (string)($result['message'] ?? 'Gagal memuat data Google Drive.'),
        ];
    }
}

$currentFolder = $data['currentFolder'] ?? ['id' => '', 'name' => 'Folder', 'parentId' => ''];
$breadcrumbs   = $data['breadcrumbs'] ?? [];
$folders       = $data['folders'] ?? [];
$files         = $data['files'] ?? [];

$typeOptions = [
    ''         => 'Semua Tipe',
    'folder'   => 'Folder',
    'pdf'      => 'PDF',
    'image'    => 'Gambar',
    'video'    => 'Video',
    'document' => 'Dokumen',
    'sheet'    => 'Spreadsheet',
    'slide'    => 'Slide',
    'other'    => 'Lainnya',
];
?>

<div class="max-w-7xl mx-auto p-4 md:p-6 space-y-6">
    <div class="bg-gradient-to-r from-blue-600 to-indigo-700 rounded-3xl p-6 text-white shadow-xl">
        <h1 class="text-2xl md:text-3xl font-bold">Google Drive Reader</h1>
        <p class="text-blue-100 mt-2">
            Modul baca folder dan subfolder Google Drive untuk SPO Keperawatan dan PPI, dengan fitur view, download, upload, buat folder, dan hapus.
        </p>
        <div class="mt-3 text-sm text-blue-100">
            Folder aktif: <span class="font-semibold"><?= e($currentFolder['name'] ?? 'Folder') ?></span>
        </div>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <?php foreach ($driveShortcutFolders as $shortcut): ?>
            <?php
            $shortcutFolderId = (string)$shortcut['folder_id'];
            $isActiveShortcut = $folderId === $shortcutFolderId || ($shortcutFolderId === '' && $folderId === '');
            ?>
            <a
                href="<?= e(driveReaderUrl($shortcutFolderId)) ?>"
                class="group block rounded-3xl border <?= $isActiveShortcut ? 'border-blue-300 ring-4 ring-blue-100' : 'border-slate-200' ?> bg-white shadow-lg hover:shadow-xl transition overflow-hidden"
            >
                <div class="p-5 flex items-center gap-4">
                    <div class="w-14 h-14 rounded-2xl bg-gradient-to-br <?= e($shortcut['color']) ?> text-white flex items-center justify-center shadow-lg group-hover:scale-105 transition">
                        <i class="fas <?= e($shortcut['icon']) ?> text-xl"></i>
                    </div>
                    <div class="flex-1">
                        <div class="flex items-center gap-2 flex-wrap">
                            <h2 class="text-lg font-bold text-slate-800"><?= e($shortcut['title']) ?></h2>
                            <?php if ($isActiveShortcut): ?>
                                <span class="px-2.5 py-1 rounded-full bg-blue-50 text-blue-700 text-xs font-bold">Aktif</span>
                            <?php endif; ?>
                        </div>
                        <p class="text-sm text-slate-500 mt-1"><?= e($shortcut['subtitle']) ?></p>
                    </div>
                    <div class="text-slate-300 group-hover:text-blue-600 transition">
                        <i class="fas fa-arrow-right text-xl"></i>
                    </div>
                </div>
            </a>
        <?php endforeach; ?>
    </div>

    <?php if ($alert['message'] !== ''): ?>
        <div class="<?= $alert['type'] === 'success'
            ? 'bg-green-50 border-l-4 border-green-500 text-green-700'
            : 'bg-red-50 border-l-4 border-red-500 text-red-700' ?> p-4 rounded-xl">
            <?= e($alert['message']) ?>
        </div>
    <?php endif; ?>

    <div class="bg-white rounded-2xl shadow-lg p-5">
        <div class="flex flex-wrap items-center gap-2 text-sm mb-4">
            <?php if (!empty($breadcrumbs)): ?>
                <?php foreach ($breadcrumbs as $index => $crumb): ?>
                    <a
                        href="<?= e(driveReaderUrl((string)$crumb['id'])) ?>"
                        class="px-3 py-1.5 rounded-full bg-blue-50 text-blue-700 hover:bg-blue-100"
                    >
                        <?= e($crumb['name']) ?>
                    </a>
                    <?php if ($index < count($breadcrumbs) - 1): ?>
                        <span class="text-gray-400">/</span>
                    <?php endif; ?>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>

        <div class="flex flex-wrap gap-3">
            <?php if (!empty($currentFolder['parentId'])): ?>
                <a
                    href="<?= e(driveReaderUrl((string)$currentFolder['parentId'])) ?>"
                    class="bg-slate-100 text-slate-700 px-4 py-2 rounded-xl hover:bg-slate-200 text-sm"
                >
                    <i class="fas fa-arrow-up mr-2"></i>Naik Satu Folder
                </a>
            <?php endif; ?>

            <button
                type="button"
                onclick="toggleCreateFolderForm()"
                class="bg-amber-500 text-white px-4 py-2 rounded-xl hover:bg-amber-600 text-sm"
            >
                <i class="fas fa-folder-plus mr-2"></i>Buat Folder Baru
            </button>
        </div>

        <div id="createFolderForm" class="hidden mt-4">
            <form method="POST" class="flex flex-col md:flex-row gap-3">
                <input type="hidden" name="create_folder" value="1">
                <input type="hidden" name="folder_id" value="<?= e($currentFolder['id'] ?? '') ?>">

                <input
                    type="text"
                    name="folder_name"
                    required
                    placeholder="Nama folder baru..."
                    class="flex-1 px-4 py-2 border border-gray-300 rounded-xl focus:ring-2 focus:ring-amber-500"
                >

                <button
                    type="submit"
                    class="bg-amber-500 text-white px-4 py-2 rounded-xl hover:bg-amber-600"
                >
                    Simpan Folder
                </button>
            </form>
        </div>
    </div>

    <div class="grid grid-cols-1 xl:grid-cols-3 gap-6">
        <div class="xl:col-span-2 bg-white rounded-2xl shadow-lg p-5">
            <h2 class="text-lg font-semibold text-gray-800 mb-4">Filter Isi Folder</h2>

            <form method="GET" class="grid grid-cols-1 md:grid-cols-5 gap-4">
                <input type="hidden" name="module" value="google_drive_reader">
                <input type="hidden" name="folder_id" value="<?= e($currentFolder['id'] ?? '') ?>">

                <div class="md:col-span-3">
                    <label class="block text-sm font-medium text-gray-700 mb-1">Cari</label>
                    <input
                        type="text"
                        name="search"
                        value="<?= e($search) ?>"
                        placeholder="Cari file, folder, tipe, atau kata kunci..."
                        class="w-full px-4 py-2 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500"
                    >
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Tipe</label>
                    <select
                        name="type"
                        class="w-full px-4 py-2 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500"
                    >
                        <?php foreach ($typeOptions as $key => $label): ?>
                            <option value="<?= e($key) ?>" <?= $type === $key ? 'selected' : '' ?>>
                                <?= e($label) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="flex items-end">
                    <button
                        type="submit"
                        class="w-full bg-blue-600 text-white px-4 py-2 rounded-xl hover:bg-blue-700"
                    >
                        <i class="fas fa-search mr-2"></i>Filter
                    </button>
                </div>
            </form>
        </div>

        <div class="bg-white rounded-2xl shadow-lg p-5">
            <h2 class="text-lg font-semibold text-gray-800 mb-4">Upload ke Folder Aktif</h2>

            <form method="POST" enctype="multipart/form-data" class="space-y-4">
                <input type="hidden" name="upload_file" value="1">
                <input type="hidden" name="folder_id" value="<?= e($currentFolder['id'] ?? '') ?>">

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Pilih file</label>
                    <input
                        type="file"
                        name="drive_file"
                        required
                        class="w-full px-4 py-2 border border-gray-300 rounded-xl"
                    >
                </div>

                <button
                    type="submit"
                    class="w-full bg-green-600 text-white px-4 py-2 rounded-xl hover:bg-green-700"
                >
                    <i class="fas fa-upload mr-2"></i>Upload
                </button>
            </form>
        </div>
    </div>

    <div class="flex items-center justify-between">
        <h2 class="text-lg font-semibold text-gray-800">Isi Folder</h2>
        <div class="text-sm text-gray-500">
            <?= count($folders) ?> folder • <?= count($files) ?> file
        </div>
    </div>

    <?php if (empty($folders) && empty($files)): ?>
        <div class="bg-yellow-50 border-l-4 border-yellow-500 p-4 rounded-xl text-yellow-700">
            Folder ini kosong atau tidak ada data yang cocok dengan filter.
        </div>
    <?php else: ?>
        <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5">
            <?php foreach ($folders as $folder): ?>
                <?php $badgeClass = fileTypeBadgeClass('folder'); ?>
                <div class="bg-white rounded-2xl shadow-lg border border-gray-100 overflow-hidden hover:shadow-xl transition">
                    <div class="p-5">
                        <div class="flex items-start gap-4">
                            <div class="w-14 h-14 rounded-2xl bg-amber-50 text-amber-600 flex items-center justify-center">
                                <i class="fas fa-folder text-xl"></i>
                            </div>

                            <div class="flex-1 min-w-0">
                                <h3 class="font-semibold text-gray-800 break-words">
                                    <?= e($folder['name'] ?? '-') ?>
                                </h3>

                                <div class="mt-2 flex flex-wrap gap-2 text-xs">
                                    <span class="px-2 py-1 rounded-full <?= e($badgeClass) ?>">
                                        FOLDER
                                    </span>
                                </div>

                                <div class="text-xs text-gray-500 mt-3">
                                    Update:
                                    <?= !empty($folder['updatedAt']) ? e(date('d/m/Y H:i', strtotime($folder['updatedAt']))) : '-' ?>
                                </div>
                            </div>
                        </div>

                        <div class="mt-5 flex flex-wrap gap-2">
                            <a
                                href="<?= e(driveReaderUrl((string)$folder['id'])) ?>"
                                class="bg-blue-600 text-white px-4 py-2 rounded-xl hover:bg-blue-700 text-sm"
                            >
                                <i class="fas fa-folder-open mr-2"></i>Buka
                            </a>

                            <form method="POST" onsubmit="return confirm('Yakin ingin menghapus folder ini?');">
                                <input type="hidden" name="delete_folder" value="1">
                                <input type="hidden" name="delete_folder_id" value="<?= e($folder['id']) ?>">
                                <button
                                    type="submit"
                                    class="bg-red-600 text-white px-4 py-2 rounded-xl hover:bg-red-700 text-sm"
                                >
                                    <i class="fas fa-trash mr-2"></i>Hapus
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>

            <?php foreach ($files as $file): ?>
                <?php
                $fileType = (string)($file['type'] ?? 'other');
                $badgeClass = fileTypeBadgeClass($fileType);
                ?>
                <div class="bg-white rounded-2xl shadow-lg border border-gray-100 overflow-hidden hover:shadow-xl transition">
                    <div class="p-5">
                        <div class="flex items-start gap-4">
                            <div class="w-14 h-14 rounded-2xl bg-blue-50 text-blue-600 flex items-center justify-center">
                                <i class="fas <?= e($file['icon'] ?? 'fa-file') ?> text-xl"></i>
                            </div>

                            <div class="flex-1 min-w-0">
                                <h3 class="font-semibold text-gray-800 break-words">
                                    <?= e($file['name'] ?? '-') ?>
                                </h3>

                                <div class="mt-2 flex flex-wrap gap-2 text-xs">
                                    <span class="px-2 py-1 rounded-full <?= e($badgeClass) ?>">
                                        <?= e(strtoupper($fileType)) ?>
                                    </span>

                                    <span class="px-2 py-1 bg-gray-100 text-gray-600 rounded-full">
                                        <?= e(formatBytes($file['size'] ?? 0)) ?>
                                    </span>

                                    <?php if (!empty($file['extension'])): ?>
                                        <span class="px-2 py-1 bg-slate-100 text-slate-600 rounded-full">
                                            .<?= e($file['extension']) ?>
                                        </span>
                                    <?php endif; ?>
                                </div>

                                <div class="text-xs text-gray-500 mt-3">
                                    Update:
                                    <?= !empty($file['updatedAt']) ? e(date('d/m/Y H:i', strtotime($file['updatedAt']))) : '-' ?>
                                </div>
                            </div>
                        </div>

                        <div class="mt-5 flex flex-wrap gap-2">
                            <button
                                type="button"
                                onclick="openDrivePreview('<?= e($file['previewLink'] ?? '') ?>', '<?= e(addslashes((string)($file['name'] ?? 'Preview'))) ?>')"
                                class="bg-blue-600 text-white px-4 py-2 rounded-xl hover:bg-blue-700 text-sm"
                            >
                                <i class="fas fa-eye mr-2"></i>View
                            </button>

                            <a
                                href="<?= e($file['downloadLink'] ?? '#') ?>"
                                target="_blank"
                                rel="noopener noreferrer"
                                class="bg-green-600 text-white px-4 py-2 rounded-xl hover:bg-green-700 text-sm"
                            >
                                <i class="fas fa-download mr-2"></i>Download
                            </a>

                            <a
                                href="<?= e($file['viewLink'] ?? '#') ?>"
                                target="_blank"
                                rel="noopener noreferrer"
                                class="bg-gray-100 text-gray-700 px-4 py-2 rounded-xl hover:bg-gray-200 text-sm"
                            >
                                <i class="fas fa-external-link-alt mr-2"></i>Buka
                            </a>

                            <form method="POST" onsubmit="return confirm('Yakin ingin menghapus file ini?');">
                                <input type="hidden" name="delete_file" value="1">
                                <input type="hidden" name="file_id" value="<?= e($file['id']) ?>">
                                <button
                                    type="submit"
                                    class="bg-red-600 text-white px-4 py-2 rounded-xl hover:bg-red-700 text-sm"
                                >
                                    <i class="fas fa-trash mr-2"></i>Hapus
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

<div id="driveModal" class="fixed inset-0 bg-black/60 hidden items-center justify-center z-50 p-4">
    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-6xl h-[88vh] overflow-hidden">
        <div class="flex items-center justify-between px-5 py-4 border-b">
            <h3 id="driveModalTitle" class="text-lg font-semibold text-gray-800">Preview File</h3>
            <button
                type="button"
                onclick="closeDrivePreview()"
                class="text-gray-500 hover:text-gray-700 text-2xl"
            >
                &times;
            </button>
        </div>

        <div class="h-[calc(88vh-72px)] bg-gray-50">
            <iframe id="drivePreviewFrame" src="" class="w-full h-full border-0"></iframe>
        </div>
    </div>
</div>

<script>
function openDrivePreview(url, title) {
    document.getElementById('driveModalTitle').textContent = title || 'Preview File';
    document.getElementById('drivePreviewFrame').src = url;
    document.getElementById('driveModal').classList.remove('hidden');
    document.getElementById('driveModal').classList.add('flex');
}

function closeDrivePreview() {
    document.getElementById('driveModal').classList.add('hidden');
    document.getElementById('driveModal').classList.remove('flex');
    document.getElementById('drivePreviewFrame').src = '';
}

function toggleCreateFolderForm() {
    const form = document.getElementById('createFolderForm');
    form.classList.toggle('hidden');
}

document.addEventListener('keydown', function (e) {
    if (e.key === 'Escape') {
        closeDrivePreview();
    }
});
</script>