<?php
// modules/kumpulan_dokumen_laporan/index.php
// Modul Kumpulan Dokumen dan Laporan - Divisi Keperawatan

declare(strict_types=1);

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

if (!function_exists('kdl_conn')) {
    function kdl_conn(): mysqli {
        if (function_exists('getConnection')) {
            $conn = getConnection();
            if ($conn instanceof mysqli) return $conn;
        }
        throw new Exception('Koneksi database gagal.');
    }
}

if (!function_exists('kdl_current_user')) {
    function kdl_current_user(): array {
        if (function_exists('current_user')) {
            $u = current_user();
            if (is_array($u)) return $u;
        }
        return $_SESSION['user'] ?? [
            'id' => $_SESSION['user_id'] ?? 0,
            'role' => $_SESSION['user_role'] ?? 'user',
            'nama' => $_SESSION['full_name'] ?? ($_SESSION['username'] ?? 'User'),
            'unit_name' => $_SESSION['unit'] ?? '',
        ];
    }
}

if (!function_exists('kdl_role')) {
    function kdl_role(): string {
        $u = kdl_current_user();
        return strtolower((string)($u['role'] ?? $_SESSION['user_role'] ?? 'user'));
    }
}

if (!function_exists('kdl_user_name')) {
    function kdl_user_name(): string {
        $u = kdl_current_user();
        return (string)($u['nama'] ?? $u['full_name'] ?? $u['name'] ?? $_SESSION['full_name'] ?? $_SESSION['username'] ?? 'User');
    }
}

if (!function_exists('kdl_user_id')) {
    function kdl_user_id(): int {
        $u = kdl_current_user();
        return (int)($u['id'] ?? $u['user_id'] ?? $u['employee_id'] ?? $_SESSION['user_id'] ?? 0);
    }
}

if (!function_exists('kdl_can_manage')) {
    function kdl_can_manage(): bool {
        $role = kdl_role();
        $allowed = ['superadmin','admin','kepala unit','ka.unit','ka unit','kasubdiv','kepala divisi keperawatan','kadiv','manager'];
        foreach ($allowed as $r) {
            if (strpos($role, $r) !== false) return true;
        }
        return false;
    }
}

if (!function_exists('kdl_format_size')) {
    function kdl_format_size(int $bytes): string {
        if ($bytes >= 1073741824) return number_format($bytes / 1073741824, 2, ',', '.') . ' GB';
        if ($bytes >= 1048576) return number_format($bytes / 1048576, 2, ',', '.') . ' MB';
        if ($bytes >= 1024) return number_format($bytes / 1024, 2, ',', '.') . ' KB';
        return $bytes . ' B';
    }
}

// Helper Google Drive (gdrive_client, gdrive_upload_file, gdrive_extract_folder_id, dst).
require_once dirname(__DIR__, 2) . '/includes/google_drive_helper.php';

$conn = kdl_conn();
$canManage = kdl_can_manage();
$userId = kdl_user_id();
$userName = kdl_user_name();
$role = kdl_role();

$ROOT_GDRIVE_URL = 'https://drive.google.com/drive/folders/1Tlr7Y7prVcnRhjsDOhMvSCp3kX4WrkW8?usp=sharing';
$message = '';
$error = '';

// Folder STAGING sementara (bukan penyimpanan akhir). File ditulis di sini sebentar
// lalu langsung diupload ke Google Drive dan dihapus dari server (lihat kdl_cleanup_staging()).
function kdl_resolve_upload_base(): string {
    $candidates = [];
    $documentRoot = rtrim((string)($_SERVER['DOCUMENT_ROOT'] ?? ''), '/\\');
    if ($documentRoot !== '') {
        $candidates[] = $documentRoot . '/uploads/_staging_dokumen_laporan';
    }
    $candidates[] = dirname(__DIR__, 2) . '/uploads/_staging_dokumen_laporan';
    $candidates[] = sys_get_temp_dir() . '/kdl_staging';

    $errors = [];
    foreach (array_unique($candidates) as $dir) {
        if (!is_dir($dir)) {
            if (!@mkdir($dir, 0775, true) && !is_dir($dir)) {
                $errors[] = $dir . ' (gagal dibuat)';
                continue;
            }
        }

        @chmod($dir, 0775);
        if (!is_writable($dir)) {
            $errors[] = $dir . ' (tidak writable)';
            continue;
        }

        // Tes tulis nyata, karena is_writable() kadang lolos tetapi proses write tetap ditolak.
        $testFile = $dir . '/.kdl_write_test_' . bin2hex(random_bytes(4));
        if (@file_put_contents($testFile, 'ok') === false) {
            $errors[] = $dir . ' (tes tulis gagal)';
            continue;
        }
        @unlink($testFile);
        return $dir;
    }

    throw new RuntimeException('Folder staging sementara tidak dapat digunakan. Detail: ' . implode('; ', $errors));
}

