<?php
declare(strict_types=1);

error_reporting(E_ALL);
ini_set('display_errors', '1');

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

checkAuth();
$conn = getConnection();

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

if (!function_exists('fetchDoctorsPoliUI')) {
    function fetchDoctorsPoliUI(mysqli $conn): array
    {
        $rows = [];
        $sql = "SELECT id, doctor_name, poli_name, room_number, wing, schedule_code, practice_days, practice_hours
                FROM polyclinic_doctors
                WHERE is_active = 1
                ORDER BY doctor_name ASC";
        $res = $conn->query($sql);
        if ($res) {
            while ($row = $res->fetch_assoc()) {
                $rows[] = $row;
            }
        }
        return $rows;
    }
}

$doctorOptions = fetchDoctorsPoliUI($conn);
$importUrl = 'index.php?module=import_poliklinik_doctors';

$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host   = $_SERVER['HTTP_HOST'] ?? '';
$apiUrl = $scheme . '://' . $host . '/modules/laporan_harian_poliklinik_api.php';
?>

<div class="max-w-6xl mx-auto p-4 md:p-6 space-y-6">
    <div class="bg-gradient-to-r from-cyan-600 to-blue-700 text-white rounded-2xl shadow-xl p-5">
        <h1 class="text-2xl md:text-3xl font-bold">Laporan Harian Poliklinik</h1>
        <p class="text-white/90 mt-1">Input kunjungan dokter, dokter tidak praktek, kendala, inventaris, dan petugas pemeriksaan.</p>
    </div>

    <div class="bg-white rounded-2xl shadow p-4 md:p-6">
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
                <label class="block text-sm text-slate-600 mb-1">Tanggal</label>
                <input id="tanggal" type="date" class="w-full border border-slate-300 rounded-xl px-3 py-2">
            </div>
            <div>
                <label class="block text-sm text-slate-600 mb-1">Shift</label>
                <select id="shift" class="w-full border border-slate-300 rounded-xl px-3 py-2">
                    <option value="Pagi">Pagi</option>
                    <option value="Sore">Sore</option>
                </select>
            </div>
            <div class="flex items-end gap-2">
                <button id="btnList" type="button" class="px-4 py-2 rounded-xl border border-slate-300 hover:bg-slate-50">Lihat Laporan</button>
                <button id="btnSave" type="button" class="px-4 py-2 rounded-xl bg-blue-600 text-white hover:bg-blue-700">Simpan Laporan</button>
            </div>
        </div>
    </div>

    <div class="bg-white rounded-2xl shadow p-4 md:p-6">
        <div class="flex flex-wrap items-center justify-between gap-2 mb-3">
            <h2 class="text-lg font-semibold">A. Kunjungan Dokter</h2>
            <div class="flex gap-2 flex-wrap">
                <a href="<?= e($importUrl) ?>" class="text-sm px-3 py-2 border rounded-xl hover:bg-slate-50">Import CSV Dokter</a>
                <button id="btnOpenDoctorModal" type="button" class="text-sm px-3 py-2 border rounded-xl hover:bg-slate-50">+ Master Dokter Baru</button>
                <button id="btnAddA" type="button" class="text-sm px-3 py-2 border rounded-xl hover:bg-slate-50">+ Tambah Dokter</button>
            </div>
        </div>
        <div id="rowsA" class="space-y-3"></div>
    </div>

    <div class="bg-white rounded-2xl shadow p-4 md:p-6">
        <div class="flex flex-wrap items-center justify-between gap-2 mb-3">
            <h2 class="text-lg font-semibold">B. Dokter Tidak Praktek</h2>
            <button id="btnAddB" type="button" class="text-sm px-3 py-2 border rounded-xl hover:bg-slate-50">+ Tambah Tidak Praktek</button>
        </div>
        <div id="rowsB" class="space-y-3"></div>
    </div>

    <div class="bg-white rounded-2xl shadow p-4 md:p-6">
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
                <label class="block text-sm text-slate-600 mb-1">C. Pasien Khusus</label>
                <textarea id="pasienKhusus" rows="4" class="w-full border border-slate-300 rounded-xl px-3 py-2"></textarea>
            </div>
            <div>
                <label class="block text-sm text-slate-600 mb-1">D. Masalah / Kendala</label>
                <textarea id="masalah" rows="4" class="w-full border border-slate-300 rounded-xl px-3 py-2"></textarea>
            </div>
            <div>
                <label class="block text-sm text-slate-600 mb-1">E. Inventaris / Logistik</label>
                <textarea id="inventaris" rows="4" class="w-full border border-slate-300 rounded-xl px-3 py-2"></textarea>
            </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mt-4">
            <div>
                <label class="block text-sm text-slate-600 mb-1">Petugas Echo</label>
                <input id="petugasEcho" class="w-full border border-slate-300 rounded-xl px-3 py-2">
            </div>
            <div>
                <label class="block text-sm text-slate-600 mb-1">Petugas Treadmill</label>
                <input id="petugasTreadmill" class="w-full border border-slate-300 rounded-xl px-3 py-2">
            </div>
            <div>
                <label class="block text-sm text-slate-600 mb-1">Petugas EKG</label>
                <input id="petugasEKG" class="w-full border border-slate-300 rounded-xl px-3 py-2">
            </div>
            <div>
                <label class="block text-sm text-slate-600 mb-1">Nama Katim / Pelapor</label>
                <input id="namaKatim" value="<?= e($_SESSION['full_name'] ?? $_SESSION['user']['nama'] ?? '') ?>" class="w-full border border-slate-300 rounded-xl px-3 py-2">
            </div>
        </div>
    </div>
