<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/app.php';
checkAuth();

$conn = getConnection();
$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) exit('ID RDK tidak valid.');

function e($v): string { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
function dindo($date): string {
    if (empty($date)) return '-';
    $ts = strtotime((string)$date);
    if (!$ts) return (string)$date;
    $bulan = [1=>'Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember'];
    return date('d', $ts) . ' ' . ($bulan[(int)date('n',$ts)] ?? '') . ' ' . date('Y',$ts);
}

$sql = "SELECT r.*, COALESCE(u.name,'-') AS unit_name,
               COALESCE(ep.full_name,'-') AS presenter_name
        FROM rdk_cases r
        LEFT JOIN units u ON u.id = r.unit_id
        LEFT JOIN employees ep ON ep.id = r.presenter_employee_id
        WHERE r.id = ? LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $id);
$stmt->execute();
$res = $stmt->get_result();
$data = $res ? $res->fetch_assoc() : null;
$stmt->close();
if (!$data) exit('Data RDK tidak ditemukan.');

$participants = [];
if ($st = $conn->prepare("SELECT * FROM rdk_case_participants WHERE rdk_case_id = ? ORDER BY id ASC")) {
    $st->bind_param('i', $id);
    $st->execute();
    $rs = $st->get_result();
    while ($rs && $r = $rs->fetch_assoc()) $participants[] = $r;
    $st->close();
}
$feedbacks = [];
if ($st = $conn->prepare("SELECT * FROM rdk_case_feedbacks WHERE rdk_case_id = ? ORDER BY id ASC")) {
    $st->bind_param('i', $id);
    $st->execute();
    $rs = $st->get_result();
    while ($rs && $r = $rs->fetch_assoc()) $feedbacks[] = $r;
    $st->close();
}
?><!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Print RDK</title>
<style>
    body{font-family:Arial,Helvetica,sans-serif;color:#111827;margin:0;background:#eef2ff}
    .page{max-width:960px;margin:24px auto;background:#fff;padding:28px 34px;box-shadow:0 10px 30px rgba(0,0,0,.08)}
    .head{text-align:center;border-bottom:3px solid #1d4ed8;padding-bottom:14px;margin-bottom:20px}
    .head img{height:62px;display:block;margin:0 auto 10px}
    h1{font-size:22px;margin:0 0 6px}
    h2{font-size:16px;background:#eff6ff;padding:10px 12px;border-left:5px solid #2563eb;border-radius:8px;margin:24px 0 12px}
    .grid{display:grid;grid-template-columns:1fr 1fr;gap:14px}
    .card{border:1px solid #e5e7eb;border-radius:10px;padding:12px;background:#fafafa}
    table{width:100%;border-collapse:collapse;margin-top:8px}
    th,td{border:1px solid #d1d5db;padding:8px;vertical-align:top;font-size:13px}
    th{background:#eff6ff}
    .text{white-space:pre-wrap;line-height:1.6}
    .actions{max-width:960px;margin:14px auto;display:flex;gap:10px;justify-content:flex-end}
    .btn{border:none;background:#1d4ed8;color:white;padding:10px 14px;border-radius:10px;cursor:pointer;text-decoration:none;font-weight:700}
    .btn.secondary{background:#0f172a}
    @media print{
        body{background:#fff}
        .actions{display:none}
        .page{box-shadow:none;margin:0;max-width:none;padding:0}
    }
</style>
</head>
<body>
<div class="actions">
    <a href="javascript:window.print()" class="btn">Print / Save PDF</a>
    <a href="../../index.php?module=rdk&view_id=<?= (int)$data['id'] ?>" class="btn secondary">Kembali</a>
</div>
<div class="page">
    <div class="head">
        <img src="https://balimedhospital.co.id/wp-content/uploads/elementor/thumbs/logo-dark-o9cm6tnx14hcrnest1hge1pwnqj0yaumij7qohadlm.png" alt="BaliMed">
        <h1>RDK / REFLEKSI DISKUSI KASUS KEPERAWATAN</h1>
        <div>RS BaliMed Denpasar</div>
    </div>

    <h2>I. Identitas Kasus (Anonim)</h2>
    <div class="grid">
        <div class="card text"><strong>Inisial Pasien:</strong> <?= e($data['patient_initial']) ?>
<strong>No. RM (3 angka terakhir):</strong> <?= e($data['rm_last3'] ?: '-') ?>
<strong>Diagnosis Medis:</strong> <?= e($data['diagnosis']) ?></div>
        <div class="card text"><strong>Tanggal Kejadian:</strong> <?= e(dindo($data['incident_date'])) ?>
<strong>Tanggal RDK:</strong> <?= e(dindo($data['meeting_date'])) ?>
<strong>Unit/Ruangan:</strong> <?= e($data['unit_name']) ?>
<strong>Penyaji:</strong> <?= e($data['presenter_name']) ?></div>
    </div>

    <h2>II. Resume Klinis (Kronologi)</h2>
    <div class="card text"><?= e($data['clinical_resume']) ?></div>
    <div class="grid">
        <div class="card text"><strong>Kondisi awal</strong>
<?= e($data['initial_assessment']) ?></div>
        <div class="card text"><strong>Tindakan keperawatan</strong>
<?= e($data['nursing_actions']) ?></div>
    </div>
    <div class="card text" style="margin-top:14px"><strong>Respon pasien</strong>
<?= e($data['patient_response']) ?></div>

    <h2>III. Masalah yang Difokuskan (Gap Analysis)</h2>
    <div class="card text"><strong>Fokus masalah</strong>
<?= e($data['focused_problem']) ?></div>
    <div class="grid" style="margin-top:14px">
        <div class="card text"><strong>Aspek Klinis</strong>
<?= e($data['aspect_clinical']) ?></div>
        <div class="card text"><strong>Aspek Komunikasi</strong>
<?= e($data['aspect_communication']) ?></div>
        <div class="card text"><strong>Aspek Prosedur</strong>
<?= e($data['aspect_procedure']) ?></div>
        <div class="card text"><strong>Aspek Emosional</strong>
<?= e($data['aspect_emotional']) ?></div>
    </div>

    <h2>IV. Dasar Pemikiran (Referensi / SOP)</h2>
    <div class="grid">
        <div class="card text"><strong>SOP / Standar</strong>
<?= e($data['sop_reference']) ?></div>
        <div class="card text"><strong>Instruksi Dokter</strong>
<?= e($data['doctor_instruction']) ?></div>
    </div>
    <div class="card text" style="margin-top:14px"><strong>Literatur / Guideline</strong>
<?= e($data['literature_reference']) ?></div>

    <h2>V. Analisis Diri (Self-Reflection)</h2>
    <div class="grid">
        <div class="card text"><strong>Apa yang sudah berjalan dengan baik?</strong>
<?= e($data['good_points']) ?></div>
        <div class="card text"><strong>Apa yang paling sulit dilakukan?</strong>
<?= e($data['difficult_points']) ?></div>
    </div>
    <div class="card text" style="margin-top:14px"><strong>Jika kejadian yang sama terulang, apa yang ingin diubah?</strong>
<?= e($data['improvement_plan']) ?></div>
    <div class="card text" style="margin-top:14px"><strong>Visual pendukung</strong>
<?= e($data['visual_support']) ?></div>

    <h2>VI. Tim yang Ikut dalam RDK</h2>
    <table>
        <thead><tr><th>No</th><th>Nama</th><th>Peran/Jabatan</th><th>Unit</th><th>Status</th><th>Catatan</th></tr></thead>
        <tbody>
        <?php foreach ($participants as $i => $p): ?>
            <tr>
                <td><?= $i + 1 ?></td>
                <td><?= e($p['participant_name']) ?></td>
                <td><?= e($p['participant_role']) ?></td>
                <td><?= e($p['participant_unit']) ?></td>
                <td><?= e($p['attendance_status']) ?></td>
                <td><?= e($p['notes']) ?></td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>

    <h2>VII. Masukan / Pertanyaan Kepala Unit dan Forum</h2>
    <table>
        <thead><tr><th>No</th><th>Nama</th><th>Unit</th><th>Masukan / Pertanyaan</th><th>Jawaban / Tindak Lanjut</th></tr></thead>
        <tbody>
        <?php foreach ($feedbacks as $i => $f): ?>
            <tr>
                <td><?= $i + 1 ?></td>
                <td><?= e($f['giver_name']) ?></td>
                <td><?= e($f['giver_unit']) ?></td>
                <td class="text"><?= e($f['question_or_input']) ?></td>
                <td class="text"><?= e($f['followup_or_answer']) ?></td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>

    <h2>VIII. Kesimpulan, Notulen, dan Usulan Rancangan Perbaikan</h2>
    <div class="card text"><strong>Ringkasan Diskusi</strong>
<?= e($data['discussion_notes']) ?></div>
    <div class="card text" style="margin-top:14px"><strong>Kesimpulan</strong>
<?= e($data['conclusion_text']) ?></div>
    <div class="card text" style="margin-top:14px"><strong>Notulen</strong>
<?= e($data['minutes_text']) ?></div>
    <div class="card text" style="margin-top:14px"><strong>Usulan Rancangan Perbaikan ke Direktur</strong>
<?= e($data['director_proposal']) ?></div>
</div>
<script>window.addEventListener('load',()=>{});</script>
</body>
</html>