function kdl_cleanup_staging(string $path): void {
    if ($path !== '' && is_file($path)) {
        @unlink($path);
    }
}

function kdl_upload_error_message(int $code): string {
    return match ($code) {
        UPLOAD_ERR_OK => 'OK',
        UPLOAD_ERR_INI_SIZE => 'Ukuran file melebihi batas upload_max_filesize pada PHP hosting.',
        UPLOAD_ERR_FORM_SIZE => 'Ukuran file melebihi batas MAX_FILE_SIZE pada form.',
        UPLOAD_ERR_PARTIAL => 'File hanya terunggah sebagian. Silakan ulangi.',
        UPLOAD_ERR_NO_FILE => 'Belum ada file lokal yang dipilih.',
        UPLOAD_ERR_NO_TMP_DIR => 'Folder temporary upload PHP tidak tersedia.',
        UPLOAD_ERR_CANT_WRITE => 'Server gagal menulis file ke disk.',
        UPLOAD_ERR_EXTENSION => 'Upload dihentikan oleh ekstensi PHP.',
        default => 'Upload gagal dengan kode ' . $code . '.',
    };
}

try {
    $uploadBase = kdl_resolve_upload_base();
} catch (Throwable $uploadDirError) {
    $uploadBase = '';
    $error = $uploadDirError->getMessage();
}

function kdl_log(mysqli $conn, string $action, string $targetType, int $targetId, string $note = ''): void {
    $uid = kdl_user_id();
    $uname = kdl_user_name();
    $stmt = $conn->prepare("INSERT INTO doclap_activity (user_id, user_name, action, target_type, target_id, note, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())");
    if ($stmt) {
        $stmt->bind_param('isssis', $uid, $uname, $action, $targetType, $targetId, $note);
        $stmt->execute();
        $stmt->close();
    }
}

function kdl_slug(string $text): string {
    $text = strtolower(trim($text));
    $text = preg_replace('/[^a-z0-9]+/i', '-', $text);
    $text = trim((string)$text, '-');
    return $text !== '' ? substr($text, 0, 80) : 'folder';
}

function kdl_get_folder(mysqli $conn, int $id): ?array {
    $stmt = $conn->prepare("SELECT * FROM doclap_folders WHERE id = ? AND is_deleted = 0 LIMIT 1");
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $res = $stmt->get_result();
    $row = $res ? $res->fetch_assoc() : null;
    $stmt->close();
    return $row ?: null;
}

// Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $act = $_POST['kdl_action'] ?? '';

    if (!$canManage && in_array($act, ['create_folder','update_folder','delete_folder','upload_file','delete_file'], true)) {
        $error = 'Akses ditolak. Hanya kepala unit/admin yang bisa menambah, mengedit, menghapus, dan upload dokumen.';
    } else {
        try {
            if ($act === 'create_folder') {
                $name = trim($_POST['folder_name'] ?? '');
                $unitName = trim($_POST['unit_name'] ?? '');
                $parentId = (int)($_POST['parent_id'] ?? 0);
                $driveUrl = trim($_POST['drive_url'] ?? '');
                $description = trim($_POST['description'] ?? '');
                if ($name === '') throw new Exception('Nama folder wajib diisi.');
                $slug = kdl_slug($name . '-' . time());
                $parentVal = $parentId > 0 ? $parentId : null;
                $stmt = $conn->prepare("INSERT INTO doclap_folders (parent_id, folder_name, folder_slug, unit_name, description, drive_url, created_by, created_by_name, created_at, updated_at, is_deleted) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW(), 0)");
                $stmt->bind_param('isssssis', $parentVal, $name, $slug, $unitName, $description, $driveUrl, $userId, $userName);
                $stmt->execute();
                $newId = (int)$conn->insert_id;
                $stmt->close();
                kdl_log($conn, 'create_folder', 'folder', $newId, $name);
                $message = 'Folder berhasil ditambahkan.';
            }

            if ($act === 'update_folder') {
                $id = (int)($_POST['folder_id'] ?? 0);
                $name = trim($_POST['folder_name'] ?? '');
                $unitName = trim($_POST['unit_name'] ?? '');
                $driveUrl = trim($_POST['drive_url'] ?? '');
                $description = trim($_POST['description'] ?? '');
                if ($id <= 0 || $name === '') throw new Exception('Data folder tidak valid.');
                $stmt = $conn->prepare("UPDATE doclap_folders SET folder_name = ?, unit_name = ?, description = ?, drive_url = ?, updated_at = NOW() WHERE id = ? AND is_deleted = 0");
                $stmt->bind_param('ssssi', $name, $unitName, $description, $driveUrl, $id);
                $stmt->execute();
                $stmt->close();
                kdl_log($conn, 'update_folder', 'folder', $id, $name);
                $message = 'Folder berhasil diperbarui.';
            }

            if ($act === 'delete_folder') {
                $id = (int)($_POST['folder_id'] ?? 0);
                if ($id <= 0) throw new Exception('Folder tidak valid.');
                $stmt = $conn->prepare("UPDATE doclap_folders SET is_deleted = 1, updated_at = NOW() WHERE id = ?");
                $stmt->bind_param('i', $id);
                $stmt->execute();
                $stmt->close();
                kdl_log($conn, 'delete_folder', 'folder', $id, 'Soft delete folder');
                $message = 'Folder berhasil dihapus dari tampilan.';
            }

            if ($act === 'upload_file') {
                $folderId = (int)($_POST['folder_id'] ?? 0);
                $docTitle = trim($_POST['doc_title'] ?? '');
                $docType = trim($_POST['doc_type'] ?? 'Dokumen');
                $driveFileUrlManual = trim($_POST['drive_file_url'] ?? '');
                $note = trim($_POST['note'] ?? '');
                if ($folderId <= 0) throw new Exception('Pilih folder tujuan.');
                $folder = kdl_get_folder($conn, $folderId);
                if (!$folder) throw new Exception('Folder tujuan tidak ditemukan.');

                $originalName = null; $mimeType = null; $sizeBytes = 0;
                $driveFileId = null; $driveFileUrl = $driveFileUrlManual;
                $stagingPath = '';

                $upload = $_FILES['document_file'] ?? null;
                if (is_array($upload)) {
                    $uploadError = (int)($upload['error'] ?? UPLOAD_ERR_NO_FILE);
                    if ($uploadError !== UPLOAD_ERR_OK && $uploadError !== UPLOAD_ERR_NO_FILE) {
                        throw new RuntimeException(kdl_upload_error_message($uploadError));
                    }

                    if ($uploadError === UPLOAD_ERR_OK) {
                        // Folder Drive tujuan WAJIB sudah diatur di folder unit (kolom drive_url),
                        // karena ini sekarang menjadi tujuan akhir penyimpanan file, bukan lagi disk lokal.
                        $targetDriveFolderId = gdrive_extract_folder_id((string)($folder['drive_url'] ?? ''));
                        if ($targetDriveFolderId === '') {
                            throw new RuntimeException('Folder unit "' . $folder['folder_name'] . '" belum memiliki Link Google Drive. Klik "Edit Folder" dan isi Link Google Drive Folder terlebih dahulu, baru upload dokumen.');
                        }

                        if ($uploadBase === '' || !is_dir($uploadBase) || !is_writable($uploadBase)) {
                            throw new RuntimeException('Folder staging sementara server belum siap/tidak writable.');
                        }

                        $tmpName = (string)($upload['tmp_name'] ?? '');
                        if ($tmpName === '' || !is_uploaded_file($tmpName)) {
                            throw new RuntimeException('File temporary upload tidak valid. Silakan pilih ulang file.');
                        }

                        $originalName = basename((string)($upload['name'] ?? 'dokumen'));
                        $sizeBytes = (int)($upload['size'] ?? 0);
                        $ext = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
                        $allowed = ['pdf','doc','docx','xls','xlsx','ppt','pptx','jpg','jpeg','png','zip','rar','txt'];
                        if (!in_array($ext, $allowed, true)) {
                            throw new RuntimeException('Format file .' . e($ext) . ' tidak didukung. Gunakan PDF/Word/Excel/PPT/gambar/ZIP.');
                        }
                        if ($sizeBytes <= 0) {
                            throw new RuntimeException('File kosong atau ukuran file tidak terbaca.');
                        }
                        if ($sizeBytes > 30 * 1024 * 1024) {
                            throw new RuntimeException('Ukuran file maksimal 30 MB. Ukuran file: ' . kdl_format_size($sizeBytes) . '.');
                        }

                        $finfo = function_exists('finfo_open') ? @finfo_open(FILEINFO_MIME_TYPE) : false;
                        $mimeType = $finfo ? (string)@finfo_file($finfo, $tmpName) : (string)($upload['type'] ?? 'application/octet-stream');
                        if ($finfo) @finfo_close($finfo);

                        $safeBase = kdl_slug(pathinfo($originalName, PATHINFO_FILENAME));
                        try {
                            $suffix = bin2hex(random_bytes(4));
                        } catch (Throwable $randomError) {
                            $suffix = substr(md5(uniqid('', true)), 0, 8);
                        }
                        $stagingName = date('YmdHis') . '_' . $suffix . '_' . $safeBase . '.' . $ext;
                        $stagingPath = rtrim($uploadBase, '/\\') . DIRECTORY_SEPARATOR . $stagingName;

                        // Pindahkan ke staging sementara dulu (PHP butuh file fisik untuk dibaca ulang
                        // saat dikirim ke Google Drive API).
                        if (!@move_uploaded_file($tmpName, $stagingPath)) {
                            $lastError = error_get_last();
                            $detail = is_array($lastError) ? trim((string)($lastError['message'] ?? '')) : '';
                            throw new RuntimeException('Gagal memproses file upload sementara di server.' . ($detail !== '' ? ' Detail server: ' . $detail : ''));
                        }

                        if (!is_file($stagingPath) || filesize($stagingPath) <= 0) {
                            kdl_cleanup_staging($stagingPath);
                            throw new RuntimeException('File gagal diverifikasi setelah upload sementara.');
                        }

                        // Upload ke Google Drive. Jika gagal, staging dibersihkan dan exception dilempar
                        // (TIDAK ada fallback simpan permanen di server).
                        try {
                            $driveResult = gdrive_upload_file($stagingPath, $originalName, $targetDriveFolderId, $mimeType ?: 'application/octet-stream');
                            $driveFileId = $driveResult['id'];
                            $driveFileUrl = $driveResult['webViewLink'];
                        } finally {
                            kdl_cleanup_staging($stagingPath);
                        }
                    }
                }

                if ($docTitle === '') {
                    $docTitle = $originalName ?: 'Dokumen Baru';
                }
                if (!$driveFileId && $driveFileUrl === '') {
                    throw new Exception('Upload file atau isi link Google Drive dokumen.');
                }

                $stmt = $conn->prepare("INSERT INTO doclap_files (folder_id, doc_title, doc_type, original_name, stored_name, file_path, mime_type, size_bytes, drive_file_url, note, uploaded_by, uploaded_by_name, uploaded_at, updated_at, is_deleted) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW(), 0)");
                // Catatan kolom: stored_name dipakai menyimpan Google Drive File ID (bukan nama file disk lagi),
                // dan file_path sengaja dikosongkan karena file tidak lagi disimpan permanen di server.
                $emptyFilePath = '';
                $stmt->bind_param('issssssissis', $folderId, $docTitle, $docType, $originalName, $driveFileId, $emptyFilePath, $mimeType, $sizeBytes, $driveFileUrl, $note, $userId, $userName);
                $stmt->execute();
                $fileId = (int)$conn->insert_id;
                $stmt->close();
                kdl_log($conn, 'upload_file', 'file', $fileId, $docTitle);
                $message = 'Dokumen berhasil diupload ke Google Drive.';
            }

            if ($act === 'delete_file') {
                $id = (int)($_POST['file_id'] ?? 0);
                if ($id <= 0) throw new Exception('File tidak valid.');
                $stmt = $conn->prepare("UPDATE doclap_files SET is_deleted = 1, updated_at = NOW() WHERE id = ?");
                $stmt->bind_param('i', $id);
                $stmt->execute();
                $stmt->close();
                kdl_log($conn, 'delete_file', 'file', $id, 'Soft delete file');
                $message = 'Dokumen berhasil dihapus dari tampilan.';
            }
        } catch (Throwable $ex) {
            $error = $ex->getMessage();
        }
    }
}