</div>

<div id="reportsModal" class="fixed inset-0 bg-black/50 hidden z-50">
    <div class="max-w-4xl mx-auto mt-10 bg-white rounded-2xl shadow-xl p-4 max-h-[85vh] overflow-auto">
        <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg font-semibold">Daftar Laporan Tersimpan</h3>
            <button id="reportsClose" type="button" class="px-3 py-1 rounded-lg border">Tutup</button>
        </div>
        <div id="reportsContent" class="space-y-3 text-sm text-slate-700">Memuat...</div>
    </div>
</div>

<div id="doctorModal" class="fixed inset-0 bg-black/50 hidden z-50">
    <div class="max-w-2xl mx-auto mt-10 bg-white rounded-2xl shadow-xl p-5">
        <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg font-semibold">Tambah Dokter Baru</h3>
            <button id="doctorModalClose" type="button" class="px-3 py-1 rounded-lg border">Tutup</button>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
                <label class="block text-sm text-slate-600 mb-1">Nama Dokter *</label>
                <input id="md_doctor_name" class="w-full border border-slate-300 rounded-xl px-3 py-2">
            </div>
            <div>
                <label class="block text-sm text-slate-600 mb-1">Nama Poli *</label>
                <input id="md_poli_name" class="w-full border border-slate-300 rounded-xl px-3 py-2">
            </div>
            <div>
                <label class="block text-sm text-slate-600 mb-1">Nomor Ruangan</label>
                <input id="md_room_number" class="w-full border border-slate-300 rounded-xl px-3 py-2">
            </div>
            <div>
                <label class="block text-sm text-slate-600 mb-1">Wing</label>
                <input id="md_wing" class="w-full border border-slate-300 rounded-xl px-3 py-2">
            </div>
            <div>
                <label class="block text-sm text-slate-600 mb-1">Schedule Code</label>
                <input id="md_schedule_code" class="w-full border border-slate-300 rounded-xl px-3 py-2">
            </div>
            <div>
                <label class="block text-sm text-slate-600 mb-1">Hari Praktek</label>
                <input id="md_practice_days" class="w-full border border-slate-300 rounded-xl px-3 py-2">
            </div>
            <div class="md:col-span-2">
                <label class="block text-sm text-slate-600 mb-1">Jam Praktek</label>
                <input id="md_practice_hours" class="w-full border border-slate-300 rounded-xl px-3 py-2">
            </div>
        </div>

        <div class="mt-4 flex justify-end gap-2">
            <button id="btnSaveDoctor" type="button" class="px-4 py-2 rounded-xl bg-blue-600 text-white hover:bg-blue-700">Simpan Dokter</button>
        </div>
    </div>
