<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard - RSUD Lamadukelleng</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <script src="https://unpkg.com/@phosphor-icons/web"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <link rel="stylesheet" href="css/style.css?v=1.2">
    <link rel="stylesheet" href="css/admin.css?v=1.2">
    <script>
        // Auth Protection
        if (sessionStorage.getItem('isAdminLoggedIn') !== 'true') {
            window.location.href = 'login.html';
        }

        // Server-side session check
        fetch('includes/auth_logic.php?action=check')
            .then(res => res.json())
            .then(data => {
                if (data.status !== 'success') {
                    sessionStorage.removeItem('isAdminLoggedIn');
                    window.location.href = 'login.html';
                }
            });

        function logout() {
            fetch('includes/auth_logic.php?action=logout')
                .then(() => {
                    sessionStorage.clear();
                    window.location.href = 'login.html';
                });
        }
    </script>
    <style>
        /* RESPONSIVE CSS */
        @media (max-width: 1024px) {
            .admin-sidebar { width: 80px; padding: 1.5rem 1rem; }
            .admin-sidebar h2, .admin-sidebar span { display: none; }
            .admin-main { margin-left: 80px; }
        }
        @media (max-width: 768px) {
            .admin-sidebar { transform: translateX(-100%); width: 260px; z-index: 1001; transition: transform 0.3s ease; }
            .admin-sidebar.mobile-active { transform: translateX(0); }
            .admin-sidebar h2, .admin-sidebar span { display: block; }
            .admin-main { margin-left: 0 !important; }
            .stats-grid, .charts-grid { grid-template-columns: 1fr !important; }
            .hamburger-btn { display: flex !important; }
        }
        .hamburger-btn { display: none; background: #f1f5f9; border: none; width: 40px; height: 40px; border-radius: 10px; align-items: center; justify-content: center; cursor: pointer; color: #1e293b; }
        .admin-view { display: none; }
        .admin-view.active { display: block; }
    </style>
</head>
<body class="admin-body">

    <!-- Sidebar -->
    <aside class="admin-sidebar">
        <div class="sidebar-header">
            <i class="ph-fill ph-hospital"></i>
            <h2>RSUD Admin</h2>
        </div>
        <ul class="sidebar-menu" style="flex: 1; overflow-y: auto; min-height: 0; padding: 1rem; list-style: none;">
            <li class="menu-item"><a href="#" class="menu-link active" data-view="view-dashboard"><i class="ph ph-squares-four"></i><span>Dashboard</span></a></li>
            <li class="menu-item"><a href="#" class="menu-link" data-view="view-patients"><i class="ph ph-users"></i><span>Pasien Baru</span></a></li>
            <li class="menu-item"><a href="#" class="menu-link" data-view="view-doctors"><i class="ph ph-user-circle-plus"></i><span>Manajemen Dokter</span></a></li>
            <li class="menu-item"><a href="#" class="menu-link" data-view="view-facilities"><i class="ph ph-first-aid"></i><span>Fasilitas & Layanan</span></a></li>
            <li class="menu-item"><a href="#" class="menu-link" data-view="view-rooms"><i class="ph ph-bed"></i><span>Ketersediaan Kamar</span></a></li>
            <li class="menu-item"><a href="#" class="menu-link" data-view="view-announcements"><i class="ph ph-megaphone"></i><span>Berita & Pengumuman</span></a></li>
            <li class="menu-item"><a href="#" class="menu-link" data-view="view-faq"><i class="ph ph-question"></i><span>Manajemen FAQ</span></a></li>
            <li class="menu-item"><a href="#" class="menu-link" data-view="view-reviews"><i class="ph ph-star"></i><span>Ulasan & Rating</span></a></li>
            <li class="menu-item"><a href="#" class="menu-link" data-view="view-users"><i class="ph ph-shield-check"></i><span>Manajemen User</span></a></li>
            <li class="menu-item"><a href="#" class="menu-link" data-view="view-settings"><i class="ph ph-gear"></i><span>Pengaturan Website</span></a></li>
            <li class="menu-item" style="margin-top: auto;"><a href="#" class="menu-link" onclick="logout()"><i class="ph ph-sign-out"></i><span>Keluar</span></a></li>
        </ul>
    </aside>

    <!-- Main Content -->
    <main class="admin-main">
        <header class="admin-topbar">
            <div class="topbar-left" style="display: flex; align-items: center; gap: 1rem;">
                <button class="hamburger-btn" onclick="toggleSidebar()"><i class="ph ph-list" style="font-size: 1.5rem;"></i></button>
                <h2 id="topbar-title">Dashboard</h2>
            </div>
            <div class="topbar-right">
                <div class="user-profile">
                    <div class="user-avatar">AD</div>
                    <div class="user-info">
                        <p class="fw-600 mb-0" style="font-size: 0.9rem;">Administrator</p>
                        <p class="text-muted mb-0" style="font-size: 0.75rem;">Super Admin</p>
                    </div>
                </div>
            </div>
        </header>

        <div class="admin-content">
            
            <!-- DASHBOARD VIEW -->
            <div id="view-dashboard" class="admin-view active">
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-card-info"><h4>Total Pasien</h4><p class="value" id="stat-total-pasien">0</p></div>
                        <div class="stat-card-icon bg-soft-blue text-blue"><i class="ph-fill ph-users"></i></div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-card-info"><h4>Dokter</h4><p class="value" id="stat-total-dokter">0</p></div>
                        <div class="stat-card-icon bg-soft-green text-green"><i class="ph-fill ph-calendar-check"></i></div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-card-info"><h4>Berita</h4><p class="value" id="stat-total-berita">0</p></div>
                        <div class="stat-card-icon bg-soft-orange text-orange"><i class="ph-fill ph-megaphone"></i></div>
                    </div>
                </div>

                <div class="charts-grid" style="display: grid; grid-template-columns: 2fr 1fr; gap: 1.5rem; margin-top: 1.5rem;">
                    <div class="admin-card p-5">
                        <h3 class="mb-4">Statistik Pendaftaran (7 Hari Terakhir)</h3>
                        <div style="height: 300px;"><canvas id="patientChart"></canvas></div>
                    </div>
                    <div class="admin-card p-5">
                        <h3 class="mb-4">Tingkat Kepuasan</h3>
                        <div style="height: 300px;"><canvas id="satisfactionChart"></canvas></div>
                    </div>
                </div>
            </div>

            <!-- VIEW PASIEN -->
            <div id="view-patients" class="admin-view">
                <div class="section-header" style="margin-bottom: 2rem; display: flex; justify-content: space-between; align-items: center;">
                    <h2 class="section-title">Pendaftaran Pasien Baru</h2>
                    <div class="search-box" style="position: relative; width: 300px;">
                        <i class="ph ph-magnifying-glass" style="position: absolute; left: 1rem; top: 50%; transform: translateY(-50%); color: #94a3b8;"></i>
                        <input type="text" class="form-control" placeholder="Cari pasien..." style="padding-left: 2.8rem; margin-bottom: 0;">
                    </div>
                </div>
                <div class="data-table-container">
                    <table class="schedule-table">
                        <thead><tr><th>Pasien</th><th>NIK</th><th>Layanan</th><th>Status</th><th>Aksi</th></tr></thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>

            <!-- VIEW DOKTER -->
            <div id="view-doctors" class="admin-view">
                <div class="section-header" style="margin-bottom: 2rem; display: flex; justify-content: space-between; align-items: center;">
                    <h2 class="section-title">Manajemen Dokter</h2>
                    <button onclick="openDoctorModal()" class="btn-primary"><i class="ph ph-user-plus"></i> Tambah Dokter</button>
                </div>
                <div class="data-table-container"><table class="schedule-table"><thead><tr><th>Foto</th><th>Nama Dokter</th><th>Spesialis</th><th>Aksi</th></tr></thead><tbody></tbody></table></div>
            </div>

            <!-- VIEW FASILITAS -->
            <div id="view-facilities" class="admin-view">
                <div class="section-header" style="margin-bottom: 2rem; display: flex; justify-content: space-between; align-items: center;">
                    <h2 class="section-title">Fasilitas & Layanan</h2>
                    <button onclick="openFacilityModal()" class="btn-primary"><i class="ph ph-plus-circle"></i> Tambah Fasilitas</button>
                </div>
                <div class="data-table-container"><table class="schedule-table"><thead><tr><th>Nama Fasilitas</th><th>Keterangan</th><th>Aksi</th></tr></thead><tbody></tbody></table></div>
            </div>

            <!-- VIEW KAMAR -->
            <div id="view-rooms" class="admin-view">
                <div class="section-header" style="margin-bottom: 2rem; display: flex; justify-content: space-between; align-items: center;">
                    <h2 class="section-title">Ketersediaan Kamar</h2>
                    <button onclick="openRoomModal('add')" class="btn-primary"><i class="ph ph-plus-circle"></i> Tambah Kelas</button>
                </div>
                <div class="data-table-container"><table class="schedule-table"><thead><tr><th>Kelas</th><th>Total Bed</th><th>Tersedia</th><th>Aksi</th></tr></thead><tbody></tbody></table></div>
            </div>

            <!-- VIEW BERITA -->
            <div id="view-announcements" class="admin-view">
                <div class="section-header" style="margin-bottom: 2rem; display: flex; justify-content: space-between; align-items: center;">
                    <h2 class="section-title">Berita & Pengumuman</h2>
                    <button onclick="openNewsModal()" class="btn-primary"><i class="ph ph-megaphone"></i> Tulis Berita</button>
                </div>
                <div class="data-table-container"><table class="schedule-table"><thead><tr><th>Judul</th><th>Kategori</th><th>Tanggal</th><th>Aksi</th></tr></thead><tbody></tbody></table></div>
            </div>

            <!-- VIEW FAQ -->
            <div id="view-faq" class="admin-view">
                <div class="section-header" style="margin-bottom: 2rem; display: flex; justify-content: space-between; align-items: center;">
                    <h2 class="section-title">Manajemen FAQ</h2>
                    <button onclick="openFaqModal()" class="btn-primary"><i class="ph ph-question"></i> Tambah FAQ</button>
                </div>
                <div class="data-table-container"><table class="schedule-table"><thead><tr><th>Pertanyaan</th><th>Jawaban</th><th>Aksi</th></tr></thead><tbody></tbody></table></div>
            </div>

            <!-- VIEW REVIEWS -->
            <div id="view-reviews" class="admin-view">
                <div class="section-header" style="margin-bottom: 2rem;"><h2 class="section-title">Ulasan Pasien</h2></div>
                <div class="p-4 admin-card" style="max-height: 600px; overflow-y: auto;"></div>
            </div>

            <!-- VIEW USERS -->
            <div id="view-users" class="admin-view">
                <div class="section-header" style="margin-bottom: 2rem; display: flex; justify-content: space-between; align-items: center;">
                    <h2 class="section-title">Manajemen User Admin</h2>
                    <button onclick="openUserModal()" class="btn-primary"><i class="ph ph-user-plus"></i> Tambah Admin</button>
                </div>
                <div class="data-table-container"><table class="schedule-table"><thead><tr><th>Nama</th><th>Username</th><th>Level</th><th>Aksi</th></tr></thead><tbody></tbody></table></div>
            </div>

            <!-- VIEW SETTINGS -->
            <div id="view-settings" class="admin-view">
                <div class="section-header" style="margin-bottom: 2rem;"><h2 class="section-title">Pengaturan Website</h2></div>
                <form onsubmit="handleUniversalSubmit(event, 'settings', null)">
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 2rem;">
                        <div class="admin-card p-5">
                            <h3>Identitas RS</h3>
                            <div class="form-group"><label>Logo</label><input type="file" name="logo" class="form-control" onchange="previewImg(this, 'logo-preview')"><img id="logo-preview" src="" style="width: 100px; margin-top: 10px;"></div>
                            <div class="form-group"><label>Nama RS</label><input type="text" name="nama_rs" class="form-control"></div>
                            <div class="form-group"><label>Slogan</label><input type="text" name="slogan" class="form-control"></div>
                        </div>
                        <div class="admin-card p-5">
                            <h3>Tampilan Hero</h3>
                            <div class="form-group"><label>Background</label><input type="file" name="background" class="form-control" onchange="previewImg(this, 'hero-preview')"><img id="hero-preview" src="" style="width: 100%; height: 100px; object-fit: cover; margin-top: 10px;"></div>
                            <div class="form-group"><label>Judul Beranda</label><input type="text" name="hero_title" class="form-control"></div>
                            <div class="form-group"><label>Alamat RS</label><textarea name="alamat" class="form-control" rows="3"></textarea></div>
                            <div class="form-group"><label>URL Video Hero (YouTube)</label><input type="text" name="video_url" class="form-control" placeholder="https://www.youtube.com/watch?v=..."></div>
                        </div>
                    </div>
                    <button type="submit" class="btn-primary" style="margin-top: 2rem;">Simpan Pengaturan</button>
                </form>
            </div>
        </div>
    </main>

    <!-- ALL MODALS -->
    <!-- Room Modal -->
    <div id="room-modal" class="modal-overlay"><div class="modal-container" style="max-width: 450px;"><div class="modal-header"><h3>Update Kamar</h3><button onclick="closeModal('room-modal')" class="close-modal">&times;</button></div><div class="modal-body"><form onsubmit="handleUniversalSubmit(event, 'kamar', 'room-modal')"><input type="hidden" name="id" id="room-id"><div class="form-group"><label>Nama Kelas</label><input type="text" name="kelas" id="room-name" class="form-control"></div><div class="form-row"><div class="form-group"><label>Total Bed</label><input type="number" name="total" id="room-total" class="form-control"></div><div class="form-group"><label>Tersedia</label><input type="number" name="tersedia" id="room-available" class="form-control"></div></div><button type="submit" class="btn-primary w-100">Simpan</button></form></div></div></div>
    <!-- News Modal -->
    <div id="news-modal" class="modal-overlay"><div class="modal-container" style="max-width: 800px;"><div class="modal-header"><h3>Tulis Berita</h3><button onclick="closeModal('news-modal')" class="close-modal">&times;</button></div><div class="modal-body"><form onsubmit="handleUniversalSubmit(event, 'berita', 'news-modal')"><input type="hidden" name="id" id="news-id"><input type="hidden" name="old_gambar" id="news-old-gambar"><div class="form-group"><label>Judul</label><input type="text" name="judul" id="news-judul" class="form-control" required></div><div class="form-row"><div class="form-group"><label>Kategori</label><select name="kategori" class="form-control"><option value="Kegiatan">Kegiatan</option><option value="Tips">Tips</option><option value="Inovasi">Inovasi</option></select></div><div class="form-group"><label>Gambar</label><input type="file" name="gambar" class="form-control"></div></div><div class="form-group"><label>Isi</label><textarea name="isi" id="news-isi" class="form-control" rows="8" required></textarea></div><button type="submit" class="btn-primary">Publikasikan</button></form></div></div></div>
    <!-- Doctor Modal -->
    <div id="doctor-modal" class="modal-overlay"><div class="modal-container"><div class="modal-header"><h3>Data Dokter</h3><button onclick="closeModal('doctor-modal')" class="close-modal">&times;</button></div><div class="modal-body"><form onsubmit="handleUniversalSubmit(event, 'dokter', 'doctor-modal')"><input type="hidden" name="id" id="doc-id"><input type="hidden" name="old_foto" id="doc-old-foto"><div class="form-group"><label>Nama</label><input type="text" name="nama" id="doc-name-input" class="form-control" required></div><div class="form-group"><label>Spesialis</label><input type="text" name="spesialis" id="doc-spesialis-input" class="form-control" required></div><div class="form-row"><div class="form-group"><label>Hari Praktik</label><input type="text" name="jadwal_hari" id="doc-hari-input" class="form-control" placeholder="Senin - Jumat"></div><div class="form-group"><label>Jam Kerja</label><input type="text" name="jadwal_jam" id="doc-jam-input" class="form-control" placeholder="08.00 - 14.00 WITA"></div></div><div class="form-group"><label>Foto</label><input type="file" name="foto" class="form-control"></div><button type="submit" class="btn-primary w-100">Simpan</button></form></div></div></div>
    <!-- User Modal -->
    <div id="user-modal" class="modal-overlay"><div class="modal-container"><div class="modal-header"><h3>Data Admin</h3><button onclick="closeModal('user-modal')" class="close-modal">&times;</button></div><div class="modal-body"><form onsubmit="handleUniversalSubmit(event, 'users', 'user-modal')"><input type="hidden" name="id" id="user-id"><div class="form-group"><label>Nama</label><input type="text" name="nama" id="user-name-input" class="form-control" required></div><div class="form-group"><label>Username</label><input type="text" name="username" id="user-username-input" class="form-control" required></div><div class="form-group"><label>Password</label><input type="password" name="password" class="form-control" placeholder="Kosongkan jika tidak diubah"></div><button type="submit" class="btn-primary w-100">Simpan</button></form></div></div></div>
    <!-- FAQ & Facility Modals... -->
    <div id="facility-modal" class="modal-overlay"><div class="modal-container"><div class="modal-header"><h3>Data Fasilitas</h3><button onclick="closeModal('facility-modal')" class="close-modal">&times;</button></div><div class="modal-body"><form onsubmit="handleUniversalSubmit(event, 'fasilitas', 'facility-modal')"><input type="hidden" name="id" id="facility-id"><div class="form-group"><label>Nama</label><input type="text" name="nama" id="facility-name-input" class="form-control" required></div><div class="form-group"><label>Keterangan</label><textarea name="keterangan" id="facility-desc-input" class="form-control"></textarea></div><button type="submit" class="btn-primary w-100">Simpan</button></form></div></div></div>
    <div id="faq-modal" class="modal-overlay"><div class="modal-container"><div class="modal-header"><h3>Data FAQ</h3><button onclick="closeModal('faq-modal')" class="close-modal">&times;</button></div><div class="modal-body"><form onsubmit="handleUniversalSubmit(event, 'faq', 'faq-modal')"><input type="hidden" name="id" id="faq-id"><div class="form-group"><label>Pertanyaan</label><input type="text" name="pertanyaan" id="faq-q-input" class="form-control" required></div><div class="form-group"><label>Jawaban</label><textarea name="jawaban" id="faq-a-input" class="form-control" rows="5" required></textarea></div><button type="submit" class="btn-primary w-100">Simpan</button></form></div></div></div>

    <script>
        // CORE LOGIC
        let patientChart, satisfactionChart;

        window.onload = () => loadAllData();

        function loadAllData() {
            fetch('includes/api_manager.php?action=summary')
                .then(res => res.json())
                .then(data => {
                    document.getElementById('stat-total-pasien').innerText = data.total_pasien;
                    document.getElementById('stat-total-dokter').innerText = data.total_dokter;
                    document.getElementById('stat-total-berita').innerText = data.total_berita;
                    renderCharts(data.weekly_stats, data.rating_stats);
                });

            fetchData('dokter', '#view-doctors tbody', renderDoctorRow);
            fetchData('faq', '#view-faq tbody', renderFaqRow);
            fetchData('kamar', '#view-rooms tbody', renderRoomRow);
            fetchData('berita', '#view-announcements tbody', renderNewsRow);
            fetchData('pendaftaran', '#view-patients tbody', renderPatientRow);
            fetchData('reviews', '#view-reviews .p-4', renderReviewRow);
            fetchData('users', '#view-users tbody', renderUserRow);
            fetchData('fasilitas', '#view-facilities tbody', renderFacilityRow);
            loadSettings();
        }

        function loadSettings() {
            fetch('includes/api_manager.php?action=fetch&table=settings&v=' + new Date().getTime())
                .then(res => res.json())
                .then(dataArr => {
                    const data = dataArr[0];
                    if (data) {
                        const form = document.querySelector('#view-settings form');
                        form.querySelector('[name="nama_rs"]').value = data.nama_rs || '';
                        form.querySelector('[name="slogan"]').value = data.slogan || '';
                        form.querySelector('[name="hero_title"]').value = data.hero_title || '';
                        if (form.querySelector('[name="alamat"]')) form.querySelector('[name="alamat"]').value = data.alamat || '';
                        if (form.querySelector('[name="video_url"]')) form.querySelector('[name="video_url"]').value = data.video_url || '';
                        if (data.logo) document.getElementById('logo-preview').src = 'uploads/' + data.logo + '?v=' + new Date().getTime();
                        if (data.background) document.getElementById('hero-preview').src = 'uploads/' + data.background + '?v=' + new Date().getTime();
                    }
                });
        }

        function fetchData(table, containerSelector, renderFn) {
            fetch(`includes/api_manager.php?action=fetch&table=${table}`)
                .then(res => res.json())
                .then(data => {
                    const container = document.querySelector(containerSelector);
                    if (!container) return;
                    container.innerHTML = '';
                    if (!Array.isArray(data) || data.length === 0) {
                        container.innerHTML = '<tr><td colspan="5" style="text-align:center; color:#94a3b8;">Belum ada data.</td></tr>';
                        return;
                    }
                    data.forEach(item => container.innerHTML += renderFn(item));
                });
        }

        function handleUniversalSubmit(e, table, modalId) {
            e.preventDefault();
            const formData = new FormData(e.target);
            const btn = e.target.querySelector('button[type="submit"]');
            const originalText = btn.innerHTML;
            
            btn.disabled = true;
            btn.innerHTML = '<i class="ph ph-circle-notch animate-spin"></i> Menyimpan...';

            fetch(`includes/api_manager.php?action=add&table=${table}`, { method: 'POST', body: formData })
                .then(res => res.json())
                .then(data => {
                    if (data.status === 'success') {
                        alert('Berhasil disimpan!');
                        if (modalId) closeModal(modalId);
                        
                        // Optimasi: Jangan reload semua jika hanya simpan settings
                        if (table === 'settings') {
                            loadSettings();
                        } else {
                            loadAllData();
                        }
                    } else { alert('Error: ' + data.message); }
                })
                .catch(err => alert('Gagal terhubung: ' + err))
                .finally(() => { 
                    btn.disabled = false; 
                    btn.innerHTML = originalText; 
                });
        }

        // RENDERERS
        const renderDoctorRow = (d) => `<tr><td><img src="uploads/${d.foto}" style="width:40px;height:40px;border-radius:50%;object-fit:cover;"></td><td>${d.nama}</td><td>${d.spesialis}<br><small class="text-muted">${d.jadwal_hari} | ${d.jadwal_jam}</small></td><td><button onclick='editItem("dokter", ${JSON.stringify(d)})' class="text-primary"><i class="ph ph-pencil"></i></button> <button onclick="deleteItem('dokter', ${d.id}, this)" class="text-red"><i class="ph ph-trash"></i></button></td></tr>`;
        const renderPatientRow = (p) => `<tr><td>${p.nama_lengkap}</td><td>${p.nik}</td><td>${p.poli}</td><td><span class="status-badge ${p.status === 'Diterima' ? 'status-confirmed' : 'status-pending'}">${p.status}</span></td><td>${p.status !== 'Diterima' ? `<button onclick="confirmPatient(${p.id}, this)" class="btn-primary" style="padding:4px 8px;font-size:11px;">Terima</button>` : ''} <button onclick="deleteItem('pendaftaran', ${p.id}, this)" class="text-red"><i class="ph ph-trash"></i></button></td></tr>`;
        const renderRoomRow = (k) => `<tr><td>${k.kelas}</td><td>${k.total}</td><td>${k.tersedia}</td><td><button onclick='editItem("kamar", ${JSON.stringify(k)})' class="text-primary"><i class="ph ph-pencil"></i></button> <button onclick="deleteItem('kamar', ${k.id}, this)" class="text-red"><i class="ph ph-trash"></i></button></td></tr>`;
        const renderNewsRow = (n) => `<tr><td>${n.judul}</td><td>${n.kategori}</td><td>${new Date(n.created_at).toLocaleDateString()}</td><td><button onclick='editItem("berita", ${JSON.stringify(n)})' class="text-primary"><i class="ph ph-pencil"></i></button> <button onclick="deleteItem('berita', ${n.id}, this)" class="text-red"><i class="ph ph-trash"></i></button></td></tr>`;
        const renderFaqRow = (f) => `<tr><td>${f.pertanyaan}</td><td>${f.jawaban.substring(0,50)}...</td><td><button onclick='editItem("faq", ${JSON.stringify(f)})' class="text-primary"><i class="ph ph-pencil"></i></button> <button onclick="deleteItem('faq', ${f.id}, this)" class="text-red"><i class="ph ph-trash"></i></button></td></tr>`;
        const renderFacilityRow = (f) => `<tr><td>${f.nama}</td><td>${f.keterangan}</td><td><button onclick='editItem("fasilitas", ${JSON.stringify(f)})' class="text-primary"><i class="ph ph-pencil"></i></button> <button onclick="deleteItem('fasilitas', ${f.id}, this)" class="text-red"><i class="ph ph-trash"></i></button></td></tr>`;
        const renderUserRow = (u) => `<tr><td>${u.nama}</td><td>${u.username}</td><td>Admin</td><td><button onclick='editItem("users", ${JSON.stringify(u)})' class="text-primary"><i class="ph ph-pencil"></i></button> <button onclick="deleteItem('users', ${u.id}, this)" class="text-red"><i class="ph ph-trash"></i></button></td></tr>`;
        const renderReviewRow = (r) => `<div class="p-4 border-bottom"><div class="d-flex justify-content-between"><b>${r.nama}</b> <span>${r.rating}/4 ⭐</span></div><p>${r.komentar}</p><button onclick="deleteItem('reviews', ${r.id}, this)" class="text-red">Hapus</button></div>`;

        // ACTIONS
        function deleteItem(table, id, btn) {
            if (confirm('Hapus selamanya?')) {
                fetch(`includes/api_manager.php?action=delete&table=${table}&id=${id}`).then(() => loadAllData());
            }
        }

        function confirmPatient(id, btn) {
            const fd = new FormData(); fd.append('id', id); fd.append('status', 'Diterima');
            fetch('includes/api_manager.php?action=add&table=pendaftaran', { method: 'POST', body: fd }).then(() => loadAllData());
        }

        function editItem(type, data) {
            if (type === 'dokter') { 
                document.getElementById('doc-id').value = data.id; 
                document.getElementById('doc-name-input').value = data.nama; 
                document.getElementById('doc-spesialis-input').value = data.spesialis; 
                document.getElementById('doc-hari-input').value = data.jadwal_hari || ''; 
                document.getElementById('doc-jam-input').value = data.jadwal_jam || ''; 
                document.getElementById('doc-old-foto').value = data.foto; 
                openModal('doctor-modal'); 
            }
            if (type === 'kamar') { document.getElementById('room-id').value = data.id; document.getElementById('room-name').value = data.kelas; document.getElementById('room-total').value = data.total; document.getElementById('room-available').value = data.tersedia; openModal('room-modal'); }
            if (type === 'berita') { document.getElementById('news-id').value = data.id; document.getElementById('news-judul').value = data.judul; document.getElementById('news-isi').value = data.isi; document.getElementById('news-old-gambar').value = data.gambar; openModal('news-modal'); }
            if (type === 'faq') { document.getElementById('faq-id').value = data.id; document.getElementById('faq-q-input').value = data.pertanyaan; document.getElementById('faq-a-input').value = data.jawaban; openModal('faq-modal'); }
            if (type === 'fasilitas') { document.getElementById('facility-id').value = data.id; document.getElementById('facility-name-input').value = data.nama; document.getElementById('facility-desc-input').value = data.keterangan; openModal('facility-modal'); }
            if (type === 'users') { document.getElementById('user-id').value = data.id; document.getElementById('user-name-input').value = data.nama; document.getElementById('user-username-input').value = data.username; openModal('user-modal'); }
        }

        // UI HELPERS
        function switchView(viewId, title) {
            document.querySelectorAll('.admin-view').forEach(v => v.classList.remove('active'));
            document.getElementById(viewId).classList.add('active');
            document.getElementById('topbar-title').innerText = title;
            document.querySelectorAll('.menu-link').forEach(l => {
                l.classList.remove('active');
                if(l.getAttribute('data-view') === viewId) l.classList.add('active');
            });
        }

        document.querySelectorAll('.menu-link').forEach(link => {
            link.addEventListener('click', (e) => {
                const viewId = link.getAttribute('data-view');
                if(viewId) { e.preventDefault(); switchView(viewId, link.querySelector('span').innerText); }
            });
        });

        function openModal(id) { document.getElementById(id).classList.add('active'); }
        function closeModal(id) { document.getElementById(id).classList.remove('active'); }
        function toggleSidebar() { document.querySelector('.admin-sidebar').classList.toggle('mobile-active'); }
        function previewImg(input, pid) { if (input.files && input.files[0]) { let reader = new FileReader(); reader.onload = (e) => { document.getElementById(pid).src = e.target.result; document.getElementById(pid).style.display = 'block'; }; reader.readAsDataURL(input.files[0]); } }

        function renderCharts(weekly, ratings) {
            const ctx1 = document.getElementById('patientChart').getContext('2d');
            if (patientChart) patientChart.destroy();
            patientChart = new Chart(ctx1, { type: 'line', data: { labels: ['Min','Sen','Sel','Rab','Kam','Jum','Sab'], datasets: [{ label: 'Pasien', data: weekly, borderColor: '#0D8ABC', fill: true, tension: 0.4 }] } });

            const ctx2 = document.getElementById('satisfactionChart').getContext('2d');
            if (satisfactionChart) satisfactionChart.destroy();
            satisfactionChart = new Chart(ctx2, { type: 'doughnut', data: { labels: ['Buruk','Cukup','Baik','Sangat Baik'], datasets: [{ data: ratings, backgroundColor: ['#f87171','#fbbf24','#38bdf8','#10b981'] }] } });
        }

        // Modals Openers for "Add"
        function openDoctorModal() { document.querySelector('#doctor-modal form').reset(); document.getElementById('doc-id').value=''; openModal('doctor-modal'); }
        function openNewsModal() { document.querySelector('#news-modal form').reset(); document.getElementById('news-id').value=''; openModal('news-modal'); }
        function openUserModal() { document.querySelector('#user-modal form').reset(); document.getElementById('user-id').value=''; openModal('user-modal'); }
        function openFacilityModal() { document.querySelector('#facility-modal form').reset(); document.getElementById('facility-id').value=''; openModal('facility-modal'); }
        function openFaqModal() { document.querySelector('#faq-modal form').reset(); document.getElementById('faq-id').value=''; openModal('faq-modal'); }
        function openRoomModal() { document.querySelector('#room-modal form').reset(); document.getElementById('room-id').value=''; openModal('room-modal'); }
    </script>
</body>
</html>