$selectedFolderId = (int)($_GET['folder_id'] ?? 0);
$search = trim($_GET['q'] ?? '');
$unitFilter = trim($_GET['unit'] ?? '');

$unitList = ['IGD','VK / Kamar Bersalin','OK / Kamar Operasi','Poliklinik','HD / Hemodialisa','Pav. Canigara','Pav. Cempaka','Pav. Cendana','Ruang Bayi','NICU','ICU'];

$folders = [];
$res = $conn->query("SELECT f.*, (SELECT COUNT(*) FROM doclap_files df WHERE df.folder_id = f.id AND df.is_deleted = 0) AS total_files FROM doclap_folders f WHERE f.is_deleted = 0 ORDER BY f.parent_id IS NULL DESC, f.unit_name ASC, f.folder_name ASC");
if ($res) while ($r = $res->fetch_assoc()) $folders[] = $r;

if ($selectedFolderId <= 0 && !empty($folders)) {
    $selectedFolderId = (int)$folders[0]['id'];
}
$selectedFolder = $selectedFolderId > 0 ? kdl_get_folder($conn, $selectedFolderId) : null;

// Files query
$files = [];
$where = "df.is_deleted = 0";
$types = '';
$params = [];
if ($selectedFolderId > 0) { $where .= " AND df.folder_id = ?"; $types .= 'i'; $params[] = $selectedFolderId; }
if ($search !== '') { $where .= " AND (df.doc_title LIKE ? OR df.doc_type LIKE ? OR df.note LIKE ? OR df.original_name LIKE ?)"; $types .= 'ssss'; $like = '%' . $search . '%'; array_push($params, $like, $like, $like, $like); }
if ($unitFilter !== '') { $where .= " AND f.unit_name = ?"; $types .= 's'; $params[] = $unitFilter; }
$sqlFiles = "SELECT df.*, f.folder_name, f.unit_name FROM doclap_files df INNER JOIN doclap_folders f ON f.id = df.folder_id WHERE $where ORDER BY df.uploaded_at DESC, df.id DESC";
$stmtFiles = $conn->prepare($sqlFiles);
if ($stmtFiles) {
    if ($types !== '') $stmtFiles->bind_param($types, ...$params);
    $stmtFiles->execute();
    $resFiles = $stmtFiles->get_result();
    while ($r = $resFiles->fetch_assoc()) $files[] = $r;
    $stmtFiles->close();
}