</div>

<script>
const AJAX_BASE = '<?= e($apiUrl) ?>';
let doctors = <?= json_encode($doctorOptions, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;

const rowsA = document.getElementById('rowsA');
const rowsB = document.getElementById('rowsB');

function doctorOptionsHTML(selectedId = '') {
    const opts = ['<option value="">-- pilih dokter --</option>'];
    doctors.forEach(d => {
        const selected = String(d.id) === String(selectedId) ? 'selected' : '';
        const label = `${d.doctor_name} | ${d.poli_name}${d.practice_days ? ' | ' + d.practice_days : ''}${d.practice_hours ? ' | ' + d.practice_hours : ''}`;
        opts.push(`<option value="${d.id}" ${selected}>${label}</option>`);
    });
    return opts.join('');
}

function getDoctorNameById(id) {
    const found = doctors.find(d => String(d.id) === String(id));
    return found ? found.doctor_name : '';
}

function addRowA(init = {}) {
    const wrap = document.createElement('div');
    wrap.className = 'grid grid-cols-12 gap-2 items-start';
    wrap.setAttribute('data-a-row', '1');
    wrap.innerHTML = `
        <select data-a-doctor-id class="col-span-12 md:col-span-7 border rounded-xl px-3 py-2">
            ${doctorOptionsHTML(init.doctor_id || '')}
        </select>
        <input data-a-nama class="col-span-12 md:col-span-3 border rounded-xl px-3 py-2" placeholder="Nama dokter (manual)" value="${init.nama || ''}">
        <input data-a-jumlah type="number" min="0" class="col-span-10 md:col-span-1 border rounded-xl px-3 py-2" placeholder="Jml" value="${init.jumlah || ''}">
        <button type="button" class="col-span-2 md:col-span-1 px-3 py-2 rounded-xl border text-red-600" onclick="this.parentElement.remove()">🗑️</button>
    `;
    const sel = wrap.querySelector('[data-a-doctor-id]');
    const nama = wrap.querySelector('[data-a-nama]');
    sel.addEventListener('change', () => {
        if (sel.value) nama.value = getDoctorNameById(sel.value);
    });
    if (sel.value && !nama.value) nama.value = getDoctorNameById(sel.value);
    rowsA.appendChild(wrap);
}

function addRowB(init = {}) {
    const wrap = document.createElement('div');
    wrap.className = 'grid grid-cols-12 gap-2 items-start';
    wrap.setAttribute('data-b-row', '1');
    wrap.innerHTML = `
        <select data-b-doctor-id class="col-span-12 md:col-span-5 border rounded-xl px-3 py-2">
            ${doctorOptionsHTML(init.doctor_id || '')}
        </select>
        <input data-b-nama class="col-span-12 md:col-span-3 border rounded-xl px-3 py-2" placeholder="Nama dokter (manual)" value="${init.nama || ''}">
        <input data-b-ket class="col-span-10 md:col-span-3 border rounded-xl px-3 py-2" placeholder="Tgl / Keterangan" value="${init.tanggal || ''}">
        <button type="button" class="col-span-2 md:col-span-1 px-3 py-2 rounded-xl border text-red-600" onclick="this.parentElement.remove()">🗑️</button>
    `;
    const sel = wrap.querySelector('[data-b-doctor-id]');
    const nama = wrap.querySelector('[data-b-nama]');
    sel.addEventListener('change', () => {
        if (sel.value) nama.value = getDoctorNameById(sel.value);
    });
    if (sel.value && !nama.value) nama.value = getDoctorNameById(sel.value);
    rowsB.appendChild(wrap);
}

function clearRows(container) {
    while (container.firstChild) container.removeChild(container.firstChild);
}

async function safeJson(res) {
    const text = await res.text();
    try {
        return JSON.parse(text);
    } catch (e) {
        throw new Error('Response bukan JSON: ' + text.substring(0, 300));
    }
}

async function refreshDoctors() {
    const res = await fetch(`${AJAX_BASE}?ajax_action=getDoctors`, { credentials: 'same-origin' });
    const data = await safeJson(res);
    if (!data.ok) throw new Error(data.error || 'Gagal memuat dokter');
    doctors = data.items || [];
}

async function saveDoctor() {
    const payload = {
        doctor_name: document.getElementById('md_doctor_name').value.trim(),
        poli_name: document.getElementById('md_poli_name').value.trim(),
        room_number: document.getElementById('md_room_number').value.trim(),
        wing: document.getElementById('md_wing').value.trim(),
        schedule_code: document.getElementById('md_schedule_code').value.trim(),
        practice_days: document.getElementById('md_practice_days').value.trim(),
        practice_hours: document.getElementById('md_practice_hours').value.trim()
    };

    const res = await fetch(`${AJAX_BASE}?ajax_action=addDoctor`, {
        method: 'POST',
        credentials: 'same-origin',
        headers: {'Content-Type':'application/json', 'X-Requested-With':'XMLHttpRequest'},
        body: JSON.stringify(payload)
    });

    const data = await safeJson(res);
    if (!data.ok) throw new Error(data.error || 'Gagal simpan dokter');

    await refreshDoctors();

    document.querySelectorAll('[data-a-doctor-id],[data-b-doctor-id]').forEach(sel => {
        const current = sel.value;
        sel.innerHTML = doctorOptionsHTML(current);
    });

    document.getElementById('doctorModal').classList.add('hidden');
    ['md_doctor_name','md_poli_name','md_room_number','md_wing','md_schedule_code','md_practice_days','md_practice_hours']
        .forEach(id => document.getElementById(id).value = '');

    alert(data.message || 'Dokter berhasil ditambahkan.');
}

async function saveReport() {
    const payload = {
        tanggal: document.getElementById('tanggal').value,
        shift: document.getElementById('shift').value,
        kunjunganDokter: [...document.querySelectorAll('[data-a-row]')].map(r => ({
            doctor_id: r.querySelector('[data-a-doctor-id]').value || null,
            nama: r.querySelector('[data-a-nama]').value.trim(),
            jumlah: parseInt(r.querySelector('[data-a-jumlah]').value || '0', 10) || 0
        })).filter(x => x.nama),
        dokterTidakPraktek: [...document.querySelectorAll('[data-b-row]')].map(r => ({
            doctor_id: r.querySelector('[data-b-doctor-id]').value || null,
            nama: r.querySelector('[data-b-nama]').value.trim(),
            tanggal: r.querySelector('[data-b-ket]').value.trim()
        })).filter(x => x.nama || x.tanggal),
        pasienKhusus: document.getElementById('pasienKhusus').value,
        masalah: document.getElementById('masalah').value,
        inventaris: document.getElementById('inventaris').value,
        petugasEcho: document.getElementById('petugasEcho').value,
        petugasTreadmill: document.getElementById('petugasTreadmill').value,
        petugasEKG: document.getElementById('petugasEKG').value,
        namaKatim: document.getElementById('namaKatim').value
    };

    const res = await fetch(`${AJAX_BASE}?ajax_action=saveReport`, {
        method: 'POST',
        credentials: 'same-origin',
        headers: {'Content-Type':'application/json', 'X-Requested-With':'XMLHttpRequest'},
        body: JSON.stringify(payload)
    });

    const data = await safeJson(res);
    if (!data.ok) throw new Error(data.error || 'Gagal menyimpan laporan');
    alert(`Laporan tersimpan. ID: ${data.id || '-'}`);
}

async function showReports() {
    const modal = document.getElementById('reportsModal');
    const content = document.getElementById('reportsContent');
    modal.classList.remove('hidden');
    content.innerHTML = 'Memuat...';

    try {
        const res = await fetch(`${AJAX_BASE}?ajax_action=listReports`, { credentials: 'same-origin' });
        const data = await safeJson(res);
        if (!data.ok) throw new Error(data.error || 'Gagal memuat laporan');

        content.innerHTML = (data.items || []).map(r => {
            const kunj = (r.kunjunganDokter || []).map(d => `${d.nama} (${d.jumlah || 0})`).join(', ') || '-';
            const off = (r.dokterTidakPraktek || []).map(d => `${d.nama}${d.tanggal ? ' - ' + d.tanggal : ''}`).join(', ') || '-';
            return `
                <div class="border border-slate-200 rounded-xl p-4">
                    <div class="flex flex-wrap justify-between gap-2">
                        <div class="font-semibold">${r.tanggal} • Shift ${r.shift}</div>
                        <div class="text-slate-500">Pelapor: ${r.nama_katim || '-'}</div>
                    </div>
                    <div class="mt-2 text-sm space-y-1">
                        <div><b>A. Kunjungan:</b> ${kunj}</div>
                        <div><b>B. Tidak Praktek:</b> ${off}</div>
                        <div><b>C. Pasien Khusus:</b> ${r.pasien_khusus || '-'}</div>
                        <div><b>D. Masalah:</b> ${r.masalah || '-'}</div>
                        <div><b>E. Inventaris:</b> ${r.inventaris || '-'}</div>
                    </div>
                    <div class="mt-3">
                        <button class="px-3 py-2 border rounded-lg hover:bg-slate-50"
                            onclick='useThisReport(${JSON.stringify(r).replace(/'/g, "&apos;")})'>
                            Pakai laporan ini
                        </button>
                    </div>
                </div>
            `;
        }).join('') || '<div class="text-slate-500">Belum ada laporan.</div>';
    } catch (e) {
        content.innerHTML = `<div class="text-red-600">Gagal memuat: ${e.message}</div>`;
    }
}

function useThisReport(r) {
    document.getElementById('tanggal').value = r.tanggal || '';
    document.getElementById('shift').value = r.shift || 'Pagi';
    document.getElementById('pasienKhusus').value = r.pasien_khusus || '';
    document.getElementById('masalah').value = r.masalah || '';
    document.getElementById('inventaris').value = r.inventaris || '';
    document.getElementById('petugasEcho').value = r.petugas_echo || '';
    document.getElementById('petugasTreadmill').value = r.petugas_treadmill || '';
    document.getElementById('petugasEKG').value = r.petugas_ekg || '';
    document.getElementById('namaKatim').value = r.nama_katim || '';

    clearRows(rowsA);
    clearRows(rowsB);

    (r.kunjunganDokter || []).forEach(addRowA);
    (r.dokterTidakPraktek || []).forEach(addRowB);

    if ((r.kunjunganDokter || []).length === 0) addRowA();
    if ((r.dokterTidakPraktek || []).length === 0) addRowB();

    document.getElementById('reportsModal').classList.add('hidden');
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

document.getElementById('btnAddA').addEventListener('click', () => addRowA());
document.getElementById('btnAddB').addEventListener('click', () => addRowB());
document.getElementById('btnSave').addEventListener('click', async () => {
    try { await saveReport(); }
    catch (e) { alert('Gagal menyimpan: ' + e.message); }
});
document.getElementById('btnList').addEventListener('click', showReports);
document.getElementById('reportsClose').addEventListener('click', () => {
    document.getElementById('reportsModal').classList.add('hidden');
});
document.getElementById('btnOpenDoctorModal').addEventListener('click', () => {
    document.getElementById('doctorModal').classList.remove('hidden');
});
document.getElementById('doctorModalClose').addEventListener('click', () => {
    document.getElementById('doctorModal').classList.add('hidden');
});
document.getElementById('btnSaveDoctor').addEventListener('click', async () => {
    try { await saveDoctor(); }
    catch (e) { alert('Gagal tambah dokter: ' + e.message); }
});

addRowA();
addRowB();
</script>