<?php
declare(strict_types=1);

if (session_status() !== PHP_SESSION_ACTIVE) {
    // Penting: aplikasi perawat memakai session_name PERAWATSESSID.
    // Saat endpoint AJAX modul dipanggil langsung, tanpa ini session login tidak terbaca
    // sehingga tracking baca tersimpan sebagai user kosong dan tidak masuk rekap sosialisasi.
    if (session_name() !== 'PERAWATSESSID') {
        session_name('PERAWATSESSID');
    }
    session_start();
}

$action = (string)($_GET['action'] ?? '');
$pfpIsJsonAction = ($action === 'mark_read' && ($_SERVER['REQUEST_METHOD'] ?? '') === 'POST');

/*
|--------------------------------------------------------------------------
| Modul Kisi-Kisi Telusur Akreditasi Pokja Pelayanan Fokus Pasien (PFP)
|--------------------------------------------------------------------------
| Fitur:
| - Auto-create table saat modul dibuka.
| - Auto-seed data dari Excel yang sudah dikonversi ke JSON.
| - Kisi-kisi EP: AKP, HPK, PP, PAP, PAB, PKPO, KE.
| - Tracking user membaca bagian overview/pertanyaan/roleplay/bukti/checklist.
| - Dashboard keberhasilan sosialisasi per unit.
| - Export evaluasi per unit ke Excel compatible (.xls).
*/

if (!isset($conn) || !($conn instanceof mysqli)) {
    require_once __DIR__ . '/../../config/database.php';
    $conn = getConnection();
}

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

function pfp_query(mysqli $conn, string $sql): bool
{
    global $pfpIsJsonAction;

    $ok = $conn->query($sql);
    if (!$ok) {
        if (!$pfpIsJsonAction) {
            echo '<div class="mb-4 rounded-xl border border-red-200 bg-red-50 p-4 text-red-700"><b>SQL Error:</b> ' . e($conn->error) . '</div>';
        }
        return false;
    }
    return true;
}