$totalFolders = count($folders);
$totalFiles = (int)($conn->query("SELECT COUNT(*) AS c FROM doclap_files WHERE is_deleted = 0")->fetch_assoc()['c'] ?? 0);
$totalDriveLinks = (int)($conn->query("SELECT COUNT(*) AS c FROM doclap_files WHERE is_deleted = 0 AND drive_file_url <> ''")->fetch_assoc()['c'] ?? 0);
$recentCount = (int)($conn->query("SELECT COUNT(*) AS c FROM doclap_files WHERE is_deleted = 0 AND uploaded_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)")->fetch_assoc()['c'] ?? 0);
?>
<style>
.kdl-hero{background:linear-gradient(135deg,#0f766e,#2563eb 55%,#7c3aed);border-radius:28px;color:#fff;padding:26px;box-shadow:0 22px 50px rgba(37,99,235,.22);position:relative;overflow:hidden}.kdl-hero:after{content:'';position:absolute;width:220px;height:220px;border-radius:999px;background:rgba(255,255,255,.12);right:-70px;top:-80px}.kdl-card{background:#fff;border:1px solid #e2e8f0;border-radius:22px;box-shadow:0 14px 34px rgba(15,23,42,.06)}.kdl-folder{display:block;padding:14px;border-radius:16px;border:1px solid #e2e8f0;background:#fff;transition:.2s}.kdl-folder:hover{transform:translateY(-2px);box-shadow:0 10px 25px rgba(15,23,42,.08)}.kdl-folder.active{border-color:#2563eb;background:#eff6ff}.kdl-pill{display:inline-flex;align-items:center;gap:6px;border-radius:999px;padding:4px 10px;font-size:12px;font-weight:700}.kdl-input{width:100%;border:1px solid #cbd5e1;border-radius:12px;padding:10px 12px}.kdl-btn{display:inline-flex;align-items:center;gap:8px;border-radius:12px;padding:10px 14px;font-weight:700}.kdl-table th{background:#f8fafc;color:#475569;font-size:12px;text-transform:uppercase;letter-spacing:.04em}.kdl-table td,.kdl-table th{padding:12px;border-bottom:1px solid #e2e8f0}.kdl-modal{display:none;position:fixed;inset:0;background:rgba(15,23,42,.55);z-index:9999;align-items:center;justify-content:center;padding:20px}.kdl-modal.show{display:flex}.kdl-modal-box{background:#fff;border-radius:22px;max-width:720px;width:100%;max-height:92vh;overflow:auto;box-shadow:0 30px 80px rgba(0,0,0,.25)}
</style>

<div class="space-y-6">
    <div class="kdl-hero">
        <div class="relative z-10 flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
            <div>
                <div class="text-sm font-bold uppercase tracking-wider text-blue-100">Divisi Keperawatan</div>
                <h1 class="text-2xl md:text-3xl font-extrabold mt-1">Kumpulan Dokumen dan Laporan</h1>
                <p class="text-blue-50 mt-2 max-w-3xl">Pusat arsip dokumen, laporan, file unit, dan tautan Google Drive. Kepala unit dapat membuat folder, edit, hapus, serta upload dokumen sesuai kebutuhan.</p>
            </div>
            <div class="flex flex-wrap gap-2">
                <a href="<?= e($ROOT_GDRIVE_URL) ?>" target="_blank" class="kdl-btn bg-white text-blue-700"><i class="fab fa-google-drive"></i> Buka Drive Utama</a>
                <?php if ($canManage): ?>
                <button type="button" onclick="kdlOpenFolderModal()" class="kdl-btn bg-yellow-300 text-slate-900"><i class="fas fa-folder-plus"></i> Tambah Folder</button>
                <?php endif; ?>
            </div>
        </div>
    </div>

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

    <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div class="kdl-card p-4"><div class="text-sm text-slate-500">Total Folder</div><div class="text-3xl font-extrabold text-slate-800"><?= $totalFolders ?></div></div>
        <div class="kdl-card p-4"><div class="text-sm text-slate-500">Total Dokumen</div><div class="text-3xl font-extrabold text-slate-800"><?= $totalFiles ?></div></div>
        <div class="kdl-card p-4"><div class="text-sm text-slate-500">Link Drive</div><div class="text-3xl font-extrabold text-slate-800"><?= $totalDriveLinks ?></div></div>
        <div class="kdl-card p-4"><div class="text-sm text-slate-500">Upload 30 Hari</div><div class="text-3xl font-extrabold text-slate-800"><?= $recentCount ?></div></div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-4 gap-6">
        <div class="lg:col-span-1 space-y-4">
            <div class="kdl-card p-4">
                <div class="flex items-center justify-between mb-3">
                    <h3 class="font-extrabold text-slate-800"><i class="fas fa-folder-tree text-blue-600 mr-2"></i> Folder Unit</h3>
                </div>
                <div class="space-y-2 max-h-[680px] overflow-auto pr-1">
                    <?php foreach ($folders as $f): ?>
                        <a href="?module=kumpulan_dokumen_laporan&folder_id=<?= (int)$f['id'] ?>" class="kdl-folder <?= (int)$f['id'] === $selectedFolderId ? 'active' : '' ?>">
                            <div class="font-bold text-slate-800 truncate"><?= e($f['folder_name']) ?></div>
                            <div class="text-xs text-slate-500 mt-1"><?= e($f['unit_name'] ?: 'Umum') ?> · <?= (int)$f['total_files'] ?> dokumen</div>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>

        <div class="lg:col-span-3 space-y-4">
            <div class="kdl-card p-5">
                <div class="flex flex-col md:flex-row md:items-start md:justify-between gap-3">
                    <div>
                        <div class="text-xs uppercase tracking-wider font-bold text-slate-400">Folder aktif</div>
                        <h2 class="text-2xl font-extrabold text-slate-800"><?= e($selectedFolder['folder_name'] ?? 'Belum ada folder') ?></h2>
                        <div class="mt-1 text-sm text-slate-500"><?= e($selectedFolder['description'] ?? '') ?></div>
                        <?php if (!empty($selectedFolder['unit_name'])): ?><span class="kdl-pill bg-blue-50 text-blue-700 mt-3"><i class="fas fa-hospital"></i><?= e($selectedFolder['unit_name']) ?></span><?php endif; ?>
                    </div>
                    <div class="flex flex-wrap gap-2">
                        <?php if (!empty($selectedFolder['drive_url'])): ?><a href="<?= e($selectedFolder['drive_url']) ?>" target="_blank" class="kdl-btn bg-green-600 text-white"><i class="fab fa-google-drive"></i> Drive Folder</a><?php endif; ?>
                        <?php if ($canManage && $selectedFolder): ?>
                            <button onclick='kdlOpenFolderModal(<?= json_encode($selectedFolder, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP) ?>)' class="kdl-btn bg-slate-100 text-slate-700"><i class="fas fa-edit"></i> Edit Folder</button>
                            <button onclick="kdlOpenUploadModal(<?= (int)$selectedFolderId ?>)" class="kdl-btn bg-blue-600 text-white"><i class="fas fa-upload"></i> Upload</button>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <div class="kdl-card p-4">
                <form method="GET" class="grid grid-cols-1 md:grid-cols-4 gap-3 items-end">
                    <input type="hidden" name="module" value="kumpulan_dokumen_laporan">
                    <input type="hidden" name="folder_id" value="<?= (int)$selectedFolderId ?>">
                    <div class="md:col-span-2"><label class="text-xs font-bold text-slate-500">Cari dokumen</label><input class="kdl-input" name="q" value="<?= e($search) ?>" placeholder="Judul, jenis, catatan, nama file..."></div>
                    <div><label class="text-xs font-bold text-slate-500">Unit</label><select class="kdl-input" name="unit"><option value="">Semua Unit</option><?php foreach ($unitList as $u): ?><option value="<?= e($u) ?>" <?= $unitFilter===$u?'selected':'' ?>><?= e($u) ?></option><?php endforeach; ?></select></div>
                    <button class="kdl-btn bg-slate-800 text-white justify-center"><i class="fas fa-search"></i> Tampilkan</button>
                </form>
            </div>

            <div class="kdl-card overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="w-full kdl-table text-sm">
                        <thead><tr><th class="text-left">Dokumen</th><th class="text-left">Jenis</th><th class="text-left">Unit/Folder</th><th class="text-left">Upload</th><th class="text-left">Aksi</th></tr></thead>
                        <tbody>
                        <?php if (empty($files)): ?>
                            <tr><td colspan="5" class="text-center text-slate-500 py-10"><i class="fas fa-inbox text-3xl mb-2 block"></i>Belum ada dokumen pada folder/filter ini.</td></tr>
                        <?php else: foreach ($files as $file): ?>
                            <tr>
                                <td>
                                    <div class="font-bold text-slate-800"><?= e($file['doc_title']) ?></div>
                                    <div class="text-xs text-slate-500"><?= e($file['original_name'] ?: 'Dokumen') ?> <?= (int)$file['size_bytes']>0 ? '· '.e(kdl_format_size((int)$file['size_bytes'])) : '' ?></div>
                                    <?php if (!empty($file['note'])): ?><div class="text-xs text-slate-500 mt-1"><?= e($file['note']) ?></div><?php endif; ?>
                                </td>
                                <td><span class="kdl-pill bg-indigo-50 text-indigo-700"><?= e($file['doc_type']) ?></span></td>
                                <td><div class="font-semibold"><?= e($file['unit_name'] ?: '-') ?></div><div class="text-xs text-slate-500"><?= e($file['folder_name']) ?></div></td>
                                <td><div><?= e($file['uploaded_by_name'] ?: '-') ?></div><div class="text-xs text-slate-500"><?= e(date('d/m/Y H:i', strtotime($file['uploaded_at']))) ?></div></td>
                                <td>
                                    <div class="flex flex-wrap gap-2">
                                        <?php if (!empty($file['drive_file_url'])): ?><a class="kdl-btn bg-green-50 text-green-700 py-2" href="<?= e($file['drive_file_url']) ?>" target="_blank"><i class="fab fa-google-drive"></i> Buka di Drive</a><?php endif; ?>
                                        <?php if ($canManage): ?><form method="POST" onsubmit="return confirm('Hapus dokumen ini dari tampilan?')"><input type="hidden" name="kdl_action" value="delete_file"><input type="hidden" name="file_id" value="<?= (int)$file['id'] ?>"><button class="kdl-btn bg-red-50 text-red-700 py-2"><i class="fas fa-trash"></i></button></form><?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<?php if ($canManage): ?>
<div id="kdlFolderModal" class="kdl-modal"><div class="kdl-modal-box p-6"><div class="flex justify-between items-center mb-4"><h3 class="text-xl font-extrabold">Folder Dokumen</h3><button onclick="kdlCloseModal('kdlFolderModal')" class="text-slate-400 hover:text-slate-700"><i class="fas fa-times text-xl"></i></button></div><form method="POST" class="space-y-4"><input type="hidden" name="kdl_action" id="folderAction" value="create_folder"><input type="hidden" name="folder_id" id="folderId"><div><label class="text-sm font-bold">Nama Folder</label><input class="kdl-input" name="folder_name" id="folderName" required placeholder="Contoh: Laporan Bulanan IGD"></div><div><label class="text-sm font-bold">Unit Keperawatan</label><select class="kdl-input" name="unit_name" id="folderUnit"><option value="">Umum / Divisi</option><?php foreach ($unitList as $u): ?><option value="<?= e($u) ?>"><?= e($u) ?></option><?php endforeach; ?></select></div><div><label class="text-sm font-bold">Link Google Drive Folder <span class="text-red-500">*wajib diisi sebelum upload</span></label><input class="kdl-input" name="drive_url" id="folderDrive" placeholder="https://drive.google.com/drive/folders/..."><p class="text-xs text-slate-500 mt-1">Tempel link folder Drive unit ini (pastikan folder sudah di-share Editor ke akun layanan sistem). Upload dokumen baru tidak akan jalan jika field ini kosong.</p></div><div><label class="text-sm font-bold">Deskripsi</label><textarea class="kdl-input" name="description" id="folderDesc" rows="3"></textarea></div><div class="flex justify-end gap-2"><button type="button" onclick="kdlCloseModal('kdlFolderModal')" class="kdl-btn bg-slate-100 text-slate-700">Batal</button><button class="kdl-btn bg-blue-600 text-white"><i class="fas fa-save"></i> Simpan Folder</button></div></form></div></div>
<div id="kdlUploadModal" class="kdl-modal"><div class="kdl-modal-box p-6"><div class="flex justify-between items-center mb-4"><h3 class="text-xl font-extrabold">Upload Dokumen</h3><button onclick="kdlCloseModal('kdlUploadModal')" class="text-slate-400 hover:text-slate-700"><i class="fas fa-times text-xl"></i></button></div><form method="POST" enctype="multipart/form-data" class="space-y-4"><input type="hidden" name="kdl_action" value="upload_file"><input type="hidden" name="folder_id" id="uploadFolderId" value="<?= (int)$selectedFolderId ?>"><div><label class="text-sm font-bold">Judul Dokumen</label><input class="kdl-input" name="doc_title" placeholder="Contoh: Laporan Bulanan Mei 2026"></div><div><label class="text-sm font-bold">Jenis Dokumen</label><select class="kdl-input" name="doc_type"><option>Laporan Bulanan</option><option>Laporan Harian</option><option>SPO</option><option>Formulir</option><option>Dokumen Akreditasi</option><option>Notulen</option><option>Surat</option><option>Materi</option><option>Dokumen Lainnya</option></select></div><div><label class="text-sm font-bold">Upload File (otomatis tersimpan ke Google Drive)</label><input type="file" class="kdl-input" name="document_file" accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.jpg,.jpeg,.png,.zip,.rar,.txt"><p class="text-xs text-slate-500 mt-1">Maksimal 30 MB. File akan otomatis diupload ke folder Google Drive unit ini (pastikan folder sudah punya Link Google Drive lewat "Edit Folder").</p></div><div><label class="text-sm font-bold">Atau Tempel Link Google Drive (jika file sudah ada di Drive)</label><input class="kdl-input" name="drive_file_url" placeholder="https://drive.google.com/..."></div><div><label class="text-sm font-bold">Catatan</label><textarea class="kdl-input" name="note" rows="3"></textarea></div><div class="flex justify-end gap-2"><button type="button" onclick="kdlCloseModal('kdlUploadModal')" class="kdl-btn bg-slate-100 text-slate-700">Batal</button><button class="kdl-btn bg-blue-600 text-white"><i class="fas fa-upload"></i> Simpan Dokumen</button></div></form></div></div>
<script>
function kdlOpenFolderModal(data){
  document.getElementById('folderAction').value = data ? 'update_folder' : 'create_folder';
  document.getElementById('folderId').value = data ? data.id : '';
  document.getElementById('folderName').value = data ? data.folder_name : '';
  document.getElementById('folderUnit').value = data ? (data.unit_name || '') : '';
  document.getElementById('folderDrive').value = data ? (data.drive_url || '') : '';
  document.getElementById('folderDesc').value = data ? (data.description || '') : '';
  document.getElementById('kdlFolderModal').classList.add('show');
}
function kdlOpenUploadModal(folderId){ document.getElementById('uploadFolderId').value = folderId; document.getElementById('kdlUploadModal').classList.add('show'); }
function kdlCloseModal(id){ document.getElementById(id).classList.remove('show'); }
</script>
<?php endif; ?>