function pfp_install(mysqli $conn): void
{
    pfp_query($conn, "CREATE TABLE IF NOT EXISTS pfp_kisi_items (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        source_no INT NOT NULL DEFAULT 0,
        bab VARCHAR(190) NOT NULL,
        kode_bab VARCHAR(20) NOT NULL,
        no_std VARCHAR(50) DEFAULT NULL,
        no_ep VARCHAR(50) DEFAULT NULL,
        elemen_penilaian TEXT,
        kode_metode VARCHAR(20) DEFAULT NULL,
        metode_telusur VARCHAR(120) DEFAULT NULL,
        kelengkapan_bukti TEXT,
        pertanyaan_utama MEDIUMTEXT,
        probing MEDIUMTEXT,
        roleplay MEDIUMTEXT,
        petugas_sasaran TEXT,
        lokasi_telusur TEXT,
        ekspektasi_jawaban MEDIUMTEXT,
        bukti_wajib MEDIUMTEXT,
        checklist MEDIUMTEXT,
        red_flags MEDIUMTEXT,
        dasar MEDIUMTEXT,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        UNIQUE KEY uniq_source_no (source_no),
        KEY idx_kode_bab (kode_bab),
        KEY idx_std_ep (no_std, no_ep)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

    pfp_query($conn, "CREATE TABLE IF NOT EXISTS pfp_read_logs (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        item_id BIGINT UNSIGNED NOT NULL,
        user_id BIGINT UNSIGNED DEFAULT NULL,
        employee_id BIGINT UNSIGNED DEFAULT NULL,
        user_name VARCHAR(190) DEFAULT NULL,
        username VARCHAR(100) DEFAULT NULL,
        unit_id BIGINT UNSIGNED DEFAULT NULL,
        unit_name VARCHAR(190) DEFAULT NULL,
        section_key ENUM('overview','pertanyaan','roleplay','bukti','checklist','all') NOT NULL DEFAULT 'overview',
        read_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        ip_address VARCHAR(60) DEFAULT NULL,
        user_agent VARCHAR(255) DEFAULT NULL,
        PRIMARY KEY (id),
        UNIQUE KEY uniq_read_once (item_id, employee_id, username, section_key),
        KEY idx_employee (employee_id),
        KEY idx_unit (unit_id),
        KEY idx_section (section_key),
        KEY idx_read_at (read_at)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

    pfp_query($conn, "CREATE TABLE IF NOT EXISTS pfp_assessment_followups (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        pokja VARCHAR(20) NOT NULL,
        ep_code VARCHAR(50) DEFAULT NULL,
        finding MEDIUMTEXT,
        root_cause MEDIUMTEXT,
        follow_up_plan MEDIUMTEXT NOT NULL,
        pic VARCHAR(190) DEFAULT NULL,
        target_period VARCHAR(100) DEFAULT NULL,
        status ENUM('Belum','Proses','Selesai','Terverifikasi') NOT NULL DEFAULT 'Belum',
        realization_date DATE DEFAULT NULL,
        realization_note MEDIUMTEXT,
        evidence_desc TEXT,
        evidence_link TEXT,
        evaluator_note MEDIUMTEXT,
        created_by VARCHAR(190) DEFAULT NULL,
        updated_by VARCHAR(190) DEFAULT NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        KEY idx_pokja (pokja),
        KEY idx_status (status),
        KEY idx_target (target_period)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

    $count = 0;
    $res = $conn->query("SELECT COUNT(*) AS total FROM pfp_kisi_items");
    if ($res instanceof mysqli_result) {
        $row = $res->fetch_assoc();
        $count = (int)($row['total'] ?? 0);
    }
    if ($count > 0) return;

    $seedFile = __DIR__ . '/data_seed_pfp.json';
    if (!file_exists($seedFile)) return;
    $records = json_decode((string)file_get_contents($seedFile), true);
    if (!is_array($records)) return;

    $stmt = $conn->prepare("INSERT INTO pfp_kisi_items
        (source_no,bab,kode_bab,no_std,no_ep,elemen_penilaian,kode_metode,metode_telusur,kelengkapan_bukti,pertanyaan_utama,probing,roleplay,petugas_sasaran,lokasi_telusur,ekspektasi_jawaban,bukti_wajib,checklist,red_flags,dasar)
        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
        ON DUPLICATE KEY UPDATE
        bab=VALUES(bab), kode_bab=VALUES(kode_bab), no_std=VALUES(no_std), no_ep=VALUES(no_ep), elemen_penilaian=VALUES(elemen_penilaian),
        kode_metode=VALUES(kode_metode), metode_telusur=VALUES(metode_telusur), kelengkapan_bukti=VALUES(kelengkapan_bukti), pertanyaan_utama=VALUES(pertanyaan_utama),
        probing=VALUES(probing), roleplay=VALUES(roleplay), petugas_sasaran=VALUES(petugas_sasaran), lokasi_telusur=VALUES(lokasi_telusur),
        ekspektasi_jawaban=VALUES(ekspektasi_jawaban), bukti_wajib=VALUES(bukti_wajib), checklist=VALUES(checklist), red_flags=VALUES(red_flags), dasar=VALUES(dasar)");
    if (!$stmt) return;

    foreach ($records as $r) {
        $sourceNo = (int)($r['source_no'] ?? 0);
        $bab = (string)($r['bab'] ?? '');
        $kodeBab = (string)($r['kode_bab'] ?? '');
        $noStd = (string)($r['no_std'] ?? '');
        $noEp = (string)($r['no_ep'] ?? '');
        $ep = (string)($r['elemen_penilaian'] ?? '');
        $kodeMetode = (string)($r['kode_metode'] ?? '');
        $metode = (string)($r['metode_telusur'] ?? '');
        $bukti = (string)($r['kelengkapan_bukti'] ?? '');
        $pertanyaan = (string)($r['pertanyaan_utama'] ?? '');
        $probing = (string)($r['probing'] ?? '');
        $roleplay = (string)($r['roleplay'] ?? '');
        $petugas = (string)($r['petugas_sasaran'] ?? '');
        $lokasi = (string)($r['lokasi_telusur'] ?? '');
        $ekspektasi = (string)($r['ekspektasi_jawaban'] ?? '');
        $buktiWajib = (string)($r['bukti_wajib'] ?? '');
        $checklist = (string)($r['checklist'] ?? '');
        $redFlags = (string)($r['red_flags'] ?? '');
        $dasar = (string)($r['dasar'] ?? '');
        $stmt->bind_param('issssssssssssssssss', $sourceNo, $bab, $kodeBab, $noStd, $noEp, $ep, $kodeMetode, $metode, $bukti, $pertanyaan, $probing, $roleplay, $petugas, $lokasi, $ekspektasi, $buktiWajib, $checklist, $redFlags, $dasar);
        $stmt->execute();
    }
    $stmt->close();
}

function pfp_current_user_payload(): array
{
    $u = $_SESSION['user'] ?? [];
    $username = (string)($_SESSION['username'] ?? $u['username'] ?? $u['nik'] ?? '');
    $nik = (string)($_SESSION['nik'] ?? $u['nik'] ?? $username);
    $unitName = (string)($_SESSION['unit_name'] ?? $_SESSION['unit'] ?? $u['unit_name'] ?? $u['unit'] ?? '-');

    return [
        'user_id' => (int)($_SESSION['user_id'] ?? $u['user_id'] ?? $u['account_id'] ?? $u['id'] ?? 0),
        'employee_id' => (int)($_SESSION['employee_id'] ?? $u['employee_id'] ?? 0),
        'user_name' => (string)($_SESSION['full_name'] ?? $_SESSION['nama_lengkap'] ?? $_SESSION['nama'] ?? $u['full_name'] ?? $u['nama_lengkap'] ?? $u['name'] ?? $u['nama'] ?? $username ?: 'User'),
        'username' => $username,
        'nik' => $nik,
        'unit_id' => (int)($_SESSION['unit_id'] ?? $u['unit_id'] ?? 0),
        'unit_name' => $unitName !== '' ? $unitName : '-',
    ];
}

function pfp_repair_read_log_employee_links(mysqli $conn): void
{
    // Perbaiki log lama yang tersimpan dengan employee_id keliru, tetapi username/NIK benar.
    try {
        $conn->query("UPDATE pfp_read_logs l
            INNER JOIN employees e ON (e.nik = l.username OR e.employee_code = l.username)
            LEFT JOIN units u ON u.id = e.unit_id
            SET l.employee_id = e.id,
                l.unit_id = e.unit_id,
                l.unit_name = COALESCE(u.name, l.unit_name),
                l.user_name = COALESCE(NULLIF(l.user_name,''), e.full_name)
            WHERE l.username IS NOT NULL
              AND l.username <> ''
              AND l.username NOT LIKE 'user_%'
              AND (l.employee_id IS NULL OR l.employee_id = 0 OR l.employee_id <> e.id)");
    } catch (Throwable $e) {
        // Abaikan agar modul tetap jalan walau struktur DB berbeda.
    }
}

function pfp_resolve_current_employee(mysqli $conn, array $u): array
{
    $employeeId = (int)($u['employee_id'] ?? 0);
    $username = trim((string)($u['username'] ?? ''));
    $nik = trim((string)($u['nik'] ?? ''));

    try {
        $where = [];
        $params = [];
        $types = '';

        if ($employeeId > 0) { $where[] = 'e.id = ?'; $params[] = $employeeId; $types .= 'i'; }
        if ($nik !== '' && stripos($nik, 'user_') !== 0) { $where[] = 'e.nik = ?'; $params[] = $nik; $types .= 's'; }
        if ($username !== '' && stripos($username, 'user_') !== 0) { $where[] = 'e.nik = ?'; $params[] = $username; $types .= 's'; $where[] = 'e.employee_code = ?'; $params[] = $username; $types .= 's'; }

        if (!$where) return $u;

        $sql = "SELECT e.id, e.nik, e.full_name, e.unit_id, COALESCE(un.name,'-') AS unit_name
                FROM employees e
                LEFT JOIN units un ON un.id=e.unit_id
                WHERE (" . implode(' OR ', $where) . ")
                ORDER BY CASE WHEN e.nik = ? THEN 0 WHEN e.nik = ? THEN 1 WHEN e.id = ? THEN 2 ELSE 3 END
                LIMIT 1";
        $stmt = $conn->prepare($sql);
        if (!$stmt) return $u;
        $params[] = $username; $types .= 's';
        $params[] = $nik; $types .= 's';
        $params[] = $employeeId; $types .= 'i';
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $row = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if ($row) {
            $u['employee_id'] = (int)$row['id'];
            $u['username'] = (string)($row['nik'] ?: $username);
            $u['nik'] = (string)($row['nik'] ?: $nik);
            $u['user_name'] = (string)($row['full_name'] ?: $u['user_name']);
            $u['unit_id'] = (int)($row['unit_id'] ?? 0);
            $u['unit_name'] = (string)($row['unit_name'] ?: $u['unit_name']);
        }
    } catch (Throwable $e) {
        // Tetap gunakan data session bila pencarian gagal.
    }
    return $u;
}

function pfp_log_join_condition(string $logAlias = 'l', string $empAlias = 'e'): string
{
    // Jika username/NIK tersedia, pakai itu sebagai kunci utama agar log lama dengan employee_id=user_id tetap terbaca benar.
    return "(({$logAlias}.username IS NOT NULL AND {$logAlias}.username<>'' AND {$logAlias}.username NOT LIKE 'user_%' AND ({$logAlias}.username={$empAlias}.nik OR {$logAlias}.username={$empAlias}.employee_code)) OR (({$logAlias}.username IS NULL OR {$logAlias}.username='' OR {$logAlias}.username LIKE 'user_%') AND {$logAlias}.employee_id={$empAlias}.id))";
}

function pfp_scalar(mysqli $conn, string $sql): int
{
    try {
        $res = $conn->query($sql);
        if (!$res) return 0;
        $row = $res->fetch_row();
        return (int)($row[0] ?? 0);
    } catch (Throwable $e) { return 0; }
}

function pfp_format_text($text): string
{
    $text = trim((string)$text);
    if ($text === '') return '<span class="text-slate-400 italic">Belum ada data.</span>';
    return nl2br(e($text));
}


function pfp_assessment_report_data(): array
{
    return [
        'title' => 'Laporan Hasil Asesmen Internal Akreditasi Area Pelayanan Fokus Pasien',
        'hospital' => 'RS BaliMéd Denpasar',
        'period' => 'Juni 2026',
        'basis' => 'Kisi-kisi telusur akreditasi PFP pada database modul: 332 Elemen Penilaian dari AKP, HPK, PP, PAP, PAB, PKPO, dan KE.',
        'summary' => 'Hasil telusur menunjukkan masing-masing pokja berada pada rentang 60–75% staf mampu membuktikan elemen penilaian yang diminta standar akreditasi. Kondisi ini dikategorikan tercapai parsial dan memerlukan akselerasi perbaikan pada dokumentasi, pembuktian implementasi, kesiapan roleplay staf, serta tindak lanjut monitoring evaluasi.',
        'pokja' => [
            'KE' => [
                'name' => 'Komunikasi dan Edukasi (KE)', 'total_ep' => 25, 'achievement' => '60–75%', 'status' => 'Tercapai parsial',
                'general' => 'Edukasi pasien dan keluarga telah berjalan, namun bukti dalam rekam medis belum konsisten. Staf masih perlu diperkuat dalam menilai hambatan edukasi, mengevaluasi pemahaman pasien, dan mendokumentasikan edukasi lanjutan.',
                'priority_ep' => [
                    ['KE 3b','Hambatan pasien dan keluarga dalam menerima edukasi dinilai sebelum pemberian edukasi dan dicatat di rekam medis.','Penilaian hambatan edukasi belum konsisten dicatat.'],
                    ['KE 4b','Pasien/keluarga dijelaskan mengenai hasil pengkajian, diagnosis, rencana asuhan, dan hasil pengobatan.','Dokumentasi edukasi belum lengkap pada semua rekam medis.'],
                    ['KE 4c','Edukasi cuci tangan, penggunaan obat aman, alat medis aman, diet/nutrisi, manajemen nyeri, dan rehabilitasi.','Edukasi keselamatan pasien belum seragam antar unit.'],
                    ['KE 5b','Proses pemberian edukasi didokumentasikan sesuai metode edukasi yang diterima pasien/keluarga.','Form edukasi belum selalu diisi lengkap.'],
                    ['KE 6c','Edukasi lanjutan di komunitas dan rujukan edukasi oleh jejaring utama.','Edukasi lanjutan saat pulang belum konsisten.'],
                    ['KE 1c','Tim/unit PKRS menyusun program promosi kesehatan rumah sakit setiap tahun.','Program, pelaksanaan, evaluasi, dan bukti PKRS perlu diperkuat.'],
                ],
                'root_causes' => ['Edukasi sering dilakukan verbal tetapi belum selalu dianggap sebagai bukti akreditasi.', 'Form edukasi belum menjadi komponen wajib verifikasi rekam medis.', 'Supervisi dokumentasi edukasi belum rutin pada semua shift.'],
                'rtl' => [
                    ['Refresh sosialisasi dokumentasi edukasi pasien dan keluarga.','Tim PKRS, Kepala Unit','Minggu I Juni 2026'],
                    ['Audit cepat 10 rekam medis per unit terkait form edukasi.','Mutu, Rekam Medis, Kepala Unit','Minggu II Juni 2026'],
                    ['Membuat checklist edukasi wajib: diagnosis, obat, cuci tangan, diet, nyeri, alat medis, rencana pulang.','PKRS dan Keperawatan','Minggu II Juni 2026'],
                    ['Coaching staf yang belum mampu menjelaskan alur edukasi.','Kepala Unit','Minggu II–III Juni 2026'],
                    ['Evaluasi ulang capaian dokumentasi edukasi.','Komite Mutu','Minggu IV Juni 2026'],
                ],
            ],
            'PKPO' => [
                'name' => 'Pelayanan Kefarmasian dan Penggunaan Obat (PKPO)', 'total_ep' => 53, 'achievement' => '60–75%', 'status' => 'Tercapai parsial',
                'general' => 'Pelayanan obat sudah berjalan, tetapi pembuktian pengelolaan high alert, LASA, obat emergensi, double check, edukasi obat pulang, serta pemantauan terapi obat belum seragam.',
                'priority_ep' => [
                    ['PKPO 1c','Bukti kajian sistem pelayanan kefarmasian dan penggunaan obat setiap tahun.','Kajian tahunan belum mudah ditunjukkan oleh unit.'],
                    ['PKPO 3.2b','Tata laksana obat emergensi untuk ketepatan dan kecepatan pemberian obat.','Bukti pengecekan troli emergency belum seragam.'],
                    ['PKPO 4.1e','Daftar obat pulang diserahkan kepada pasien disertai edukasi penggunaannya.','Edukasi obat pulang belum terdokumentasi konsisten.'],
                    ['PKPO 6a','Staf pemberi obat kompeten dan berwenang sesuai pembatasan yang ditetapkan.','Bukti kompetensi dan kewenangan klinis belum selalu siap.'],
                    ['PKPO 6c','Double checking untuk obat high alert.','Bukti double check belum lengkap pada semua unit.'],
                    ['PKPO 7a','Pemantauan terapi obat secara kolaboratif.','Monitoring efek terapi/efek samping belum terdokumentasi optimal.'],
                ],
                'root_causes' => ['Staf memahami 7 benar pemberian obat, namun belum semua dapat menunjukkan bukti kewenangan dan double check.', 'Edukasi obat pulang belum menjadi indikator wajib pasien pulang.', 'Monitoring obat high alert belum seragam antar ruangan.'],
                'rtl' => [
                    ['Review ulang daftar high alert, LASA, dan obat emergensi di seluruh unit.','Instalasi Farmasi','Minggu I Juni 2026'],
                    ['Audit troli emergency dan bukti pengecekan harian/mingguan.','Farmasi, Keperawatan','Minggu I–II Juni 2026'],
                    ['Sosialisasi ulang double check obat high alert.','Farmasi, Kepala Unit','Minggu II Juni 2026'],
                    ['Integrasi edukasi obat pulang dalam checklist pasien pulang.','Farmasi, Keperawatan, Rekam Medis','Minggu II–III Juni 2026'],
                    ['Audit dokumentasi pemberian obat dan edukasi obat pulang.','Komite Mutu','Minggu IV Juni 2026'],
                ],
            ],
            'PAB' => [
                'name' => 'Pelayanan Anestesi dan Bedah (PAB)', 'total_ep' => 38, 'achievement' => '60–75%', 'status' => 'Tercapai parsial',
                'general' => 'Pelayanan anestesi, sedasi, dan bedah telah berjalan, namun pengisian asesmen prasedasi, informed consent anestesi/sedasi, pemantauan intraoperatif, dan dokumentasi pasca anestesi perlu diperkuat.',
                'priority_ep' => [
                    ['PAB 1a','Regulasi pelayanan anestesi, sedasi, dan pembedahan.','Staf belum semua mampu menjelaskan regulasi dan alur.'],
                    ['PAB 1b','Pelayanan anestesi dan sedasi memenuhi kebutuhan pasien.','Bukti pemenuhan kebutuhan pasien belum selalu lengkap.'],
                    ['PAB 2c','PPA luar rumah sakit memiliki rekomendasi/izin sesuai regulasi.','Bukti kredensial atau rekomendasi belum mudah ditunjukkan.'],
                    ['PAB 3.2a','Pengkajian prasedasi dicatat dalam rekam medis.','Dokumentasi asesmen prasedasi belum konsisten.'],
                    ['PAB 5b','Informasi dokter anestesi didokumentasikan dalam persetujuan anestesi/sedasi.','Informed consent anestesi belum lengkap pada sebagian rekam medis.'],
                    ['PAB 6a','Frekuensi dan jenis pemantauan selama anestesi dan pembedahan sesuai status pasien.','Form monitoring intraoperatif perlu diperkuat.'],
                ],
                'root_causes' => ['Dokumentasi fase pra, intra, dan pasca tindakan belum selalu lengkap.', 'Verifikasi berkas sebelum tindakan belum sepenuhnya memakai checklist standar.', 'Bukti kredensial dan kewenangan klinis belum selalu tersedia saat telusur.'],
                'rtl' => [
                    ['Audit 20 berkas tindakan operasi/anestesi terakhir.','Kepala OK, Rekam Medis, Komite Medik','Minggu I Juni 2026'],
                    ['Verifikasi asesmen pra-anestesi, informed consent, sign in, time out, sign out.','OK, Anestesi, Keperawatan','Minggu II Juni 2026'],
                    ['Simulasi roleplay telusur PAB untuk staf OK, RR, dan anestesi.','Asesor Internal','Minggu II–III Juni 2026'],
                    ['Penyediaan folder bukti PAB di unit OK.','Kepala OK','Minggu III Juni 2026'],
                    ['Evaluasi ulang kepatuhan dokumentasi PAB.','Komite Mutu','Minggu IV Juni 2026'],
                ],
            ],
            'PAP' => [
                'name' => 'Pelayanan dan Asuhan Pasien (PAP)', 'total_ep' => 52, 'achievement' => '60–75%', 'status' => 'Tercapai parsial',
                'general' => 'Asuhan pasien telah diberikan oleh PPA, namun belum seluruhnya terdokumentasi secara lengkap, seragam, terintegrasi, dan dievaluasi berkala.',
                'priority_ep' => [
                    ['PAP 1b','Asuhan seragam diberikan kepada setiap pasien.','Variasi praktik antar unit dan shift masih ditemukan.'],
                    ['PAP 1.1e','Pasien tindakan invasif/berisiko di rawat jalan dikaji dan didokumentasikan.','Dokumentasi rawat jalan belum konsisten.'],
                    ['PAP 1.2b','Rencana asuhan dievaluasi berkala dan didokumentasikan setiap PPA.','Evaluasi rencana asuhan belum rutin tertulis.'],
                    ['PAP 2b','Pelayanan pasien risiko tinggi dan pelayanan risiko tinggi.','Identifikasi dan dokumentasi pasien risiko tinggi perlu diperkuat.'],
                    ['PAP 3d','Bukti terapi gizi terintegrasi pada pasien risiko gizi.','Rencana, pemberian, dan evaluasi gizi belum lengkap.'],
                    ['PAP 4a','Skrining, pengkajian, dan tata laksana nyeri.','Dokumentasi nyeri belum konsisten sampai evaluasi ulang.'],
                ],
                'root_causes' => ['CPPT belum sepenuhnya menggambarkan kolaborasi PPA.', 'Rencana asuhan belum selalu dievaluasi dan diperbarui.', 'Pasien risiko tinggi belum selalu diberi penanda dan rencana asuhan khusus.'],
                'rtl' => [
                    ['Audit CPPT dan rencana asuhan pada pasien rawat inap.','Kepala Unit, Rekam Medis','Minggu I–II Juni 2026'],
                    ['Coaching dokumentasi asuhan berbasis masalah pasien.','Kasubdiv Ranap/Rajal','Minggu II Juni 2026'],
                    ['Penguatan form pasien risiko tinggi dan tindakan invasif.','Komite Mutu, Keperawatan','Minggu II–III Juni 2026'],
                    ['Audit skrining nyeri, reassessment nyeri, dan terapi gizi.','Tim Mutu Unit','Minggu III Juni 2026'],
                    ['Evaluasi ulang kepatuhan dokumentasi PAP.','Komite Mutu','Minggu IV Juni 2026'],
                ],
            ],
            'PP' => [
                'name' => 'Pengkajian Pasien (PP)', 'total_ep' => 58, 'achievement' => '60–75%', 'status' => 'Tercapai parsial',
                'general' => 'Asesmen awal telah berjalan, namun kelengkapan isi minimal pengkajian awal, pengkajian ulang, risiko nutrisi, serta bukti pengawasan laboratorium dan radiologi perlu disiapkan lebih baik.',
                'priority_ep' => [
                    ['PP 1b','Isi minimal pengkajian awal meliputi poin yang ditetapkan.','Pengisian asesmen awal belum lengkap pada semua berkas.'],
                    ['PP 1.2a','Kriteria risiko nutrisional ditetapkan bersama staf kompeten.','Skrining nutrisi belum seragam pemahamannya.'],
                    ['PP 2d','Pengkajian ulang oleh PPA sesuai interval regulasi.','Reassessment belum selalu tepat waktu.'],
                    ['PP 3.1b','Bukti tanggung jawab pimpinan laboratorium.','Bukti pengawasan laboratorium perlu disiapkan.'],
                    ['PP 3.4b','Bukti evaluasi/audit semua reagen.','Audit reagen belum mudah ditunjukkan saat telusur.'],
                    ['PP 4.1b','Bukti pengawasan pelayanan radiologi oleh penanggung jawab radiologi.','Bukti supervisi radiologi perlu dilengkapi.'],
                ],
                'root_causes' => ['Asesmen awal dilakukan, tetapi item wajib belum seluruhnya lengkap.', 'Pengkajian ulang belum dipahami sebagai bukti kesinambungan asuhan.', 'Bukti mutu penunjang diagnostik belum tersosialisasi sampai unit pengguna layanan.'],
                'rtl' => [
                    ['Audit kelengkapan asesmen awal dan asesmen ulang.','Rekam Medis, Keperawatan, Komite Medik','Minggu I Juni 2026'],
                    ['Sosialisasi interval pengkajian ulang kepada PPA.','Komite Medik, Keperawatan','Minggu II Juni 2026'],
                    ['Penyusunan folder bukti pengawasan laboratorium dan radiologi.','Kepala Penunjang Medis','Minggu II Juni 2026'],
                    ['Audit bukti evaluasi reagen dan mutu radiologi.','Komite Mutu','Minggu III Juni 2026'],
                    ['Evaluasi ulang kesiapan PP.','Asesor Internal','Minggu IV Juni 2026'],
                ],
            ],
            'HPK' => [
                'name' => 'Hak Pasien dan Keluarga (HPK)', 'total_ep' => 39, 'achievement' => '60–75%', 'status' => 'Tercapai parsial',
                'general' => 'Penghormatan hak pasien telah berjalan, namun pembuktian informed consent, edukasi hak pasien, dokumentasi pengelolaan nyeri, dan identitas pemberi persetujuan masih perlu diperkuat.',
                'priority_ep' => [
                    ['HPK 1a','Regulasi hak pasien dan keluarga diterapkan.','Staf belum semua mampu menjelaskan hak pasien secara lengkap.'],
                    ['HPK 2b','Edukasi kondisi medis, diagnosis, rencana perawatan dan tindakan.','Edukasi medis belum selalu terdokumentasi lengkap.'],
                    ['HPK 2.2a','Hak pasien mendapatkan pengkajian dan pengelolaan nyeri.','Dokumentasi pengelolaan nyeri belum konsisten.'],
                    ['HPK 4b','Informasi pemeriksaan, tindakan, dan pengobatan yang memerlukan informed consent.','Bukti pemberian informasi belum lengkap.'],
                    ['HPK 4.1b','Informed consent dilakukan staf kompeten dengan bahasa mudah dipahami.','Validasi pemberi informasi perlu diperkuat.'],
                    ['HPK 4.2b','Rekam medis mencantumkan nama individu yang menyatakan persetujuan.','Identitas pemberi persetujuan belum selalu lengkap.'],
                ],
                'root_causes' => ['Proses informed consent dilakukan, tetapi dokumentasi belum konsisten.', 'Edukasi hak pasien belum dipahami merata oleh seluruh staf.', 'Form persetujuan tindakan belum selalu diisi lengkap.'],
                'rtl' => [
                    ['Refresh sosialisasi HPK dan informed consent.','Komite Medik, Keperawatan, Mutu','Minggu I Juni 2026'],
                    ['Audit 20 rekam medis terkait informed consent.','Rekam Medis, Komite Mutu','Minggu II Juni 2026'],
                    ['Simulasi wawancara staf tentang hak pasien.','Asesor Internal, Kepala Unit','Minggu II–III Juni 2026'],
                    ['Perbaikan checklist kelengkapan informed consent.','Rekam Medis','Minggu III Juni 2026'],
                    ['Evaluasi ulang kepatuhan HPK.','Komite Mutu','Minggu IV Juni 2026'],
                ],
            ],
            'AKP' => [
                'name' => 'Akses dan Kontinuitas Pelayanan (AKP)', 'total_ep' => 67, 'achievement' => '60–75%', 'status' => 'Tercapai parsial',
                'general' => 'Alur akses pasien, transfer, rujukan, CPPT, edukasi risiko, dan kesinambungan pelayanan telah berjalan, namun pembuktiannya belum konsisten di seluruh unit.',
                'priority_ep' => [
                    ['AKP 1a','Regulasi akses dan kesinambungan pelayanan ditetapkan.','Staf belum semua memahami regulasi AKP secara utuh.'],
                    ['AKP 3d','Perkembangan pasien didokumentasikan para PPA di CPPT.','CPPT belum konsisten terintegrasi antar PPA.'],
                    ['AKP 4b','Formulir transfer internal meliputi komponen wajib.','Form transfer belum selalu lengkap.'],
                    ['AKP 5.2b','Edukasi risiko medis akibat asuhan medis yang belum lengkap.','Edukasi risiko belum konsisten terdokumentasi.'],
                    ['AKP 5.4b','Rujukan pasien dilakukan sesuai kebutuhan kesinambungan asuhan.','Dokumentasi alasan dan proses rujukan perlu diperkuat.'],
                    ['AKP 5.5e','Pasien dan keluarga dijelaskan bila rujukan tidak dapat dilaksanakan.','Bukti komunikasi rujukan belum lengkap.'],
                ],
                'root_causes' => ['Form transfer dan rujukan belum selalu dilakukan verifikasi kelengkapan.', 'CPPT belum sepenuhnya menggambarkan kesinambungan pelayanan.', 'Edukasi risiko saat rujukan/pulang belum selalu terdokumentasi.'],
                'rtl' => [
                    ['Audit form transfer internal dan rujukan.','Kepala Unit, Rekam Medis','Minggu I–II Juni 2026'],
                    ['Penguatan CPPT terintegrasi antar PPA.','Keperawatan, Komite Medik','Minggu II Juni 2026'],
                    ['Sosialisasi ulang alur rujukan dan edukasi risiko.','IGD, Rawat Inap, Rawat Jalan','Minggu II–III Juni 2026'],
                    ['Simulasi telusur AKP di IGD, rawat inap, poliklinik, dan OK.','Asesor Internal','Minggu III Juni 2026'],
                    ['Evaluasi ulang kelengkapan AKP.','Komite Mutu','Minggu IV Juni 2026'],
                ],
            ],
        ],
        'system_findings' => [
            'Dokumentasi belum konsisten pada edukasi, CPPT, informed consent, asesmen ulang, nyeri, obat pulang, transfer, dan rujukan pasien.',
            'Staf belum seragam dalam menjawab roleplay; sebagian mampu menjelaskan praktik tetapi belum mengaitkan dengan standar dan EP.',
            'Bukti implementasi belum tersusun dalam folder yang mudah ditunjukkan saat telusur.',
            'Monitoring dan evaluasi belum selalu sampai pada analisis, PIC, target waktu, tindak lanjut, dan evaluasi ulang.',
            'Terdapat variasi praktik antar unit dan antar shift, terutama pada dokumentasi dan komunikasi pasien/keluarga.',
        ],
        'weekly_plan' => [
            ['Minggu I Juni 2026','Validasi regulasi, folder bukti, EP prioritas, kesiapan kepala unit, dan audit awal dokumen.'],
            ['Minggu II Juni 2026','Audit rekam medis terfokus: CPPT, edukasi, informed consent, asesmen, transfer, rujukan, obat.'],
            ['Minggu III Juni 2026','Observasi lapangan, roleplay staf, coaching unit, dan pemenuhan bukti implementasi.'],
            ['Minggu IV Juni 2026','Re-asesmen internal, validasi bukti perbaikan, dan penyusunan laporan akhir tindak lanjut.'],
        ],
        'targets' => [
            ['Kemampuan staf membuktikan EP','60–75%','Minimal 85%'],
            ['Kelengkapan bukti rekam medis','Parsial','Minimal 90% pada sampel audit'],
            ['Kesiapan folder bukti pokja','Belum seragam','100% pokja tersedia'],
            ['Kesiapan kepala unit menjelaskan EP','Bervariasi','100% kepala unit siap'],
            ['Kesiapan staf menjawab roleplay','Belum merata','Minimal 85% staf sampel mampu menjawab'],
            ['Bukti monitoring dan tindak lanjut','Parsial','Semua pokja memiliki RTL terdokumentasi'],
        ],
    ];
}

function pfp_seed_assessment_followups(mysqli $conn, array $report): void
{
    $count = 0;
    try {
        $res = $conn->query("SELECT COUNT(*) AS total FROM pfp_assessment_followups");
        if ($res instanceof mysqli_result && ($row = $res->fetch_assoc())) $count = (int)($row['total'] ?? 0);
    } catch (Throwable $e) { return; }
    if ($count > 0) return;

    $stmt = $conn->prepare("INSERT INTO pfp_assessment_followups
        (pokja, ep_code, finding, root_cause, follow_up_plan, pic, target_period, status, created_by)
        VALUES (?,?,?,?,?,?,?,?,?)");
    if (!$stmt) return;

    foreach (($report['pokja'] ?? []) as $kode => $p) {
        $rootCause = implode("\n", array_map('strval', $p['root_causes'] ?? []));
        $priorityFindings = [];
        foreach (($p['priority_ep'] ?? []) as $ep) {
            $priorityFindings[] = ($ep[0] ?? '') . ' - ' . ($ep[2] ?? '');
        }
        $findingSummary = implode("\n", $priorityFindings);
        foreach (($p['rtl'] ?? []) as $rtl) {
            $pokja = (string)$kode;
            $epCode = '';
            $finding = $findingSummary;
            $root = $rootCause;
            $plan = (string)($rtl[0] ?? '');
            $pic = (string)($rtl[1] ?? '');
            $target = (string)($rtl[2] ?? '');
            $status = 'Belum';
            $createdBy = 'Seed laporan asesmen Juni 2026';
            $stmt->bind_param('sssssssss', $pokja, $epCode, $finding, $root, $plan, $pic, $target, $status, $createdBy);
            $stmt->execute();
        }
    }
    $stmt->close();
}

function pfp_get_assessment_followups(mysqli $conn, string $pokjaFilter = '', string $statusFilter = ''): array
{
    $where = [];
    $params = [];
    $types = '';
    if ($pokjaFilter !== '') { $where[] = 'pokja = ?'; $params[] = $pokjaFilter; $types .= 's'; }
    if ($statusFilter !== '') { $where[] = 'status = ?'; $params[] = $statusFilter; $types .= 's'; }
    $sql = "SELECT * FROM pfp_assessment_followups" . ($where ? " WHERE " . implode(' AND ', $where) : '') . " ORDER BY FIELD(pokja,'AKP','HPK','PP','PAP','PAB','PKPO','KE'), id";
    $rows = [];
    $stmt = $conn->prepare($sql);
    if ($stmt) {
        if ($params) $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $res = $stmt->get_result();
        if ($res instanceof mysqli_result) while ($r = $res->fetch_assoc()) $rows[] = $r;
        $stmt->close();
    }
    return $rows;
}

function pfp_status_badge_class(string $status): string
{
    return match ($status) {
        'Terverifikasi' => 'bg-emerald-100 text-emerald-700',
        'Selesai' => 'bg-blue-100 text-blue-700',
        'Proses' => 'bg-amber-100 text-amber-700',
        default => 'bg-slate-100 text-slate-600',
    };
}

function pfp_report_cell($value): string
{
    return e((string)$value);
}

pfp_install($conn);
pfp_seed_assessment_followups($conn, pfp_assessment_report_data());
pfp_repair_read_log_employee_links($conn);

$sections = ['overview' => 'Ringkasan EP', 'pertanyaan' => 'Pertanyaan', 'roleplay' => 'Role Play', 'bukti' => 'Bukti', 'checklist' => 'Checklist'];

if ($action === 'mark_read' && ($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
    while (ob_get_level() > 0) { @ob_end_clean(); }
    header('Content-Type: application/json; charset=utf-8');

    $itemId = (int)($_POST['item_id'] ?? 0);
    $section = (string)($_POST['section_key'] ?? 'overview');
    if (!array_key_exists($section, $sections)) {
        $section = 'overview';
    }

    if ($itemId <= 0) {
        echo json_encode(['success' => false, 'message' => 'Item tidak valid.']);
        exit;
    }

    $checkItem = $conn->prepare("SELECT id FROM pfp_kisi_items WHERE id=? AND is_active=1 LIMIT 1");
    if ($checkItem) {
        $checkItem->bind_param('i', $itemId);
        $checkItem->execute();
        $exists = $checkItem->get_result()->fetch_assoc();
        $checkItem->close();
        if (!$exists) {
            echo json_encode(['success' => false, 'message' => 'Data EP tidak ditemukan.']);
            exit;
        }
    }

    $u = pfp_resolve_current_employee($conn, pfp_current_user_payload());
    if ((int)$u['employee_id'] <= 0 || trim((string)$u['username']) === '' || strpos((string)$u['username'], 'user_') === 0) {
        echo json_encode(['success' => false, 'message' => 'Session login tidak terbaca. Silakan refresh halaman atau login ulang, lalu klik Tandai dibaca lagi.']);
        exit;
    }

    $ip = substr((string)($_SERVER['REMOTE_ADDR'] ?? ''), 0, 60);
    $ua = substr((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 250);

    $stmt = $conn->prepare("INSERT INTO pfp_read_logs (item_id,user_id,employee_id,user_name,username,unit_id,unit_name,section_key,read_at,ip_address,user_agent)
        VALUES (?,?,?,?,?,?,?,?,NOW(),?,?)
        ON DUPLICATE KEY UPDATE
            read_at=NOW(),
            user_name=VALUES(user_name),
            unit_id=VALUES(unit_id),
            unit_name=VALUES(unit_name),
            ip_address=VALUES(ip_address),
            user_agent=VALUES(user_agent)");

    if (!$stmt) {
        echo json_encode(['success' => false, 'message' => 'Prepare gagal: ' . $conn->error]);
        exit;
    }

    $stmt->bind_param(
        'iiississss',
        $itemId,
        $u['user_id'],
        $u['employee_id'],
        $u['user_name'],
        $u['username'],
        $u['unit_id'],
        $u['unit_name'],
        $section,
        $ip,
        $ua
    );
    $ok = $stmt->execute();
    $err = $stmt->error ?: $conn->error;
    $stmt->close();

    echo json_encode([
        'success' => (bool)$ok,
        'message' => $ok ? 'Bagian sudah ditandai dibaca.' : ('Gagal menyimpan: ' . $err)
    ]);
    exit;
}


if ($action === 'save_assessment_followup' && ($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
    $id = (int)($_POST['id'] ?? 0);
    $status = (string)($_POST['status'] ?? 'Belum');
    if (!in_array($status, ['Belum','Proses','Selesai','Terverifikasi'], true)) $status = 'Belum';
    $realizationDate = trim((string)($_POST['realization_date'] ?? ''));
    $realizationNote = trim((string)($_POST['realization_note'] ?? ''));
    $evidenceDesc = trim((string)($_POST['evidence_desc'] ?? ''));
    $evidenceLink = trim((string)($_POST['evidence_link'] ?? ''));
    $evaluatorNote = trim((string)($_POST['evaluator_note'] ?? ''));
    $updatedBy = pfp_current_user_payload()['user_name'] ?? 'User';

    if ($id > 0) {
        $stmt = $conn->prepare("UPDATE pfp_assessment_followups
            SET status=?, realization_date=NULLIF(?,''), realization_note=?, evidence_desc=?, evidence_link=?, evaluator_note=?, updated_by=?
            WHERE id=?");
        if ($stmt) {
            $stmt->bind_param('sssssssi', $status, $realizationDate, $realizationNote, $evidenceDesc, $evidenceLink, $evaluatorNote, $updatedBy, $id);
            $stmt->execute();
            $stmt->close();
        }
    }
    $redir = '?module=kisi_pfp&tab=laporan_asesmen&rtl_saved=1';
    if (!empty($_POST['rtl_pokja'])) $redir .= '&rtl_pokja=' . urlencode((string)$_POST['rtl_pokja']);
    if (!empty($_POST['rtl_status'])) $redir .= '&rtl_status=' . urlencode((string)$_POST['rtl_status']);
    header('Location: ' . $redir);
    exit;
}

if ($action === 'export_assessment_followup') {
    $pokjaFilter = strtoupper(trim((string)($_GET['rtl_pokja'] ?? '')));
    $statusFilter = trim((string)($_GET['rtl_status'] ?? ''));
    $rows = pfp_get_assessment_followups($conn, $pokjaFilter, $statusFilter);
    header('Content-Type: application/vnd.ms-excel; charset=utf-8');
    header('Content-Disposition: attachment; filename="monitoring_rtl_asesmen_pfp_juni_2026_' . date('Ymd_His') . '.xls"');
    echo "<html><head><meta charset='UTF-8'></head><body>";
    echo "<h2>Monitoring Tindak Lanjut Laporan Hasil Asesmen PFP</h2>";
    echo "<p><b>Periode:</b> Juni 2026<br><b>Filter Pokja:</b> " . e($pokjaFilter ?: 'Semua') . "<br><b>Filter Status:</b> " . e($statusFilter ?: 'Semua') . "<br><b>Tanggal Export:</b> " . date('d/m/Y H:i') . "</p>";
    echo "<table border='1' cellpadding='5' cellspacing='0'>";
    echo "<tr style='background:#dbeafe;font-weight:bold'><th>No</th><th>Pokja</th><th>EP/Area</th><th>Temuan</th><th>Akar Masalah</th><th>Rencana Tindak Lanjut</th><th>PIC</th><th>Target</th><th>Status</th><th>Tanggal Realisasi</th><th>Catatan Realisasi</th><th>Bukti Sosialisasi/Implementasi</th><th>Link Bukti</th><th>Catatan Evaluator</th><th>Updated At</th></tr>";
    $no=1;
    foreach ($rows as $r) {
        echo '<tr><td>'.$no++.'</td><td>'.e($r['pokja']).'</td><td>'.e($r['ep_code']).'</td><td>'.nl2br(e($r['finding'])).'</td><td>'.nl2br(e($r['root_cause'])).'</td><td>'.e($r['follow_up_plan']).'</td><td>'.e($r['pic']).'</td><td>'.e($r['target_period']).'</td><td>'.e($r['status']).'</td><td>'.e($r['realization_date']).'</td><td>'.nl2br(e($r['realization_note'])).'</td><td>'.nl2br(e($r['evidence_desc'])).'</td><td>'.e($r['evidence_link']).'</td><td>'.nl2br(e($r['evaluator_note'])).'</td><td>'.e($r['updated_at']).'</td></tr>';
    }
    echo "</table></body></html>";
    exit;
}

if ($action === 'export_assessment_report') {
    $report = pfp_assessment_report_data();
    header('Content-Type: application/vnd.ms-excel; charset=utf-8');
    header('Content-Disposition: attachment; filename="laporan_hasil_asesmen_akreditasi_pfp_juni_2026_' . date('Ymd_His') . '.xls"');
    echo "<html><head><meta charset='UTF-8'></head><body>";
    echo "<h2>" . pfp_report_cell($report['title']) . "</h2>";
    echo "<p><b>Rumah Sakit:</b> " . pfp_report_cell($report['hospital']) . "<br><b>Periode RTL:</b> " . pfp_report_cell($report['period']) . "<br><b>Dasar:</b> " . pfp_report_cell($report['basis']) . "</p>";
    echo "<h3>Ringkasan Capaian Pokja</h3><table border='1' cellpadding='5' cellspacing='0'><tr style='background:#dbeafe;font-weight:bold'><th>Pokja</th><th>Jumlah EP</th><th>Capaian</th><th>Status</th><th>Gambaran Umum</th></tr>";
    foreach ($report['pokja'] as $kode => $p) {
        echo "<tr><td>" . pfp_report_cell($kode . ' - ' . $p['name']) . "</td><td>" . (int)$p['total_ep'] . "</td><td>" . pfp_report_cell($p['achievement']) . "</td><td>" . pfp_report_cell($p['status']) . "</td><td>" . pfp_report_cell($p['general']) . "</td></tr>";
    }
    echo "</table>";
    foreach ($report['pokja'] as $kode => $p) {
        echo "<h3>" . pfp_report_cell($kode . ' - ' . $p['name']) . "</h3>";
        echo "<h4>EP Prioritas Belum Tercapai Optimal</h4><table border='1' cellpadding='5' cellspacing='0'><tr style='background:#fee2e2;font-weight:bold'><th>No EP</th><th>Elemen Penilaian</th><th>Masalah Utama</th></tr>";
        foreach ($p['priority_ep'] as $ep) {
            echo "<tr><td>" . pfp_report_cell($ep[0]) . "</td><td>" . pfp_report_cell($ep[1]) . "</td><td>" . pfp_report_cell($ep[2]) . "</td></tr>";
        }
        echo "</table><h4>Akar Masalah</h4><ul>";
        foreach ($p['root_causes'] as $rc) echo "<li>" . pfp_report_cell($rc) . "</li>";
        echo "</ul><h4>Rencana Tindak Lanjut Juni 2026</h4><table border='1' cellpadding='5' cellspacing='0'><tr style='background:#dcfce7;font-weight:bold'><th>Tindak Lanjut</th><th>PIC</th><th>Target</th></tr>";
        foreach ($p['rtl'] as $rtl) {
            echo "<tr><td>" . pfp_report_cell($rtl[0]) . "</td><td>" . pfp_report_cell($rtl[1]) . "</td><td>" . pfp_report_cell($rtl[2]) . "</td></tr>";
        }
        echo "</table>";
    }
    echo "<h3>Temuan Sistemik Lintas Pokja</h3><ul>";
    foreach ($report['system_findings'] as $f) echo "<li>" . pfp_report_cell($f) . "</li>";
    echo "</ul><h3>Rencana Mingguan Juni 2026</h3><table border='1' cellpadding='5' cellspacing='0'><tr style='background:#fef3c7;font-weight:bold'><th>Minggu</th><th>Fokus</th></tr>";
    foreach ($report['weekly_plan'] as $w) echo "<tr><td>" . pfp_report_cell($w[0]) . "</td><td>" . pfp_report_cell($w[1]) . "</td></tr>";
    echo "</table><h3>Target Akhir Juni 2026</h3><table border='1' cellpadding='5' cellspacing='0'><tr style='background:#e0e7ff;font-weight:bold'><th>Parameter</th><th>Kondisi Saat Ini</th><th>Target</th></tr>";
    foreach ($report['targets'] as $t) echo "<tr><td>" . pfp_report_cell($t[0]) . "</td><td>" . pfp_report_cell($t[1]) . "</td><td>" . pfp_report_cell($t[2]) . "</td></tr>";
    echo "</table></body></html>";
    exit;
}

if ($action === 'export_unit') {
    $unitId = (int)($_GET['unit_id'] ?? 0);
    $unitWhere = $unitId > 0 ? ' AND e.unit_id = ' . $unitId : '';
    $unitName = 'Semua Unit';
    if ($unitId > 0) {
        $ur = $conn->query("SELECT name FROM units WHERE id={$unitId} LIMIT 1");
        if ($ur instanceof mysqli_result && ($urow = $ur->fetch_assoc())) $unitName = (string)$urow['name'];
    }
    $totalItems = max(1, pfp_scalar($conn, "SELECT COUNT(*) FROM pfp_kisi_items WHERE is_active=1"));
    $totalSections = $totalItems * 5;
    $logJoinEmployee = pfp_log_join_condition('l', 'e');
    $sql = "SELECT e.id AS employee_id, e.full_name, e.nik, u.name AS unit_name,
                   COUNT(DISTINCT CONCAT(l.item_id,':',l.section_key)) AS read_sections,
                   COUNT(DISTINCT l.item_id) AS read_items,
                   MAX(l.read_at) AS last_read
            FROM employees e
            LEFT JOIN units u ON u.id=e.unit_id
            LEFT JOIN pfp_read_logs l ON {$logJoinEmployee}
            WHERE e.employment_status='aktif' {$unitWhere}
            GROUP BY e.id, e.full_name, e.nik, u.name
            ORDER BY u.name, e.full_name";
    $rows = [];
    $res = $conn->query($sql);
    if ($res instanceof mysqli_result) while ($r=$res->fetch_assoc()) $rows[]=$r;

    header('Content-Type: application/vnd.ms-excel; charset=utf-8');
    header('Content-Disposition: attachment; filename="evaluasi_sosialisasi_pfp_' . preg_replace('/[^A-Za-z0-9_\-]/','_', $unitName) . '_' . date('Ymd_His') . '.xls"');
    echo "<html><head><meta charset='UTF-8'></head><body>";
    echo "<h2>Evaluasi Sosialisasi Kisi-Kisi Telusur Akreditasi PFP</h2>";
    echo "<p><b>Unit:</b> " . e($unitName) . "<br><b>Tanggal Export:</b> " . date('d/m/Y H:i') . "<br><b>Total EP:</b> {$totalItems}</p>";
    echo "<table border='1' cellpadding='5' cellspacing='0'>";
    echo "<tr style='background:#dbeafe;font-weight:bold'><th>No</th><th>NIK</th><th>Nama User</th><th>Unit</th><th>EP Dibaca</th><th>Bagian Dibaca</th><th>Progress</th><th>Terakhir Baca</th><th>Status</th></tr>";
    $no=1;
    foreach ($rows as $r) {
        $pct = min(100, round(((int)$r['read_sections'] / $totalSections) * 100, 1));
        $status = $pct >= 100 ? 'Lengkap' : ($pct > 0 ? 'Proses' : 'Belum Baca');
        echo '<tr>';
        echo '<td>'.$no++.'</td><td>'.e($r['nik']).'</td><td>'.e($r['full_name']).'</td><td>'.e($r['unit_name']).'</td><td>'.(int)$r['read_items'].'/'.$totalItems.'</td><td>'.(int)$r['read_sections'].'/'.$totalSections.'</td><td>'.$pct.'%</td><td>'.e($r['last_read'] ?: '-').'</td><td>'.$status.'</td>';
        echo '</tr>';
    }
    echo "</table><br>";

    $detailSql = "SELECT COALESCE(u.name,l.unit_name,'-') AS unit_name, COALESCE(e.full_name,l.user_name,'-') AS full_name, COALESCE(e.nik,l.username,'-') AS nik,
                         i.kode_bab, i.no_std, i.no_ep, i.elemen_penilaian, l.section_key, l.read_at
                  FROM pfp_read_logs l
                  INNER JOIN pfp_kisi_items i ON i.id=l.item_id
                  LEFT JOIN employees e ON " . pfp_log_join_condition('l','e') . "
                  LEFT JOIN units u ON u.id=COALESCE(e.unit_id,l.unit_id)
                  WHERE 1=1 " . ($unitId>0 ? " AND COALESCE(e.unit_id,l.unit_id)={$unitId}" : '') . "
                  ORDER BY unit_name, full_name, i.source_no, l.section_key";
    $dres = $conn->query($detailSql);
    echo "<h3>Detail Bagian yang Sudah Dibaca</h3><table border='1' cellpadding='5' cellspacing='0'>";
    echo "<tr style='background:#dcfce7;font-weight:bold'><th>No</th><th>Unit</th><th>NIK/User</th><th>Nama</th><th>Bab</th><th>Std</th><th>EP</th><th>Elemen Penilaian</th><th>Bagian</th><th>Waktu Baca</th></tr>";
    $no=1;
    if ($dres instanceof mysqli_result) while ($r=$dres->fetch_assoc()) {
        echo '<tr><td>'.$no++.'</td><td>'.e($r['unit_name']).'</td><td>'.e($r['nik']).'</td><td>'.e($r['full_name']).'</td><td>'.e($r['kode_bab']).'</td><td>'.e($r['no_std']).'</td><td>'.e($r['no_ep']).'</td><td>'.e($r['elemen_penilaian']).'</td><td>'.e($r['section_key']).'</td><td>'.e($r['read_at']).'</td></tr>';
    }
    echo '</table></body></html>';
    exit;
}

$tab = (string)($_GET['tab'] ?? 'dashboard');
$itemId = (int)($_GET['item_id'] ?? 0);
$kode = strtoupper(trim((string)($_GET['kode'] ?? '')));
$q = trim((string)($_GET['q'] ?? ''));
$unitFilter = (int)($_GET['unit_id'] ?? 0);
$current = pfp_current_user_payload();
$assessmentReport = pfp_assessment_report_data();
$rtlPokjaFilter = strtoupper(trim((string)($_GET['rtl_pokja'] ?? '')));
$rtlStatusFilter = trim((string)($_GET['rtl_status'] ?? ''));
$assessmentFollowups = pfp_get_assessment_followups($conn, $rtlPokjaFilter, $rtlStatusFilter);
$rtlTotal = count($assessmentFollowups);
$rtlDone = 0; foreach ($assessmentFollowups as $rf) { if (in_array((string)$rf['status'], ['Selesai','Terverifikasi'], true)) $rtlDone++; }
$rtlPct = $rtlTotal > 0 ? round(($rtlDone / $rtlTotal) * 100, 1) : 0;

$totalItems = pfp_scalar($conn, "SELECT COUNT(*) FROM pfp_kisi_items WHERE is_active=1");
$totalLogs = pfp_scalar($conn, "SELECT COUNT(*) FROM pfp_read_logs");
$totalReaders = pfp_scalar($conn, "SELECT COUNT(DISTINCT COALESCE(NULLIF(employee_id,0), user_id)) FROM pfp_read_logs");
$totalActiveStaff = max(1, pfp_scalar($conn, "SELECT COUNT(*) FROM employees WHERE employment_status='aktif'"));
$overallPct = min(100, round(($totalLogs / max(1, $totalItems * 5 * $totalActiveStaff)) * 100, 1));

$babRows = [];
$resBab = $conn->query("SELECT kode_bab, MIN(bab) AS bab, COUNT(*) AS total FROM pfp_kisi_items WHERE is_active=1 GROUP BY kode_bab ORDER BY FIELD(kode_bab,'AKP','HPK','PP','PAP','PAB','PKPO','KE'), kode_bab");
if ($resBab instanceof mysqli_result) while($r=$resBab->fetch_assoc()) $babRows[]=$r;

$units = [];
$resUnit = $conn->query("SELECT id,name FROM units WHERE is_active=1 ORDER BY name");
if ($resUnit instanceof mysqli_result) while($r=$resUnit->fetch_assoc()) $units[]=$r;
?>
<div class="max-w-7xl mx-auto p-4 md:p-6 space-y-6">
    <div class="relative overflow-hidden rounded-3xl bg-gradient-to-br from-blue-700 via-indigo-700 to-violet-700 p-6 md:p-8 text-white shadow-2xl">
        <div class="absolute -right-12 -top-12 h-48 w-48 rounded-full bg-white/10"></div>
        <div class="absolute -bottom-16 left-1/2 h-56 w-56 rounded-full bg-cyan-300/10"></div>
        <div class="relative z-10 flex flex-col lg:flex-row lg:items-center lg:justify-between gap-5">
            <div>
                <p class="text-sm font-semibold uppercase tracking-[0.25em] text-blue-100">Pokja Pelayanan Fokus Pasien</p>
                <h1 class="mt-2 text-2xl md:text-4xl font-extrabold leading-tight">Kisi-Kisi Telusur Akreditasi PFP</h1>
                <p class="mt-2 max-w-3xl text-blue-50">Bank pertanyaan surveior, role play, ekspektasi jawaban, bukti wajib, red flags, serta dashboard sosialisasi berbasis tracking baca user.</p>
            </div>
            <div class="grid grid-cols-3 gap-3 text-center">
                <div class="rounded-2xl bg-white/15 px-4 py-3 backdrop-blur"><div class="text-2xl font-black"><?= (int)$totalItems ?></div><div class="text-xs text-blue-100">Total EP</div></div>
                <div class="rounded-2xl bg-white/15 px-4 py-3 backdrop-blur"><div class="text-2xl font-black"><?= (int)$totalReaders ?></div><div class="text-xs text-blue-100">User Baca</div></div>
                <div class="rounded-2xl bg-white/15 px-4 py-3 backdrop-blur"><div class="text-2xl font-black"><?= e($overallPct) ?>%</div><div class="text-xs text-blue-100">Sosialisasi</div></div>
            </div>
        </div>
    </div>

    <div class="flex flex-wrap gap-2">
        <a href="?module=kisi_pfp&tab=dashboard" class="px-4 py-2 rounded-full text-sm font-bold <?= $tab==='dashboard'?'bg-blue-600 text-white shadow-lg':'bg-white text-slate-700 border border-slate-200' ?>"><i class="fas fa-chart-pie mr-2"></i>Dashboard</a>
        <a href="?module=kisi_pfp&tab=kisi" class="px-4 py-2 rounded-full text-sm font-bold <?= $tab==='kisi'?'bg-blue-600 text-white shadow-lg':'bg-white text-slate-700 border border-slate-200' ?>"><i class="fas fa-list-check mr-2"></i>Kisi-Kisi EP</a>
        <a href="?module=kisi_pfp&tab=sosialisasi" class="px-4 py-2 rounded-full text-sm font-bold <?= $tab==='sosialisasi'?'bg-blue-600 text-white shadow-lg':'bg-white text-slate-700 border border-slate-200' ?>"><i class="fas fa-users-viewfinder mr-2"></i>Sosialisasi Unit</a>
        <a href="?module=kisi_pfp&tab=laporan_asesmen" class="px-4 py-2 rounded-full text-sm font-bold <?= $tab==='laporan_asesmen'?'bg-blue-600 text-white shadow-lg':'bg-white text-slate-700 border border-slate-200' ?>"><i class="fas fa-file-shield mr-2"></i>Laporan Hasil Asesmen</a>
    </div>

<?php if ($tab === 'dashboard'): ?>
    <?php
    $unitStats = [];
    $logJoinEmployee = pfp_log_join_condition('l', 'e');
    $sqlUnit = "SELECT u.id,u.name, COUNT(DISTINCT e.id) AS total_staff,
                       COUNT(DISTINCT CASE WHEN l.id IS NOT NULL THEN e.id END) AS readers,
                       COUNT(DISTINCT CONCAT(l.item_id,':',l.section_key,':',e.id)) AS read_sections,
                       MAX(l.read_at) AS last_read
                FROM units u
                LEFT JOIN employees e ON e.unit_id=u.id AND e.employment_status='aktif'
                LEFT JOIN pfp_read_logs l ON {$logJoinEmployee}
                WHERE u.is_active=1
                GROUP BY u.id,u.name
                ORDER BY (read_sections) DESC, u.name";
    $rs = $conn->query($sqlUnit);
    if ($rs instanceof mysqli_result) while($r=$rs->fetch_assoc()) $unitStats[]=$r;
    ?>
    <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <?php foreach ($babRows as $b): ?>
            <a href="?module=kisi_pfp&tab=kisi&kode=<?= e($b['kode_bab']) ?>" class="rounded-2xl bg-white p-5 shadow border border-slate-100 hover:-translate-y-1 transition">
                <div class="flex items-center justify-between"><div class="text-sm text-slate-500 font-semibold"><?= e($b['bab']) ?></div><i class="fas fa-arrow-up-right-from-square text-blue-500"></i></div>
                <div class="mt-3 text-3xl font-black text-slate-800"><?= (int)$b['total'] ?></div>
                <div class="mt-1 text-sm font-bold text-blue-600"><?= e($b['kode_bab']) ?> Elemen Penilaian</div>
            </a>
        <?php endforeach; ?>
    </div>

    <div class="rounded-3xl bg-white shadow-xl border border-slate-100 overflow-hidden">
        <div class="p-5 border-b bg-slate-50 flex items-center justify-between gap-3 flex-wrap">
            <div><h2 class="text-xl font-extrabold text-slate-800">Dashboard Keberhasilan Sosialisasi per Unit</h2><p class="text-sm text-slate-500">Persentase dihitung dari bagian kisi-kisi yang sudah dibaca oleh staf aktif unit.</p></div>
            <a href="?module=kisi_pfp&action=export_unit" class="px-4 py-2 rounded-xl bg-emerald-600 text-white font-bold shadow hover:bg-emerald-700"><i class="fas fa-file-excel mr-2"></i>Export Semua Unit</a>
        </div>
        <div class="overflow-x-auto">
            <table class="min-w-full text-sm">
                <thead class="bg-slate-100 text-slate-600 uppercase text-xs"><tr><th class="px-4 py-3 text-left">Unit</th><th class="px-4 py-3">Staf Aktif</th><th class="px-4 py-3">Sudah Baca</th><th class="px-4 py-3">Progress</th><th class="px-4 py-3">Terakhir</th><th class="px-4 py-3">Export</th></tr></thead>
                <tbody class="divide-y divide-slate-100">
                <?php foreach ($unitStats as $urow):
                    $den = max(1, (int)$urow['total_staff'] * max(1,$totalItems) * 5);
                    $pct = min(100, round(((int)$urow['read_sections'] / $den) * 100, 1));
                ?>
                    <tr class="hover:bg-blue-50/40"><td class="px-4 py-3 font-bold text-slate-800"><?= e($urow['name']) ?></td><td class="px-4 py-3 text-center"><?= (int)$urow['total_staff'] ?></td><td class="px-4 py-3 text-center"><?= (int)$urow['readers'] ?></td><td class="px-4 py-3 min-w-[220px]"><div class="flex items-center gap-3"><div class="h-3 flex-1 rounded-full bg-slate-100 overflow-hidden"><div class="h-full bg-gradient-to-r from-blue-500 to-emerald-500" style="width:<?= e($pct) ?>%"></div></div><b><?= e($pct) ?>%</b></div></td><td class="px-4 py-3 text-slate-500"><?= e($urow['last_read'] ?: '-') ?></td><td class="px-4 py-3 text-center"><a class="text-emerald-700 font-bold" href="?module=kisi_pfp&action=export_unit&unit_id=<?= (int)$urow['id'] ?>"><i class="fas fa-download mr-1"></i>Excel</a></td></tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

<?php elseif ($tab === 'laporan_asesmen'): ?>
    <style>
        @media print {
            body * { visibility: hidden; }
            #pfpAssessmentPrint, #pfpAssessmentPrint * { visibility: visible; }
            #pfpAssessmentPrint { position: absolute; left: 0; top: 0; width: 100%; padding: 18px; background: #fff; }
            .no-print { display: none !important; }
            .print-break { page-break-before: always; }
            table { page-break-inside: auto; }
            tr { page-break-inside: avoid; page-break-after: auto; }
        }
    </style>
    <div class="rounded-3xl bg-white p-5 shadow-xl border border-slate-100 no-print">
        <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
            <div>
                <h2 class="text-xl font-extrabold text-slate-800">Laporan Hasil Asesmen Internal</h2>
                <p class="text-sm text-slate-500">Berisi analisis capaian 60–75%, EP prioritas belum tercapai, akar masalah, dan RTL Juni 2026.</p>
            </div>
            <div class="flex flex-wrap gap-2">
                <button type="button" onclick="window.print()" class="px-4 py-2 rounded-xl bg-slate-800 text-white font-bold"><i class="fas fa-print mr-2"></i>Cetak</button>
                <a href="?module=kisi_pfp&action=export_assessment_report" class="px-4 py-2 rounded-xl bg-emerald-600 text-white font-bold"><i class="fas fa-file-excel mr-2"></i>Export Excel</a>
            </div>
        </div>
    </div>

    <div class="rounded-3xl bg-white p-5 shadow-xl border border-slate-100 no-print space-y-4">
        <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
            <div>
                <h2 class="text-xl font-extrabold text-slate-800"><i class="fas fa-clipboard-check text-emerald-600 mr-2"></i>Monitoring Tindak Lanjut & Bukti Evaluasi</h2>
                <p class="text-sm text-slate-500">Di bagian ini Bapak/Ibu bisa mengisi bukti sosialisasi, realisasi kegiatan, link dokumen/foto, status tindak lanjut, dan catatan evaluator. Data ini yang membuat laporan bisa dievaluasi.</p>
            </div>
            <div class="rounded-2xl bg-emerald-50 border border-emerald-100 px-4 py-3 text-emerald-800 font-bold">
                Progress RTL: <?= e($rtlPct) ?>% <span class="text-xs font-semibold">(<?= (int)$rtlDone ?>/<?= (int)$rtlTotal ?> selesai)</span>
            </div>
        </div>
        <?php if (isset($_GET['rtl_saved'])): ?>
            <div class="rounded-2xl border border-emerald-200 bg-emerald-50 p-3 text-emerald-700 font-bold text-sm"><i class="fas fa-check-circle mr-2"></i>Data evaluasi tindak lanjut berhasil disimpan.</div>
        <?php endif; ?>
        <form method="get" class="flex flex-wrap gap-3 items-end">
            <input type="hidden" name="module" value="kisi_pfp">
            <input type="hidden" name="tab" value="laporan_asesmen">
            <div>
                <label class="text-xs font-bold text-slate-500 uppercase">Filter Pokja</label>
                <select name="rtl_pokja" class="mt-1 rounded-xl border-slate-200 min-w-[180px]">
                    <option value="">Semua Pokja</option>
                    <?php foreach (array_keys($assessmentReport['pokja']) as $pk): ?><option value="<?= e($pk) ?>" <?= $rtlPokjaFilter===$pk?'selected':'' ?>><?= e($pk) ?></option><?php endforeach; ?>
                </select>
            </div>
            <div>
                <label class="text-xs font-bold text-slate-500 uppercase">Filter Status</label>
                <select name="rtl_status" class="mt-1 rounded-xl border-slate-200 min-w-[180px]">
                    <option value="">Semua Status</option>
                    <?php foreach (['Belum','Proses','Selesai','Terverifikasi'] as $st): ?><option value="<?= e($st) ?>" <?= $rtlStatusFilter===$st?'selected':'' ?>><?= e($st) ?></option><?php endforeach; ?>
                </select>
            </div>
            <button class="rounded-xl bg-blue-600 text-white px-5 py-2.5 font-bold"><i class="fas fa-filter mr-2"></i>Filter</button>
            <a class="rounded-xl bg-emerald-600 text-white px-5 py-2.5 font-bold" href="?module=kisi_pfp&action=export_assessment_followup&rtl_pokja=<?= urlencode($rtlPokjaFilter) ?>&rtl_status=<?= urlencode($rtlStatusFilter) ?>"><i class="fas fa-file-excel mr-2"></i>Export Monitoring RTL</a>
        </form>
        <div class="overflow-x-auto rounded-2xl border border-slate-200">
            <table class="min-w-full text-sm">
                <thead class="bg-slate-100 text-xs uppercase text-slate-600">
                    <tr><th class="px-3 py-3 text-left">Pokja</th><th class="px-3 py-3 text-left min-w-[260px]">Rencana Tindak Lanjut</th><th class="px-3 py-3 text-left">PIC/Target</th><th class="px-3 py-3 text-left min-w-[360px]">Isi Realisasi & Bukti</th><th class="px-3 py-3">Status</th><th class="px-3 py-3">Simpan</th></tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                <?php foreach ($assessmentFollowups as $fr): ?>
                    <tr class="align-top hover:bg-blue-50/30">
                        <td class="px-3 py-3"><div class="font-black text-blue-700"><?= e($fr['pokja']) ?></div><div class="text-xs text-slate-500"><?= e($fr['ep_code'] ?: 'Area pokja') ?></div><span class="mt-2 inline-flex px-2 py-1 rounded-full text-xs font-bold <?= e(pfp_status_badge_class((string)$fr['status'])) ?>"><?= e($fr['status']) ?></span></td>
                        <td class="px-3 py-3"><div class="font-bold text-slate-800"><?= e($fr['follow_up_plan']) ?></div><details class="mt-2 text-xs text-slate-600"><summary class="cursor-pointer font-bold text-amber-700">Lihat temuan & akar masalah</summary><div class="mt-2 whitespace-pre-line"><?= e($fr['finding']) ?></div><div class="mt-2 whitespace-pre-line"><b>Akar masalah:</b><br><?= e($fr['root_cause']) ?></div></details></td>
                        <td class="px-3 py-3"><div class="font-semibold text-slate-800"><?= e($fr['pic']) ?></div><div class="text-xs text-emerald-700 font-bold mt-1"><?= e($fr['target_period']) ?></div><div class="text-xs text-slate-400 mt-2">Update: <?= e($fr['updated_at']) ?></div></td>
                        <td class="px-3 py-3">
                            <form method="post" action="?module=kisi_pfp&action=save_assessment_followup">
                                <input type="hidden" name="id" value="<?= (int)$fr['id'] ?>">
                                <input type="hidden" name="rtl_pokja" value="<?= e($rtlPokjaFilter) ?>">
                                <input type="hidden" name="rtl_status" value="<?= e($rtlStatusFilter) ?>">
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-2">
                                    <div><label class="text-[11px] font-bold text-slate-500 uppercase">Tanggal Realisasi</label><input type="date" name="realization_date" value="<?= e($fr['realization_date']) ?>" class="mt-1 w-full rounded-xl border-slate-200 text-sm"></div>
                                    <div><label class="text-[11px] font-bold text-slate-500 uppercase">Status</label><select name="status" class="mt-1 w-full rounded-xl border-slate-200 text-sm"><?php foreach(['Belum','Proses','Selesai','Terverifikasi'] as $st): ?><option value="<?= e($st) ?>" <?= $fr['status']===$st?'selected':'' ?>><?= e($st) ?></option><?php endforeach; ?></select></div>
                                </div>
                                <label class="text-[11px] font-bold text-slate-500 uppercase mt-2 block">Catatan Realisasi</label><textarea name="realization_note" rows="2" class="mt-1 w-full rounded-xl border-slate-200 text-sm" placeholder="Contoh: Sosialisasi sudah dilakukan tanggal..., peserta..., hasil audit..."><?= e($fr['realization_note']) ?></textarea>
                                <label class="text-[11px] font-bold text-slate-500 uppercase mt-2 block">Bukti Sosialisasi / Implementasi</label><textarea name="evidence_desc" rows="2" class="mt-1 w-full rounded-xl border-slate-200 text-sm" placeholder="Contoh: daftar hadir, foto kegiatan, notulen, hasil audit RM, screenshot dashboard baca..."><?= e($fr['evidence_desc']) ?></textarea>
                                <label class="text-[11px] font-bold text-slate-500 uppercase mt-2 block">Link Bukti Google Drive / Dokumen</label><input type="url" name="evidence_link" value="<?= e($fr['evidence_link']) ?>" class="mt-1 w-full rounded-xl border-slate-200 text-sm" placeholder="https://drive.google.com/..."></input>
                                <label class="text-[11px] font-bold text-slate-500 uppercase mt-2 block">Catatan Evaluator</label><textarea name="evaluator_note" rows="2" class="mt-1 w-full rounded-xl border-slate-200 text-sm" placeholder="Contoh: bukti sudah sesuai / perlu dilengkapi..."><?= e($fr['evaluator_note']) ?></textarea>
                        </td>
                        <td class="px-3 py-3 text-center"><span class="px-2 py-1 rounded-full text-xs font-bold <?= e(pfp_status_badge_class((string)$fr['status'])) ?>"><?= e($fr['status']) ?></span></td>
                        <td class="px-3 py-3 text-center"><button class="rounded-xl bg-blue-600 text-white px-3 py-2 font-bold text-xs"><i class="fas fa-save mr-1"></i>Simpan</button></form></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div id="pfpAssessmentPrint" class="space-y-6">
        <div class="rounded-3xl bg-gradient-to-br from-slate-900 via-blue-900 to-indigo-900 p-6 md:p-8 text-white shadow-xl">
            <p class="text-sm font-semibold uppercase tracking-[0.25em] text-blue-100">Asesmen Internal Akreditasi</p>
            <h1 class="mt-2 text-2xl md:text-4xl font-black leading-tight"><?= e($assessmentReport['title']) ?></h1>
            <p class="mt-3 max-w-5xl text-blue-50"><b><?= e($assessmentReport['hospital']) ?></b> • Periode tindak lanjut: <b><?= e($assessmentReport['period']) ?></b></p>
            <p class="mt-4 max-w-5xl text-blue-50 leading-relaxed"><?= e($assessmentReport['summary']) ?></p>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div class="rounded-2xl bg-white p-5 shadow border border-slate-100"><div class="text-xs uppercase font-bold text-slate-500">Total EP DB</div><div class="text-3xl font-black text-blue-700"><?= (int)$totalItems ?></div><div class="text-sm text-slate-500">Kisi-kisi PFP aktif</div></div>
            <div class="rounded-2xl bg-white p-5 shadow border border-slate-100"><div class="text-xs uppercase font-bold text-slate-500">Jumlah Pokja</div><div class="text-3xl font-black text-indigo-700"><?= count($assessmentReport['pokja']) ?></div><div class="text-sm text-slate-500">AKP, HPK, PP, PAP, PAB, PKPO, KE</div></div>
            <div class="rounded-2xl bg-white p-5 shadow border border-slate-100"><div class="text-xs uppercase font-bold text-slate-500">Capaian Telusur</div><div class="text-3xl font-black text-amber-600">60–75%</div><div class="text-sm text-slate-500">Staf mampu membuktikan EP</div></div>
            <div class="rounded-2xl bg-white p-5 shadow border border-slate-100"><div class="text-xs uppercase font-bold text-slate-500">Target Juni</div><div class="text-3xl font-black text-emerald-600">≥85%</div><div class="text-sm text-slate-500">Setelah RTL dan re-asesmen</div></div>
        </div>

        <div class="rounded-3xl bg-white shadow-xl border border-slate-100 overflow-hidden">
            <div class="p-5 border-b bg-slate-50"><h2 class="font-extrabold text-slate-800">Dasar dan Ruang Lingkup Asesmen</h2></div>
            <div class="p-5 text-sm leading-relaxed text-slate-700">
                <p><b>Dasar data:</b> <?= e($assessmentReport['basis']) ?></p>
                <p class="mt-2">Metode asesmen meliputi telaah regulasi dan dokumen, telaah rekam medis, wawancara staf, observasi lapangan, serta simulasi pembuktian EP oleh staf sasaran.</p>
            </div>
        </div>

        <div class="rounded-3xl bg-white shadow-xl border border-slate-100 overflow-hidden">
            <div class="p-5 border-b bg-slate-50"><h2 class="font-extrabold text-slate-800">Ringkasan Capaian per Pokja</h2></div>
            <div class="overflow-x-auto"><table class="min-w-full text-sm"><thead class="bg-slate-100 text-xs uppercase text-slate-600"><tr><th class="px-4 py-3 text-left">Pokja</th><th class="px-4 py-3">Jumlah EP</th><th class="px-4 py-3">Capaian</th><th class="px-4 py-3">Status</th><th class="px-4 py-3 text-left">Gambaran Umum</th></tr></thead><tbody class="divide-y divide-slate-100">
                <?php foreach ($assessmentReport['pokja'] as $kode => $p): ?>
                    <tr><td class="px-4 py-3 font-extrabold text-blue-700"><?= e($kode) ?><div class="text-xs text-slate-500 font-semibold"><?= e($p['name']) ?></div></td><td class="px-4 py-3 text-center font-bold"><?= (int)$p['total_ep'] ?></td><td class="px-4 py-3 text-center font-bold text-amber-700"><?= e($p['achievement']) ?></td><td class="px-4 py-3 text-center"><span class="px-2 py-1 rounded-full bg-amber-100 text-amber-700 text-xs font-bold"><?= e($p['status']) ?></span></td><td class="px-4 py-3 text-slate-700"><?= e($p['general']) ?></td></tr>
                <?php endforeach; ?>
            </tbody></table></div>
        </div>

        <?php $idx=0; foreach ($assessmentReport['pokja'] as $kode => $p): $idx++; ?>
            <div class="rounded-3xl bg-white shadow-xl border border-slate-100 overflow-hidden <?= $idx>1 ? 'print-break' : '' ?>">
                <div class="p-5 bg-gradient-to-r from-blue-700 to-indigo-700 text-white">
                    <div class="text-sm text-blue-100 font-bold"><?= e($kode) ?> • <?= (int)$p['total_ep'] ?> EP • Capaian <?= e($p['achievement']) ?></div>
                    <h2 class="text-2xl font-black mt-1"><?= e($p['name']) ?></h2>
                    <p class="mt-2 text-blue-50 leading-relaxed"><?= e($p['general']) ?></p>
                </div>
                <div class="p-5 space-y-5">
                    <div>
                        <h3 class="font-extrabold text-slate-800 mb-3"><i class="fas fa-triangle-exclamation text-red-500 mr-2"></i>EP Prioritas Belum Tercapai Optimal</h3>
                        <div class="overflow-x-auto"><table class="min-w-full text-sm border border-slate-200"><thead class="bg-red-50 text-red-700"><tr><th class="px-3 py-2 text-left">No EP</th><th class="px-3 py-2 text-left">Elemen Penilaian</th><th class="px-3 py-2 text-left">Masalah Utama</th></tr></thead><tbody class="divide-y divide-slate-100">
                            <?php foreach ($p['priority_ep'] as $ep): ?>
                                <tr><td class="px-3 py-2 font-bold text-red-700 whitespace-nowrap"><?= e($ep[0]) ?></td><td class="px-3 py-2"><?= e($ep[1]) ?></td><td class="px-3 py-2"><?= e($ep[2]) ?></td></tr>
                            <?php endforeach; ?>
                        </tbody></table></div>
                    </div>
                    <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
                        <div class="rounded-2xl border border-amber-200 bg-amber-50 p-4">
                            <h3 class="font-extrabold text-amber-800 mb-2"><i class="fas fa-magnifying-glass-chart mr-2"></i>Akar Masalah</h3>
                            <ul class="list-disc pl-5 text-sm text-amber-900 space-y-1"><?php foreach ($p['root_causes'] as $rc): ?><li><?= e($rc) ?></li><?php endforeach; ?></ul>
                        </div>
                        <div class="rounded-2xl border border-emerald-200 bg-emerald-50 p-4">
                            <h3 class="font-extrabold text-emerald-800 mb-2"><i class="fas fa-bullseye mr-2"></i>Output yang Diharapkan</h3>
                            <ul class="list-disc pl-5 text-sm text-emerald-900 space-y-1"><li>Staf mampu menunjukkan bukti EP saat telusur.</li><li>Dokumentasi rekam medis lebih lengkap dan konsisten.</li><li>Folder bukti pokja/unit siap ditunjukkan.</li><li>RTL memiliki PIC, target, dan evaluasi ulang.</li></ul>
                        </div>
                    </div>
                    <div>
                        <h3 class="font-extrabold text-slate-800 mb-3"><i class="fas fa-calendar-check text-emerald-600 mr-2"></i>Rencana Tindak Lanjut Juni 2026</h3>
                        <div class="overflow-x-auto"><table class="min-w-full text-sm border border-slate-200"><thead class="bg-emerald-50 text-emerald-700"><tr><th class="px-3 py-2 text-left">Tindak Lanjut</th><th class="px-3 py-2 text-left">PIC</th><th class="px-3 py-2 text-left">Target</th></tr></thead><tbody class="divide-y divide-slate-100">
                            <?php foreach ($p['rtl'] as $rtl): ?>
                                <tr><td class="px-3 py-2"><?= e($rtl[0]) ?></td><td class="px-3 py-2 font-semibold"><?= e($rtl[1]) ?></td><td class="px-3 py-2 font-bold text-emerald-700"><?= e($rtl[2]) ?></td></tr>
                            <?php endforeach; ?>
                        </tbody></table></div>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>

        <div class="rounded-3xl bg-white shadow-xl border border-slate-100 overflow-hidden print-break">
            <div class="p-5 border-b bg-slate-50"><h2 class="font-extrabold text-slate-800">Temuan Sistemik Lintas Pokja</h2></div>
            <div class="p-5"><ul class="grid grid-cols-1 md:grid-cols-2 gap-3 text-sm text-slate-700"><?php foreach ($assessmentReport['system_findings'] as $f): ?><li class="rounded-2xl bg-slate-50 border border-slate-100 p-4"><i class="fas fa-circle-exclamation text-amber-500 mr-2"></i><?= e($f) ?></li><?php endforeach; ?></ul></div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-5">
            <div class="rounded-3xl bg-white shadow-xl border border-slate-100 overflow-hidden">
                <div class="p-5 border-b bg-slate-50"><h2 class="font-extrabold text-slate-800">Rencana Mingguan Juni 2026</h2></div>
                <div class="overflow-x-auto"><table class="min-w-full text-sm"><thead class="bg-slate-100 text-xs uppercase text-slate-600"><tr><th class="px-4 py-3 text-left">Minggu</th><th class="px-4 py-3 text-left">Fokus</th></tr></thead><tbody class="divide-y divide-slate-100"><?php foreach ($assessmentReport['weekly_plan'] as $w): ?><tr><td class="px-4 py-3 font-bold text-blue-700 whitespace-nowrap"><?= e($w[0]) ?></td><td class="px-4 py-3"><?= e($w[1]) ?></td></tr><?php endforeach; ?></tbody></table></div>
            </div>
            <div class="rounded-3xl bg-white shadow-xl border border-slate-100 overflow-hidden">
                <div class="p-5 border-b bg-slate-50"><h2 class="font-extrabold text-slate-800">Target Akhir Juni 2026</h2></div>
                <div class="overflow-x-auto"><table class="min-w-full text-sm"><thead class="bg-slate-100 text-xs uppercase text-slate-600"><tr><th class="px-4 py-3 text-left">Parameter</th><th class="px-4 py-3">Saat Ini</th><th class="px-4 py-3">Target</th></tr></thead><tbody class="divide-y divide-slate-100"><?php foreach ($assessmentReport['targets'] as $t): ?><tr><td class="px-4 py-3 font-semibold"><?= e($t[0]) ?></td><td class="px-4 py-3 text-center text-amber-700 font-bold"><?= e($t[1]) ?></td><td class="px-4 py-3 text-center text-emerald-700 font-bold"><?= e($t[2]) ?></td></tr><?php endforeach; ?></tbody></table></div>
            </div>
        </div>

        <div class="rounded-3xl bg-white shadow-xl border border-slate-100 overflow-hidden print-break">
            <div class="p-5 border-b bg-slate-50"><h2 class="font-extrabold text-slate-800">Monitoring Tindak Lanjut dan Bukti Evaluasi</h2><p class="text-sm text-slate-500">Rekap dari isian realisasi, bukti sosialisasi/implementasi, dan catatan evaluator.</p></div>
            <div class="overflow-x-auto"><table class="min-w-full text-sm"><thead class="bg-slate-100 text-xs uppercase text-slate-600"><tr><th class="px-3 py-2 text-left">Pokja</th><th class="px-3 py-2 text-left">RTL</th><th class="px-3 py-2 text-left">PIC/Target</th><th class="px-3 py-2 text-left">Status & Realisasi</th><th class="px-3 py-2 text-left">Bukti</th></tr></thead><tbody class="divide-y divide-slate-100">
                <?php foreach ($assessmentFollowups as $fr): ?>
                    <tr><td class="px-3 py-2 font-bold text-blue-700"><?= e($fr['pokja']) ?></td><td class="px-3 py-2"><?= e($fr['follow_up_plan']) ?></td><td class="px-3 py-2"><?= e($fr['pic']) ?><br><b><?= e($fr['target_period']) ?></b></td><td class="px-3 py-2"><b><?= e($fr['status']) ?></b><br><?= e($fr['realization_date'] ?: '-') ?><br><?= nl2br(e($fr['realization_note'])) ?></td><td class="px-3 py-2"><?= nl2br(e($fr['evidence_desc'])) ?><br><?= e($fr['evidence_link']) ?><br><i><?= nl2br(e($fr['evaluator_note'])) ?></i></td></tr>
                <?php endforeach; ?>
            </tbody></table></div>
        </div>

        <div class="rounded-3xl bg-white shadow-xl border border-slate-100 p-5">
            <h2 class="font-extrabold text-slate-800">Kesimpulan</h2>
            <p class="mt-2 text-sm leading-relaxed text-slate-700">Implementasi standar akreditasi area Pelayanan Fokus Pasien di RS BaliMéd Denpasar telah berjalan, namun belum seluruh EP dapat dibuktikan secara konsisten oleh staf. Capaian 60–75% menunjukkan kondisi tercapai parsial. Fokus Juni 2026 diarahkan pada akselerasi pembuktian EP prioritas, penguatan dokumentasi rekam medis, penyediaan folder bukti, coaching roleplay staf, audit mingguan, dan re-asesmen akhir bulan.</p>
            <div class="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6 text-sm">
                <div><b>Disusun oleh:</b><br>Tim Asesor Internal Akreditasi<br>RS BaliMéd Denpasar</div>
                <div class="md:text-right"><b>Denpasar, Juni 2026</b><br>Dokumen tindak lanjut asesmen internal</div>
            </div>
        </div>
    </div>

<?php elseif ($tab === 'kisi'): ?>
    <?php
    $where = "WHERE is_active=1";
    if ($kode !== '') $where .= " AND kode_bab='".$conn->real_escape_string($kode)."'";
    if ($q !== '') {
        $like = "%".$conn->real_escape_string($q)."%";
        $where .= " AND (elemen_penilaian LIKE '{$like}' OR pertanyaan_utama LIKE '{$like}' OR roleplay LIKE '{$like}' OR bukti_wajib LIKE '{$like}')";
    }
    $items=[];
    $rs=$conn->query("SELECT * FROM pfp_kisi_items {$where} ORDER BY source_no ASC LIMIT 400");
    if ($rs instanceof mysqli_result) while($r=$rs->fetch_assoc()) $items[]=$r;
    ?>
    <div class="rounded-3xl bg-white p-5 shadow border border-slate-100">
        <form method="get" class="grid grid-cols-1 md:grid-cols-4 gap-3 items-end">
            <input type="hidden" name="module" value="kisi_pfp"><input type="hidden" name="tab" value="kisi">
            <div><label class="text-xs font-bold text-slate-500 uppercase">Bab</label><select name="kode" class="mt-1 w-full rounded-xl border-slate-200"><option value="">Semua PFP</option><?php foreach($babRows as $b): ?><option value="<?= e($b['kode_bab']) ?>" <?= $kode===$b['kode_bab']?'selected':'' ?>><?= e($b['kode_bab'].' - '.$b['bab']) ?></option><?php endforeach; ?></select></div>
            <div class="md:col-span-2"><label class="text-xs font-bold text-slate-500 uppercase">Cari EP / Roleplay / Bukti</label><input name="q" value="<?= e($q) ?>" placeholder="contoh: CPPT, edukasi, transfer, high alert..." class="mt-1 w-full rounded-xl border-slate-200"></div>
            <button class="rounded-xl bg-blue-600 text-white px-5 py-2.5 font-bold shadow"><i class="fas fa-search mr-2"></i>Tampilkan</button>
        </form>
    </div>

    <?php if ($itemId > 0):
        $stmt=$conn->prepare("SELECT * FROM pfp_kisi_items WHERE id=? LIMIT 1"); $stmt->bind_param('i',$itemId); $stmt->execute(); $detail=$stmt->get_result()->fetch_assoc(); $stmt->close();
        $readMap=[]; $currentResolved = pfp_resolve_current_employee($conn, $current); $rid=(int)$currentResolved['employee_id']; $uname=$conn->real_escape_string((string)$currentResolved['username']);
        $rr=$conn->query("SELECT section_key, read_at FROM pfp_read_logs WHERE item_id={$itemId} AND (employee_id={$rid} OR username='{$uname}')");
        if ($rr instanceof mysqli_result) while($r=$rr->fetch_assoc()) $readMap[$r['section_key']]=$r['read_at'];
        if ($detail): ?>
        <div class="rounded-3xl bg-white shadow-xl border border-slate-100 overflow-hidden">
            <div class="p-5 bg-gradient-to-r from-slate-900 to-blue-900 text-white"><div class="text-sm text-blue-100 font-bold">No <?= (int)$detail['source_no'] ?> • <?= e($detail['kode_bab']) ?> <?= e($detail['no_std']) ?> EP <?= e($detail['no_ep']) ?> • <?= e($detail['metode_telusur']) ?></div><h2 class="mt-2 text-2xl font-extrabold"><?= e($detail['elemen_penilaian']) ?></h2></div>
            <div class="p-5 grid grid-cols-1 lg:grid-cols-5 gap-4">
                <?php
                $blocks = [
                    'overview'=>['Ringkasan EP','fa-circle-info', '<b>Petugas/Unit Sasaran:</b><br>'.pfp_format_text($detail['petugas_sasaran']).'<br><br><b>Lokasi Telusur:</b><br>'.pfp_format_text($detail['lokasi_telusur']).'<br><br><b>Ekspektasi Jawaban Minimal:</b><br>'.pfp_format_text($detail['ekspektasi_jawaban'])],
                    'pertanyaan'=>['Pertanyaan Surveior','fa-comments', '<b>Pertanyaan Utama:</b><br>'.pfp_format_text($detail['pertanyaan_utama']).'<br><br><b>Probing:</b><br>'.pfp_format_text($detail['probing'])],
                    'roleplay'=>['Role Play Detail','fa-masks-theater', pfp_format_text($detail['roleplay'])],
                    'bukti'=>['Bukti Wajib & Red Flags','fa-folder-open', '<b>Kelengkapan Bukti:</b><br>'.pfp_format_text($detail['kelengkapan_bukti']).'<br><br><b>Bukti Wajib Ditunjukkan:</b><br>'.pfp_format_text($detail['bukti_wajib']).'<br><br><b>Red Flags:</b><br>'.pfp_format_text($detail['red_flags'])],
                    'checklist'=>['Checklist & Dasar','fa-square-check', '<b>Checklist Simulasi:</b><br>'.pfp_format_text($detail['checklist']).'<br><br><b>Keterangan / Dasar:</b><br>'.pfp_format_text($detail['dasar'])],
                ];
                foreach($blocks as $key=>$b): ?>
                    <div class="lg:col-span-5 rounded-2xl border border-slate-200 overflow-hidden">
                        <div class="bg-slate-50 px-4 py-3 flex items-center justify-between gap-3 flex-wrap"><h3 class="font-extrabold text-slate-800"><i class="fas <?= e($b[1]) ?> text-blue-600 mr-2"></i><?= e($b[0]) ?></h3><button onclick="markPfpRead(<?= (int)$detail['id'] ?>,'<?= e($key) ?>',this)" class="px-3 py-2 rounded-xl <?= isset($readMap[$key])?'bg-emerald-100 text-emerald-700':'bg-blue-600 text-white' ?> text-xs font-bold"><i class="fas fa-check mr-1"></i><?= isset($readMap[$key])?'Sudah dibaca':'Tandai dibaca' ?></button></div>
                        <div class="p-4 leading-relaxed text-slate-700 text-sm"><?= $b[2] ?></div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>
    <?php endif; ?>

    <div class="rounded-3xl bg-white shadow-xl border border-slate-100 overflow-hidden">
        <div class="p-5 border-b bg-slate-50"><h2 class="font-extrabold text-slate-800">Daftar Kisi-Kisi Telusur PFP</h2><p class="text-sm text-slate-500">Klik detail untuk membuka role play, pertanyaan, ekspektasi jawaban, bukti, dan checklist.</p></div>
        <div class="overflow-x-auto"><table class="min-w-full text-sm"><thead class="bg-slate-100 uppercase text-xs text-slate-600"><tr><th class="px-4 py-3 text-left">Bab</th><th class="px-4 py-3">Std/EP</th><th class="px-4 py-3 text-left">Elemen Penilaian</th><th class="px-4 py-3">Metode</th><th class="px-4 py-3">Aksi</th></tr></thead><tbody class="divide-y divide-slate-100">
        <?php foreach($items as $it): ?><tr class="hover:bg-blue-50/40"><td class="px-4 py-3"><b class="text-blue-700"><?= e($it['kode_bab']) ?></b><div class="text-xs text-slate-500"><?= e($it['bab']) ?></div></td><td class="px-4 py-3 text-center font-bold"><?= e($it['no_std']) ?> / <?= e($it['no_ep']) ?></td><td class="px-4 py-3 max-w-xl"><div class="font-semibold text-slate-800"><?= e($it['elemen_penilaian']) ?></div><div class="text-xs text-slate-500 mt-1 line-clamp-2"><?= e(substr((string)$it['pertanyaan_utama'],0,160)) ?>...</div></td><td class="px-4 py-3 text-center"><span class="px-2 py-1 rounded-full bg-indigo-50 text-indigo-700 font-bold text-xs"><?= e($it['kode_metode']) ?></span><div class="text-xs text-slate-500 mt-1"><?= e($it['metode_telusur']) ?></div></td><td class="px-4 py-3 text-center"><a class="inline-flex items-center px-3 py-2 rounded-xl bg-blue-600 text-white font-bold text-xs" href="?module=kisi_pfp&tab=kisi&kode=<?= e($kode) ?>&q=<?= urlencode($q) ?>&item_id=<?= (int)$it['id'] ?>"><i class="fas fa-eye mr-1"></i>Detail</a></td></tr><?php endforeach; ?>
        </tbody></table></div>
    </div>
<?php elseif ($tab === 'sosialisasi'): ?>
    <div class="rounded-3xl bg-white p-5 shadow border border-slate-100">
        <form method="get" class="flex flex-wrap gap-3 items-end"><input type="hidden" name="module" value="kisi_pfp"><input type="hidden" name="tab" value="sosialisasi"><div><label class="text-xs font-bold text-slate-500 uppercase">Pilih Unit</label><select name="unit_id" class="mt-1 min-w-[260px] rounded-xl border-slate-200"><option value="0">Semua Unit</option><?php foreach($units as $u): ?><option value="<?= (int)$u['id'] ?>" <?= $unitFilter===(int)$u['id']?'selected':'' ?>><?= e($u['name']) ?></option><?php endforeach; ?></select></div><button class="rounded-xl bg-blue-600 text-white px-5 py-2.5 font-bold">Filter</button><a class="rounded-xl bg-emerald-600 text-white px-5 py-2.5 font-bold" href="?module=kisi_pfp&action=export_unit&unit_id=<?= (int)$unitFilter ?>"><i class="fas fa-file-excel mr-2"></i>Export Unit</a></form>
    </div>
    <?php
    $unitWhere = $unitFilter>0 ? ' AND e.unit_id='.$unitFilter : '';
    $staff=[];
    $logJoinEmployee = pfp_log_join_condition('l', 'e');
    $rs=$conn->query("SELECT e.id,e.nik,e.full_name,u.name AS unit_name, COUNT(DISTINCT l.item_id) read_items, COUNT(DISTINCT CONCAT(l.item_id,':',l.section_key)) read_sections, MAX(l.read_at) last_read FROM employees e LEFT JOIN units u ON u.id=e.unit_id LEFT JOIN pfp_read_logs l ON {$logJoinEmployee} WHERE e.employment_status='aktif' {$unitWhere} GROUP BY e.id,e.nik,e.full_name,u.name ORDER BY u.name,e.full_name");
    if($rs instanceof mysqli_result) while($r=$rs->fetch_assoc()) $staff[]=$r;
    $den=max(1,$totalItems*5);
    $readDetails=[];
    $detailWhere = $unitFilter>0 ? ' AND COALESCE(e.unit_id,l.unit_id)='.$unitFilter : '';
    $detailSql = "SELECT COALESCE(u.name,l.unit_name,'-') AS unit_name, COALESCE(e.full_name,l.user_name,'-') AS full_name, COALESCE(e.nik,l.username,'-') AS nik,
                         i.kode_bab, i.no_std, i.no_ep, i.elemen_penilaian, l.section_key, l.read_at
                  FROM pfp_read_logs l
                  INNER JOIN pfp_kisi_items i ON i.id=l.item_id
                  LEFT JOIN employees e ON " . pfp_log_join_condition('l','e') . "
                  LEFT JOIN units u ON u.id=COALESCE(e.unit_id,l.unit_id)
                  WHERE 1=1 {$detailWhere}
                  ORDER BY l.read_at DESC, unit_name, full_name
                  LIMIT 1000";
    $drs=$conn->query($detailSql);
    if($drs instanceof mysqli_result) while($r=$drs->fetch_assoc()) $readDetails[]=$r;
    ?>
    <div class="rounded-3xl bg-white shadow-xl border border-slate-100 overflow-hidden"><div class="p-5 border-b bg-slate-50"><h2 class="font-extrabold text-slate-800">Rekap User yang Sudah Membaca</h2><p class="text-sm text-slate-500">Kepala unit dapat memakai export ini sebagai bahan evaluasi sosialisasi standar akreditasi PFP.</p></div><div class="overflow-x-auto"><table class="min-w-full text-sm"><thead class="bg-slate-100 uppercase text-xs text-slate-600"><tr><th class="px-4 py-3 text-left">Nama</th><th class="px-4 py-3">NIK</th><th class="px-4 py-3">Unit</th><th class="px-4 py-3">EP Dibaca</th><th class="px-4 py-3">Bagian Dibaca</th><th class="px-4 py-3">Progress</th><th class="px-4 py-3">Status</th></tr></thead><tbody class="divide-y divide-slate-100">
    <?php foreach($staff as $s): $pct=min(100,round(((int)$s['read_sections']/$den)*100,1)); ?><tr class="hover:bg-blue-50/40"><td class="px-4 py-3 font-bold text-slate-800"><?= e($s['full_name']) ?><div class="text-xs text-slate-500">Terakhir: <?= e($s['last_read'] ?: '-') ?></div></td><td class="px-4 py-3 text-center"><?= e($s['nik']) ?></td><td class="px-4 py-3 text-center"><?= e($s['unit_name']) ?></td><td class="px-4 py-3 text-center"><?= (int)$s['read_items'] ?>/<?= (int)$totalItems ?></td><td class="px-4 py-3 text-center"><?= (int)$s['read_sections'] ?>/<?= (int)$den ?></td><td class="px-4 py-3 min-w-[200px]"><div class="flex items-center gap-3"><div class="h-3 flex-1 rounded-full bg-slate-100 overflow-hidden"><div class="h-full bg-gradient-to-r from-blue-500 to-emerald-500" style="width:<?= e($pct) ?>%"></div></div><b><?= e($pct) ?>%</b></div></td><td class="px-4 py-3 text-center"><span class="px-2 py-1 rounded-full text-xs font-bold <?= $pct>=100?'bg-emerald-100 text-emerald-700':($pct>0?'bg-amber-100 text-amber-700':'bg-slate-100 text-slate-500') ?>"><?= $pct>=100?'Lengkap':($pct>0?'Proses':'Belum Baca') ?></span></td></tr><?php endforeach; ?>
    </tbody></table></div></div>

    <div class="rounded-3xl bg-white shadow-xl border border-slate-100 overflow-hidden">
        <div class="p-5 border-b bg-slate-50 flex items-center justify-between gap-3 flex-wrap">
            <div><h2 class="font-extrabold text-slate-800">Detail Aktivitas yang Sudah Dibaca</h2><p class="text-sm text-slate-500">Tabel ini menampilkan log EP dan bagian yang benar-benar sudah ditandai dibaca. Filter unit mengikuti pilihan di atas.</p></div>
            <a class="rounded-xl bg-emerald-600 text-white px-5 py-2.5 font-bold" href="?module=kisi_pfp&action=export_unit&unit_id=<?= (int)$unitFilter ?>"><i class="fas fa-file-excel mr-2"></i>Export Detail Excel</a>
        </div>
        <div class="overflow-x-auto"><table class="min-w-full text-sm"><thead class="bg-slate-100 uppercase text-xs text-slate-600"><tr><th class="px-4 py-3 text-left">Waktu</th><th class="px-4 py-3 text-left">Nama</th><th class="px-4 py-3">NIK</th><th class="px-4 py-3">Unit</th><th class="px-4 py-3">Pokja</th><th class="px-4 py-3">Std/EP</th><th class="px-4 py-3 text-left">Elemen Penilaian</th><th class="px-4 py-3">Bagian</th></tr></thead><tbody class="divide-y divide-slate-100">
        <?php if (empty($readDetails)): ?>
            <tr><td colspan="8" class="px-4 py-6 text-center text-slate-500">Belum ada aktivitas baca yang tersimpan untuk filter ini.</td></tr>
        <?php else: foreach($readDetails as $d): ?>
            <tr class="hover:bg-emerald-50/40"><td class="px-4 py-3 whitespace-nowrap text-slate-600"><?= e($d['read_at']) ?></td><td class="px-4 py-3 font-bold text-slate-800"><?= e($d['full_name']) ?></td><td class="px-4 py-3 text-center"><?= e($d['nik']) ?></td><td class="px-4 py-3 text-center"><?= e($d['unit_name']) ?></td><td class="px-4 py-3 text-center font-bold text-blue-700"><?= e($d['kode_bab']) ?></td><td class="px-4 py-3 text-center"><?= e($d['no_std']) ?> / <?= e($d['no_ep']) ?></td><td class="px-4 py-3 max-w-xl"><?= e($d['elemen_penilaian']) ?></td><td class="px-4 py-3 text-center"><span class="px-2 py-1 rounded-full bg-emerald-100 text-emerald-700 text-xs font-bold"><?= e($sections[$d['section_key']] ?? $d['section_key']) ?></span></td></tr>
        <?php endforeach; endif; ?>
        </tbody></table></div>
    </div>
<?php endif; ?>
</div>
<script>
async function postPfpRead(url, fd) {
    const response = await fetch(url, {
        method: 'POST',
        body: fd,
        headers: { 'X-Requested-With': 'XMLHttpRequest' },
        credentials: 'same-origin'
    });

    const text = await response.text();
    try {
        return JSON.parse(text);
    } catch (e) {
        throw new Error('Response bukan JSON dari ' + url + ': ' + text.substring(0, 180));
    }
}

async function markPfpRead(itemId, sectionKey, btn) {
    const fd = new FormData();
    fd.append('item_id', itemId);
    fd.append('section_key', sectionKey);
    btn.disabled = true;

    const endpoints = [
        '?module=kisi_pfp&action=mark_read',
        'index.php?module=kisi_pfp&action=mark_read',
        'modules/kisi_pfp/index.php?action=mark_read',
        'modules/kisi_kisi_pfp/index.php?action=mark_read'
    ];

    let lastError = null;
    for (const url of endpoints) {
        try {
            const res = await postPfpRead(url, fd);
            btn.disabled = false;
            if (res.success) {
                btn.className = 'px-3 py-2 rounded-xl bg-emerald-100 text-emerald-700 text-xs font-bold';
                btn.innerHTML = '<i class="fas fa-check mr-1"></i>Sudah dibaca';
                return;
            }
            alert(res.message || 'Gagal menyimpan.');
            return;
        } catch (err) {
            lastError = err;
        }
    }

    btn.disabled = false;
    console.error(lastError);
    alert('Koneksi gagal. Cek apakah folder modul bernama modules/kisi_pfp atau modules/kisi_kisi_pfp dan file index.php sudah diupload.');
}
</script>
