<?php
// modules/rdk/index.php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/../../config/database.php';

$conn = getConnection();
$currentUser = $_SESSION['user'] ?? [];
$currentEmployeeId = (int)($currentUser['employee_id'] ?? $currentUser['id'] ?? $currentUser['user_id'] ?? 0);
$currentRole = strtolower((string)($currentUser['role'] ?? $_SESSION['user_role'] ?? 'viewer'));

if (!function_exists('e')) {
    function e($value): string {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}
if (!function_exists('rdk_text')) {
    function rdk_text(?string $value): string {
        return trim((string)$value);
    }
}
if (!function_exists('rdk_date_id')) {
    function rdk_date_id($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);
    }
}
if (!function_exists('rdk_fetch_units')) {
    function rdk_fetch_units(mysqli $conn): array {
        $data = [];
        $sql = "SELECT id, name FROM units WHERE is_active = 1 ORDER BY name ASC";
        if ($res = $conn->query($sql)) {
            while ($row = $res->fetch_assoc()) {
                $data[] = $row;
            }
            $res->close();
        }
        return $data;
    }
}
if (!function_exists('rdk_fetch_employees')) {
    function rdk_fetch_employees(mysqli $conn): array {
        $data = [];

        $candidateQueries = [
            "SELECT e.id,
                    COALESCE(e.full_name, '-') AS full_name,
                    COALESCE(u.name, '-') AS unit_name,
                    COALESCE(e.position_name, '') AS position_name
             FROM employees e
             LEFT JOIN units u ON u.id = e.unit_id
             WHERE COALESCE(e.employment_status, 'aktif') = 'aktif'
             ORDER BY COALESCE(e.full_name, '') ASC",

            "SELECT e.id,
                    COALESCE(e.nama, '-') AS full_name,
                    COALESCE(u.name, '-') AS unit_name,
                    COALESCE(e.jabatan, '') AS position_name
             FROM employees e
             LEFT JOIN units u ON u.id = e.unit_id
             WHERE COALESCE(e.employment_status, 'aktif') = 'aktif'
             ORDER BY COALESCE(e.nama, '') ASC",

            "SELECT e.id,
                    COALESCE(e.full_name, e.nama, '-') AS full_name,
                    '-' AS unit_name,
                    COALESCE(e.position_name, e.jabatan, '') AS position_name
             FROM employees e
             ORDER BY e.id DESC"
        ];

        foreach ($candidateQueries as $sql) {
            try {
                if ($res = $conn->query($sql)) {
                    while ($row = $res->fetch_assoc()) {
                        $data[] = $row;
                    }
                    $res->close();
                    if ($data) {
                        return $data;
                    }
                }
            } catch (Throwable $e) {
                $data = [];
            }
        }

        return $data;
    }
}
if (!function_exists('rdk_can_edit')) {
    function rdk_can_edit(string $role): bool {
        return in_array($role, ['superadmin', 'admin', 'editor', 'kepala_unit', 'kasubdiv', 'kadiv'], true);
    }
}

if (!function_exists('rdk_table_columns')) {
    function rdk_table_columns(mysqli $conn, string $table): array
    {
        $cols = [];
        $table = trim($table);
        if ($table === '') return $cols;

        $sql = "SHOW COLUMNS FROM `" . $conn->real_escape_string($table) . "`";
        if ($res = $conn->query($sql)) {
            while ($row = $res->fetch_assoc()) {
                $cols[] = $row['Field'] ?? '';
            }
            $res->close();
        }
        return $cols;
    }
}

if (!function_exists('rdk_pick_column')) {
    function rdk_pick_column(array $available, array $candidates, string $fallback = ''): string
    {
        foreach ($candidates as $col) {
            if (in_array($col, $available, true)) {
                return $col;
            }
        }
        return $fallback;
    }
}


if (!function_exists('rdk_case_detail')) {
    function rdk_case_detail(mysqli $conn, int $id): ?array
    {
        $employeeCols = rdk_table_columns($conn, 'employees');
        $unitCols = rdk_table_columns($conn, 'units');

        $empNameCol = rdk_pick_column($employeeCols, [
            'full_name',
            'nama_lengkap',
            'name',
            'employee_name',
            'nama'
        ], '');

        $unitNameCol = rdk_pick_column($unitCols, [
            'name',
            'unit_name',
            'nama_unit'
        ], 'name');

        $presenterNameExpr = $empNameCol !== ''
            ? "COALESCE(NULLIF(ec.`{$empNameCol}`, ''), CONCAT('Staff #', ec.id))"
            : "CONCAT('Staff #', ec.id)";

        $createdByNameExpr = $empNameCol !== ''
            ? "COALESCE(NULLIF(ecreate.`{$empNameCol}`, ''), CONCAT('Staff #', ecreate.id))"
            : "CONCAT('Staff #', ecreate.id)";

        $updatedByNameExpr = $empNameCol !== ''
            ? "COALESCE(NULLIF(eupdate.`{$empNameCol}`, ''), CONCAT('Staff #', eupdate.id))"
            : "CONCAT('Staff #', eupdate.id)";

        $sql = "
            SELECT
                rc.*,
                COALESCE(u.`{$unitNameCol}`, '-') AS unit_name,
                {$presenterNameExpr} AS presenter_name,
                {$createdByNameExpr} AS created_by_name,
                {$updatedByNameExpr} AS updated_by_name
            FROM rdk_cases rc
            LEFT JOIN units u ON u.id = rc.unit_id
            LEFT JOIN employees ec ON ec.id = rc.presenter_employee_id
            LEFT JOIN employees ecreate ON ecreate.id = rc.created_by
            LEFT JOIN employees eupdate ON eupdate.id = rc.updated_by
            WHERE rc.id = ?
            LIMIT 1
        ";

        $stmt = $conn->prepare($sql);
        if (!$stmt) {
            return null;
        }

        $stmt->bind_param('i', $id);
        $stmt->execute();
        $res = $stmt->get_result();
        $row = $res ? $res->fetch_assoc() : null;
        $stmt->close();

        if (!$row) {
            return null;
        }

        $row['participants'] = [];
        $row['feedbacks'] = [];

        $stmtP = $conn->prepare("
            SELECT id, participant_name, participant_role, participant_unit, attendance_status, notes
            FROM rdk_case_participants
            WHERE rdk_case_id = ?
            ORDER BY id ASC
        ");
        if ($stmtP) {
            $stmtP->bind_param('i', $id);
            $stmtP->execute();
            $resP = $stmtP->get_result();
            while ($resP && ($p = $resP->fetch_assoc())) {
                $row['participants'][] = $p;
            }
            $stmtP->close();
        }

        $stmtF = $conn->prepare("
            SELECT id, giver_name, giver_unit, question_or_input, followup_or_answer
            FROM rdk_case_feedbacks
            WHERE rdk_case_id = ?
            ORDER BY id ASC
        ");
        if ($stmtF) {
            $stmtF->bind_param('i', $id);
            $stmtF->execute();
            $resF = $stmtF->get_result();
            while ($resF && ($f = $resF->fetch_assoc())) {
                $row['feedbacks'][] = $f;
            }
            $stmtF->close();
        }

        return $row;
    }
}

$success = '';
$error = '';
$action = (string)($_POST['action'] ?? $_GET['action'] ?? '');
$viewId = (int)($_GET['view_id'] ?? 0);
$editId = (int)($_GET['edit_id'] ?? 0);
$deleteId = (int)($_GET['delete_id'] ?? 0);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'save' && rdk_can_edit($currentRole)) {
    mysqli_begin_transaction($conn);
    try {
        $id = (int)($_POST['id'] ?? 0);
        $meeting_date = rdk_text($_POST['meeting_date'] ?? date('Y-m-d'));
        $incident_date = rdk_text($_POST['incident_date'] ?? '');
        $patient_initial = strtoupper(rdk_text($_POST['patient_initial'] ?? ''));
        $rm_last3 = substr(preg_replace('/\D+/', '', (string)($_POST['rm_last3'] ?? '')), -3);
        $diagnosis = rdk_text($_POST['diagnosis'] ?? '');
        $unit_id = (int)($_POST['unit_id'] ?? 0);
        $presenter_employee_id = (int)($_POST['presenter_employee_id'] ?? 0);
        $status = in_array((string)($_POST['status'] ?? 'draft'), ['draft', 'final'], true) ? (string)$_POST['status'] : 'draft';

        $clinical_resume = rdk_text($_POST['clinical_resume'] ?? '');
        $initial_assessment = rdk_text($_POST['initial_assessment'] ?? '');
        $nursing_actions = rdk_text($_POST['nursing_actions'] ?? '');
        $patient_response = rdk_text($_POST['patient_response'] ?? '');

        $focused_problem = rdk_text($_POST['focused_problem'] ?? '');
        $aspect_clinical = rdk_text($_POST['aspect_clinical'] ?? '');
        $aspect_communication = rdk_text($_POST['aspect_communication'] ?? '');
        $aspect_procedure = rdk_text($_POST['aspect_procedure'] ?? '');
        $aspect_emotional = rdk_text($_POST['aspect_emotional'] ?? '');

        $sop_reference = rdk_text($_POST['sop_reference'] ?? '');
        $doctor_instruction = rdk_text($_POST['doctor_instruction'] ?? '');
        $literature_reference = rdk_text($_POST['literature_reference'] ?? '');

        $good_points = rdk_text($_POST['good_points'] ?? '');
        $difficult_points = rdk_text($_POST['difficult_points'] ?? '');
        $improvement_plan = rdk_text($_POST['improvement_plan'] ?? '');
        $visual_support = rdk_text($_POST['visual_support'] ?? '');

        $discussion_notes = rdk_text($_POST['discussion_notes'] ?? '');
        $conclusion_text = rdk_text($_POST['conclusion_text'] ?? '');
        $minutes_text = rdk_text($_POST['minutes_text'] ?? '');
        $director_proposal = rdk_text($_POST['director_proposal'] ?? '');

        if ($patient_initial === '' || $meeting_date === '' || $diagnosis === '' || $unit_id <= 0) {
            throw new RuntimeException('Mohon lengkapi minimal: tanggal RDK, inisial pasien, diagnosis, dan unit/ruangan.');
        }

        if ($id > 0) {
            $sql = "UPDATE rdk_cases SET
                        meeting_date=?, incident_date=?, patient_initial=?, rm_last3=?, diagnosis=?, unit_id=?, presenter_employee_id=?,
                        clinical_resume=?, initial_assessment=?, nursing_actions=?, patient_response=?,
                        focused_problem=?, aspect_clinical=?, aspect_communication=?, aspect_procedure=?, aspect_emotional=?,
                        sop_reference=?, doctor_instruction=?, literature_reference=?,
                        good_points=?, difficult_points=?, improvement_plan=?, visual_support=?,
                        discussion_notes=?, conclusion_text=?, minutes_text=?, director_proposal=?, status=?, updated_by=?, updated_at=NOW()
                    WHERE id=?";
            $stmt = $conn->prepare($sql);
            if (!$stmt) throw new RuntimeException('Gagal menyiapkan query update RDK.');
            $updatedBy = $currentEmployeeId;
            $stmt->bind_param(
                'sssssii' . str_repeat('s', 21) . 'ii',
                $meeting_date, $incident_date, $patient_initial, $rm_last3, $diagnosis, $unit_id, $presenter_employee_id,
                $clinical_resume, $initial_assessment, $nursing_actions, $patient_response,
                $focused_problem, $aspect_clinical, $aspect_communication, $aspect_procedure, $aspect_emotional,
                $sop_reference, $doctor_instruction, $literature_reference,
                $good_points, $difficult_points, $improvement_plan, $visual_support,
                $discussion_notes, $conclusion_text, $minutes_text, $director_proposal, $status, $updatedBy, $id
            );
            if (!$stmt->execute()) {
                throw new RuntimeException('Gagal update data RDK: ' . $stmt->error);
            }
            $stmt->close();
            $rdkId = $id;
            if (function_exists('logActivity')) logActivity('update', 'rdk', $rdkId, 'Memperbarui data RDK');
        } else {
            $sql = "INSERT INTO rdk_cases (
                        meeting_date, incident_date, patient_initial, rm_last3, diagnosis, unit_id, presenter_employee_id,
                        clinical_resume, initial_assessment, nursing_actions, patient_response,
                        focused_problem, aspect_clinical, aspect_communication, aspect_procedure, aspect_emotional,
                        sop_reference, doctor_instruction, literature_reference,
                        good_points, difficult_points, improvement_plan, visual_support,
                        discussion_notes, conclusion_text, minutes_text, director_proposal,
                        status, created_by, updated_by, created_at, updated_at
                    ) VALUES (
                        ?, ?, ?, ?, ?, ?, ?,
                        ?, ?, ?, ?,
                        ?, ?, ?, ?, ?,
                        ?, ?, ?,
                        ?, ?, ?, ?,
                        ?, ?, ?, ?,
                        ?, ?, ?, NOW(), NOW()
                    )";
            $stmt = $conn->prepare($sql);
            if (!$stmt) throw new RuntimeException('Gagal menyiapkan query simpan RDK.');
            $createdBy = $currentEmployeeId;
            $updatedBy = $currentEmployeeId;
            $stmt->bind_param(
                'sssssii' . str_repeat('s', 21) . 'ii',
                $meeting_date, $incident_date, $patient_initial, $rm_last3, $diagnosis, $unit_id, $presenter_employee_id,
                $clinical_resume, $initial_assessment, $nursing_actions, $patient_response,
                $focused_problem, $aspect_clinical, $aspect_communication, $aspect_procedure, $aspect_emotional,
                $sop_reference, $doctor_instruction, $literature_reference,
                $good_points, $difficult_points, $improvement_plan, $visual_support,
                $discussion_notes, $conclusion_text, $minutes_text, $director_proposal,
                $status, $createdBy, $updatedBy
            );
            if (!$stmt->execute()) {
                throw new RuntimeException('Gagal simpan data RDK: ' . $stmt->error);
            }
            $rdkId = (int)$conn->insert_id;
            $stmt->close();
            if (function_exists('logActivity')) logActivity('create', 'rdk', $rdkId, 'Menambahkan data RDK');
        }

        if (!$conn->query("DELETE FROM rdk_case_participants WHERE rdk_case_id = " . (int)$rdkId)) {
            throw new RuntimeException('Gagal membersihkan daftar peserta.');
        }
        if (!$conn->query("DELETE FROM rdk_case_feedbacks WHERE rdk_case_id = " . (int)$rdkId)) {
            throw new RuntimeException('Gagal membersihkan daftar masukan diskusi.');
        }

        $participant_names = $_POST['participant_name'] ?? [];
        $participant_roles = $_POST['participant_role'] ?? [];
        $participant_units = $_POST['participant_unit'] ?? [];
        $participant_notes = $_POST['participant_notes'] ?? [];
        $participant_attendance = $_POST['participant_attendance'] ?? [];

        $stmtP = $conn->prepare("INSERT INTO rdk_case_participants (rdk_case_id, participant_name, participant_role, participant_unit, attendance_status, notes) VALUES (?, ?, ?, ?, ?, ?)");
        if (!$stmtP) throw new RuntimeException('Gagal menyiapkan simpan peserta.');
        for ($i = 0; $i < count($participant_names); $i++) {
            $pname = rdk_text($participant_names[$i] ?? '');
            $prole = rdk_text($participant_roles[$i] ?? '');
            $punit = rdk_text($participant_units[$i] ?? '');
            $pnote = rdk_text($participant_notes[$i] ?? '');
            $patt  = rdk_text($participant_attendance[$i] ?? 'hadir');
            if ($pname === '') continue;
            $stmtP->bind_param('isssss', $rdkId, $pname, $prole, $punit, $patt, $pnote);
            $stmtP->execute();
        }
        $stmtP->close();

        $feedback_names = $_POST['feedback_name'] ?? [];
        $feedback_units = $_POST['feedback_unit'] ?? [];
        $feedback_questions = $_POST['feedback_question'] ?? [];
        $feedback_followups = $_POST['feedback_followup'] ?? [];

        $stmtF = $conn->prepare("INSERT INTO rdk_case_feedbacks (rdk_case_id, giver_name, giver_unit, question_or_input, followup_or_answer) VALUES (?, ?, ?, ?, ?)");
        if (!$stmtF) throw new RuntimeException('Gagal menyiapkan simpan masukan diskusi.');
        for ($i = 0; $i < count($feedback_names); $i++) {
            $fname = rdk_text($feedback_names[$i] ?? '');
            $funit = rdk_text($feedback_units[$i] ?? '');
            $fquestion = rdk_text($feedback_questions[$i] ?? '');
            $ffollow = rdk_text($feedback_followups[$i] ?? '');
            if ($fname === '' && $fquestion === '') continue;
            $stmtF->bind_param('issss', $rdkId, $fname, $funit, $fquestion, $ffollow);
            $stmtF->execute();
        }
        $stmtF->close();

        mysqli_commit($conn);
        $success = 'Data RDK berhasil disimpan.';
        $viewId = $rdkId;
        $editId = 0;
    } catch (Throwable $e) {
        mysqli_rollback($conn);
        $error = $e->getMessage();
    }
}

if ($deleteId > 0 && rdk_can_edit($currentRole)) {
    mysqli_begin_transaction($conn);
    try {
        $conn->query("DELETE FROM rdk_case_participants WHERE rdk_case_id = " . (int)$deleteId);
        $conn->query("DELETE FROM rdk_case_feedbacks WHERE rdk_case_id = " . (int)$deleteId);
        $stmt = $conn->prepare("DELETE FROM rdk_cases WHERE id = ? LIMIT 1");
        if (!$stmt) throw new RuntimeException('Gagal menyiapkan hapus RDK.');
        $stmt->bind_param('i', $deleteId);
        $stmt->execute();
        $stmt->close();
        mysqli_commit($conn);
        if (function_exists('logActivity')) logActivity('delete', 'rdk', $deleteId, 'Menghapus data RDK');
        $success = 'Data RDK berhasil dihapus.';
    } catch (Throwable $e) {
        mysqli_rollback($conn);
        $error = $e->getMessage();
    }
}

$units = rdk_fetch_units($conn);
$employees = rdk_fetch_employees($conn);
$formData = null;
if ($editId > 0) {
    $formData = rdk_case_detail($conn, $editId);
}
if (!$formData) {
    $formData = [
        'id' => 0,
        'meeting_date' => date('Y-m-d'),
        'incident_date' => '',
        'patient_initial' => '',
        'rm_last3' => '',
        'diagnosis' => '',
        'unit_id' => 0,
        'presenter_employee_id' => $currentEmployeeId,
        'clinical_resume' => '',
        'initial_assessment' => '',
        'nursing_actions' => '',
        'patient_response' => '',
        'focused_problem' => '',
        'aspect_clinical' => '',
        'aspect_communication' => '',
        'aspect_procedure' => '',
        'aspect_emotional' => '',
        'sop_reference' => '',
        'doctor_instruction' => '',
        'literature_reference' => '',
        'good_points' => '',
        'difficult_points' => '',
        'improvement_plan' => '',
        'visual_support' => '',
        'discussion_notes' => '',
        'conclusion_text' => '',
        'minutes_text' => '',
        'director_proposal' => '',
        'status' => 'draft',
        'participants' => [[
            'participant_name' => (string)($currentUser['full_name'] ?? $currentUser['nama'] ?? ''),
            'participant_role' => (string)($currentUser['position_name'] ?? $currentUser['jabatan'] ?? 'Penyaji'),
            'participant_unit' => (string)($currentUser['unit_name'] ?? $currentUser['unit'] ?? ''),
            'attendance_status' => 'hadir',
            'notes' => 'Penyaji'
        ]],
        'feedbacks' => [[
            'giver_name' => '',
            'giver_unit' => '',
            'question_or_input' => '',
            'followup_or_answer' => ''
        ]],
    ];
}

$keyword = trim((string)($_GET['q'] ?? ''));
$statusFilter = trim((string)($_GET['status'] ?? ''));
$unitFilter = (int)($_GET['unit_filter'] ?? 0);
$where = ['1=1'];
if ($keyword !== '') {
    $kw = $conn->real_escape_string($keyword);
    $where[] = "(r.patient_initial LIKE '%{$kw}%' OR r.diagnosis LIKE '%{$kw}%' OR r.focused_problem LIKE '%{$kw}%')";
}
if ($statusFilter !== '' && in_array($statusFilter, ['draft', 'final'], true)) {
    $where[] = "r.status = '" . $conn->real_escape_string($statusFilter) . "'";
}
if ($unitFilter > 0) {
    $where[] = 'r.unit_id = ' . $unitFilter;
}
$sqlList = "SELECT r.id, r.meeting_date, r.patient_initial, r.rm_last3, r.diagnosis, r.status, r.created_at,
                   COALESCE(u.name,'-') AS unit_name,
                   (SELECT COUNT(*) FROM rdk_case_participants p WHERE p.rdk_case_id = r.id) AS total_participants,
                   (SELECT COUNT(*) FROM rdk_case_feedbacks f WHERE f.rdk_case_id = r.id) AS total_feedbacks
            FROM rdk_cases r
            LEFT JOIN units u ON u.id = r.unit_id
            WHERE " . implode(' AND ', $where) . "
            ORDER BY r.meeting_date DESC, r.id DESC";
$listRows = [];
if ($resList = $conn->query($sqlList)) {
    while ($row = $resList->fetch_assoc()) $listRows[] = $row;
    $resList->close();
}

$detailData = $viewId > 0 ? rdk_case_detail($conn, $viewId) : null;
?>


<style>
.rdk-shell{--rdk-ring:rgba(14,165,233,.18);--rdk-border:#dbe7f3;}
.rdk-shell .premium-panel{background:linear-gradient(180deg,#ffffff 0%,#f8fbff 100%);border:1px solid #e6eef8;box-shadow:0 18px 40px rgba(15,23,42,.06);}
.rdk-shell .premium-header{background:linear-gradient(180deg,#ffffff 0%,#f8fafc 100%);border-bottom:1px solid #e6eef8;}
.rdk-shell .glass-strip{background:linear-gradient(135deg,rgba(255,255,255,.2),rgba(255,255,255,.08));backdrop-filter:blur(10px);}
.rdk-shell input[type=text],.rdk-shell input[type=date],.rdk-shell select,.rdk-shell textarea{width:100%;border:1px solid var(--rdk-border);background:#fff;color:#0f172a;border-radius:18px;padding:.9rem 1rem;outline:none;transition:all .2s ease;box-shadow:inset 0 1px 2px rgba(15,23,42,.02);}
.rdk-shell input[type=text],.rdk-shell input[type=date],.rdk-shell select{min-height:54px;}
.rdk-shell textarea{min-height:130px;resize:vertical;line-height:1.6;}
.rdk-shell .compact-textarea{min-height:110px;}
.rdk-shell input:focus,.rdk-shell select:focus,.rdk-shell textarea:focus{border-color:#38bdf8;box-shadow:0 0 0 4px var(--rdk-ring);background:#fff;}
.rdk-shell label{margin-bottom:.45rem;}
.rdk-shell .section-card{position:relative;overflow:hidden;border-radius:28px;padding:1.25rem;border:1px solid #e6eef8;box-shadow:0 12px 30px rgba(15,23,42,.04);}
.rdk-shell .section-card:before{content:'';position:absolute;left:0;top:0;bottom:0;width:6px;border-radius:999px;}
.rdk-shell .section-card-blue{background:linear-gradient(180deg,#f4fbff 0%,#eef7ff 100%);}
.rdk-shell .section-card-blue:before{background:linear-gradient(180deg,#38bdf8,#2563eb);}
.rdk-shell .section-card-amber{background:linear-gradient(180deg,#fffaf0 0%,#fff7e7 100%);}
.rdk-shell .section-card-amber:before{background:linear-gradient(180deg,#f59e0b,#ea580c);}
.rdk-shell .section-card-emerald{background:linear-gradient(180deg,#f2fffa 0%,#ebfff6 100%);}
.rdk-shell .section-card-emerald:before{background:linear-gradient(180deg,#10b981,#059669);}
.rdk-shell .section-card-violet{background:linear-gradient(180deg,#f7f5ff 0%,#f3efff 100%);}
.rdk-shell .section-card-violet:before{background:linear-gradient(180deg,#8b5cf6,#6366f1);}
.rdk-shell .section-head{display:flex;align-items:flex-start;justify-content:space-between;gap:1rem;margin-bottom:1rem;padding-left:.5rem;}
.rdk-shell .section-kicker{display:inline-flex;align-items:center;gap:.45rem;padding:.4rem .8rem;border-radius:999px;background:rgba(255,255,255,.7);font-size:.75rem;font-weight:700;letter-spacing:.03em;text-transform:uppercase;color:#334155;border:1px solid rgba(148,163,184,.18);}
.rdk-shell .section-title{font-size:1.05rem;font-weight:800;color:#0f172a;margin-top:.55rem;}
.rdk-shell .section-help{font-size:.86rem;color:#64748b;margin-top:.25rem;}
.rdk-shell .mini-panel{border:1px solid #e6eef8;border-radius:22px;padding:1rem;background:rgba(255,255,255,.72);box-shadow:inset 0 1px 0 rgba(255,255,255,.9);}
.rdk-shell .tab-nav{display:flex;gap:.75rem;overflow:auto;padding:.25rem;}
.rdk-shell .tab-btn{border:1px solid #dbe7f3;background:#fff;color:#475569;padding:.8rem 1rem;border-radius:18px;font-weight:700;white-space:nowrap;transition:.2s;box-shadow:0 8px 18px rgba(15,23,42,.04);}
.rdk-shell .tab-btn.active{background:linear-gradient(135deg,#0ea5e9,#4f46e5);color:#fff;border-color:transparent;box-shadow:0 12px 28px rgba(79,70,229,.24);}
.rdk-shell [data-rdk-tab-pane]{display:none;}
.rdk-shell [data-rdk-tab-pane].active{display:block;animation:rdkFade .2s ease;}
@keyframes rdkFade{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:translateY(0)}}
.rdk-shell .action-btn{display:inline-flex;align-items:center;gap:.55rem;padding:.85rem 1.1rem;border-radius:18px;font-weight:700;transition:.2s;}
.rdk-shell .history-card{border:1px solid #e6eef8;border-radius:22px;padding:1rem;background:linear-gradient(180deg,#fff 0%,#fbfdff 100%);box-shadow:0 10px 24px rgba(15,23,42,.04);}
.rdk-shell .history-card:hover{transform:translateY(-2px);box-shadow:0 18px 30px rgba(15,23,42,.08);}
.rdk-shell .history-actions a{border-radius:14px;padding:.6rem .85rem;font-weight:700;}
@media (max-width:768px){.rdk-shell .tab-btn{padding:.7rem .9rem;font-size:.85rem}.rdk-shell .section-card{padding:1rem}.rdk-shell .mini-panel{padding:.85rem}}
</style>

<div class="rdk-shell space-y-6 p-1">
    <div class="bg-gradient-to-r from-cyan-500 via-sky-500 to-indigo-600 rounded-3xl shadow-xl text-white p-6 md:p-8">
        <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-5">
            <div>
                <div class="inline-flex items-center gap-2 bg-white/15 rounded-full px-4 py-2 text-sm font-medium mb-3">
                    <i class="fas fa-user-doctor"></i>
                    <span>Modul RDK / Refleksi Diskusi Kasus Keperawatan</span>
                </div>
                <h1 class="text-2xl md:text-3xl font-extrabold tracking-tight">Forum refleksi klinis yang rapi, anonim, dan siap cetak</h1>
                <p class="text-cyan-50 mt-2 max-w-3xl">Isi identitas kasus anonim, kronologi, gap analysis, refleksi diri, masukan kepala unit, notulen, hingga usulan rancangan perbaikan ke direktur dalam satu modul terintegrasi.</p>
            </div>
            <div class="grid grid-cols-2 gap-3 min-w-[240px]">
                <div class="bg-white/15 rounded-2xl p-4">
                    <div class="text-xs uppercase opacity-80">Total RDK</div>
                    <div class="text-2xl font-bold"><?= count($listRows) ?></div>
                </div>
                <div class="bg-white/15 rounded-2xl p-4">
                    <div class="text-xs uppercase opacity-80">Draft</div>
                    <div class="text-2xl font-bold"><?= count(array_filter($listRows, fn($x) => $x['status'] === 'draft')) ?></div>
                </div>
            </div>
        </div>
    </div>

    <?php if ($success): ?>
        <div class="bg-emerald-50 border border-emerald-200 text-emerald-700 rounded-2xl px-4 py-3"><?= e($success) ?></div>
    <?php endif; ?>
    <?php if ($error): ?>
        <div class="bg-rose-50 border border-rose-200 text-rose-700 rounded-2xl px-4 py-3"><?= e($error) ?></div>
    <?php endif; ?>

    <div class="grid grid-cols-1 xl:grid-cols-3 gap-6">
        <div class="xl:col-span-2 premium-panel rounded-[30px] overflow-hidden">
            <div class="px-6 py-5 premium-header flex items-center justify-between gap-3 flex-wrap">
                <div>
                    <h2 class="text-lg font-bold text-slate-800">Form Input RDK</h2>
                    <p class="text-sm text-slate-500">Lengkapi kerangka presentasi, diskusi, dan tindak lanjut perbaikan.</p>
                </div>
                <?php if (rdk_can_edit($currentRole)): ?>
                    <a href="index.php?module=rdk" class="inline-flex items-center gap-2 px-4 py-2 rounded-xl bg-slate-900 text-white text-sm font-semibold hover:bg-slate-800">
                        <i class="fas fa-plus"></i> RDK Baru
                    </a>
                <?php endif; ?>
            </div>

            <form method="post" class="p-6 md:p-7 space-y-6">
                <div class="tab-nav">
                    <button type="button" class="tab-btn active" data-rdk-tab="identitas">I. Identitas</button>
                    <button type="button" class="tab-btn" data-rdk-tab="resume">II. Resume Klinis</button>
                    <button type="button" class="tab-btn" data-rdk-tab="gap">III. Gap Analysis</button>
                    <button type="button" class="tab-btn" data-rdk-tab="referensi">IV. Referensi</button>
                    <button type="button" class="tab-btn" data-rdk-tab="refleksi">V. Refleksi & Forum</button>
                </div>
                <input type="hidden" name="action" value="save">
                <input type="hidden" name="id" value="<?= (int)$formData['id'] ?>">

                <div data-rdk-tab-pane="identitas" class="active">
                <div class="mini-panel">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                    <div>
                        <label class="block text-sm font-semibold text-slate-700 mb-1">Tanggal RDK</label>
                        <input type="date" name="meeting_date" value="<?= e($formData['meeting_date']) ?>" class="w-full rounded-2xl border-slate-300 focus:border-sky-500 focus:ring-sky-500">
                    </div>
                    <div>
                        <label class="block text-sm font-semibold text-slate-700 mb-1">Tanggal Kejadian Kasus</label>
                        <input type="date" name="incident_date" value="<?= e($formData['incident_date']) ?>" class="w-full rounded-2xl border-slate-300 focus:border-sky-500 focus:ring-sky-500">
                    </div>
                    <div>
                        <label class="block text-sm font-semibold text-slate-700 mb-1">Inisial Pasien</label>
                        <input type="text" name="patient_initial" value="<?= e($formData['patient_initial']) ?>" placeholder="Contoh: Ny. A / Tn. B" class="w-full rounded-2xl border-slate-300 focus:border-sky-500 focus:ring-sky-500">
                    </div>
                    <div>
                        <label class="block text-sm font-semibold text-slate-700 mb-1">No. RM (3 angka terakhir)</label>
                        <input type="text" maxlength="3" name="rm_last3" value="<?= e($formData['rm_last3']) ?>" placeholder="123" class="w-full rounded-2xl border-slate-300 focus:border-sky-500 focus:ring-sky-500">
                    </div>
                    <div class="md:col-span-2">
                        <label class="block text-sm font-semibold text-slate-700 mb-1">Diagnosis Medis</label>
                        <input type="text" name="diagnosis" value="<?= e($formData['diagnosis']) ?>" class="w-full rounded-2xl border-slate-300 focus:border-sky-500 focus:ring-sky-500">
                    </div>
                    <div>
                        <label class="block text-sm font-semibold text-slate-700 mb-1">Unit / Ruangan</label>
                        <select name="unit_id" class="w-full rounded-2xl border-slate-300 focus:border-sky-500 focus:ring-sky-500">
                            <option value="">Pilih unit</option>
                            <?php foreach ($units as $unit): ?>
                                <option value="<?= (int)$unit['id'] ?>" <?= (int)$formData['unit_id'] === (int)$unit['id'] ? 'selected' : '' ?>><?= e($unit['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-semibold text-slate-700 mb-1">Penyaji / PIC Kasus</label>
                        <select name="presenter_employee_id" class="w-full rounded-2xl border-slate-300 focus:border-sky-500 focus:ring-sky-500">
                            <option value="0">Pilih penyaji</option>
                            <?php foreach ($employees as $emp): ?>
                                <option value="<?= (int)$emp['id'] ?>" <?= (int)$formData['presenter_employee_id'] === (int)$emp['id'] ? 'selected' : '' ?>><?= e($emp['full_name']) ?> - <?= e($emp['unit_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                </div>
                </div>

                <div data-rdk-tab-pane="resume">
                <div class="section-card section-card-blue space-y-4">
                    <div class="section-head"><div><div class="section-kicker"><i class="fas fa-notes-medical"></i> Resume Klinis</div><h3 class="section-title">II. Resume Klinis (Kronologi)</h3><p class="section-help">Jelaskan perjalanan pasien secara singkat, fokus pada fase yang relevan untuk diskusi.</p></div></div>
                    <textarea name="clinical_resume" rows="5" class="w-full rounded-2xl border-slate-300" placeholder="Jelaskan perjalanan pasien sejak masuk hingga masalah muncul..."><?= e($formData['clinical_resume']) ?></textarea>
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <textarea name="initial_assessment" rows="4" class="w-full rounded-2xl border-slate-300 compact-textarea" placeholder="Kondisi utama saat pengkajian awal"><?= e($formData['initial_assessment']) ?></textarea>
                        <textarea name="nursing_actions" rows="4" class="w-full rounded-2xl border-slate-300 compact-textarea" placeholder="Tindakan keperawatan yang sudah diberikan"><?= e($formData['nursing_actions']) ?></textarea>
                        <textarea name="patient_response" rows="4" class="w-full rounded-2xl border-slate-300 compact-textarea" placeholder="Respon pasien terhadap tindakan"><?= e($formData['patient_response']) ?></textarea>
                    </div>
                </div>
                </div>

                <div data-rdk-tab-pane="gap">
                <div class="section-card section-card-amber space-y-4">
                    <div class="section-head"><div><div class="section-kicker"><i class="fas fa-magnifying-glass-chart"></i> Gap Analysis</div><h3 class="section-title">III. Masalah yang Difokuskan</h3><p class="section-help">Tuliskan gap klinis, komunikasi, prosedur, atau respon emosional yang paling mengganjal.</p></div></div>
                    <textarea name="focused_problem" rows="4" class="w-full rounded-2xl border-slate-300" placeholder="Apa yang paling mengganjal dalam kasus ini?"><?= e($formData['focused_problem']) ?></textarea>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <textarea name="aspect_clinical" rows="4" class="w-full rounded-2xl border-slate-300 compact-textarea" placeholder="Aspek Klinis"><?= e($formData['aspect_clinical']) ?></textarea>
                        <textarea name="aspect_communication" rows="4" class="w-full rounded-2xl border-slate-300 compact-textarea" placeholder="Aspek Komunikasi"><?= e($formData['aspect_communication']) ?></textarea>
                        <textarea name="aspect_procedure" rows="4" class="w-full rounded-2xl border-slate-300 compact-textarea" placeholder="Aspek Prosedur"><?= e($formData['aspect_procedure']) ?></textarea>
                        <textarea name="aspect_emotional" rows="4" class="w-full rounded-2xl border-slate-300 compact-textarea" placeholder="Aspek Emosional"><?= e($formData['aspect_emotional']) ?></textarea>
                    </div>
                </div>
                </div>

                <div data-rdk-tab-pane="referensi">
                <div class="section-card section-card-emerald space-y-4">
                    <div class="section-head"><div><div class="section-kicker"><i class="fas fa-book-medical"></i> Referensi / SOP</div><h3 class="section-title">IV. Dasar Pemikiran</h3><p class="section-help">Dokumentasikan SOP, instruksi dokter, dan literatur yang menjadi dasar pengambilan keputusan.</p></div></div>
                    <textarea name="sop_reference" rows="4" class="w-full rounded-2xl border-slate-300" placeholder="SOP / panduan praktik klinis yang digunakan"><?= e($formData['sop_reference']) ?></textarea>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <textarea name="doctor_instruction" rows="4" class="w-full rounded-2xl border-slate-300 compact-textarea" placeholder="Instruksi dokter yang menjadi dasar tindakan"><?= e($formData['doctor_instruction']) ?></textarea>
                        <textarea name="literature_reference" rows="4" class="w-full rounded-2xl border-slate-300 compact-textarea" placeholder="Literatur / guideline pendukung"><?= e($formData['literature_reference']) ?></textarea>
                    </div>
                </div>
                </div>

                <div data-rdk-tab-pane="refleksi">
                <div class="section-card section-card-violet space-y-4">
                    <div class="section-head"><div><div class="section-kicker"><i class="fas fa-brain"></i> Self Reflection</div><h3 class="section-title">V. Analisis Diri</h3><p class="section-help">Refleksi singkat, jujur, dan spesifik untuk perbaikan praktik berikutnya.</p></div></div>
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <textarea name="good_points" rows="5" class="w-full rounded-2xl border-slate-300 compact-textarea" placeholder="Apa yang sudah berjalan dengan baik?"><?= e($formData['good_points']) ?></textarea>
                        <textarea name="difficult_points" rows="5" class="w-full rounded-2xl border-slate-300 compact-textarea" placeholder="Apa yang paling sulit dilakukan?"><?= e($formData['difficult_points']) ?></textarea>
                        <textarea name="improvement_plan" rows="5" class="w-full rounded-2xl border-slate-300 compact-textarea" placeholder="Jika terulang besok pagi, apa yang ingin diubah?"><?= e($formData['improvement_plan']) ?></textarea>
                    </div>
                    <textarea name="visual_support" rows="3" class="w-full rounded-2xl border-slate-300 compact-textarea" placeholder="Lampiran visual pendukung (hasil lab/EKG, catatan privasi, dll.)"><?= e($formData['visual_support']) ?></textarea>
                </div>

                <div class="mini-panel space-y-4">
                    <div class="flex items-center justify-between gap-3 flex-wrap">
                        <div><div class="section-kicker"><i class="fas fa-users"></i> Peserta</div><h3 class="section-title">Tim yang Ikut dalam RDK</h3></div>
                        <button type="button" onclick="rdkAddParticipant()" class="action-btn bg-sky-600 text-white text-sm hover:bg-sky-700">
                            <i class="fas fa-user-plus mr-1"></i> Tambah Peserta
                        </button>
                    </div>
                    <div id="participant-wrapper" class="space-y-3">
                        <?php foreach (($formData['participants'] ?: []) as $participant): ?>
                            <div class="participant-row grid grid-cols-1 md:grid-cols-12 gap-3 border border-slate-200 rounded-2xl p-4 bg-slate-50">
                                <div class="md:col-span-3"><input type="text" name="participant_name[]" value="<?= e($participant['participant_name'] ?? '') ?>" placeholder="Nama" class="w-full rounded-xl border-slate-300"></div>
                                <div class="md:col-span-2"><input type="text" name="participant_role[]" value="<?= e($participant['participant_role'] ?? '') ?>" placeholder="Peran/Jabatan" class="w-full rounded-xl border-slate-300"></div>
                                <div class="md:col-span-2"><input type="text" name="participant_unit[]" value="<?= e($participant['participant_unit'] ?? '') ?>" placeholder="Unit" class="w-full rounded-xl border-slate-300"></div>
                                <div class="md:col-span-2">
                                    <select name="participant_attendance[]" class="w-full rounded-xl border-slate-300">
                                        <option value="hadir" <?= (($participant['attendance_status'] ?? '') === 'hadir') ? 'selected' : '' ?>>Hadir</option>
                                        <option value="izin" <?= (($participant['attendance_status'] ?? '') === 'izin') ? 'selected' : '' ?>>Izin</option>
                                        <option value="dinas" <?= (($participant['attendance_status'] ?? '') === 'dinas') ? 'selected' : '' ?>>Dinas</option>
                                    </select>
                                </div>
                                <div class="md:col-span-2"><input type="text" name="participant_notes[]" value="<?= e($participant['notes'] ?? '') ?>" placeholder="Catatan" class="w-full rounded-xl border-slate-300"></div>
                                <div class="md:col-span-1 flex items-center justify-end"><button type="button" onclick="this.closest('.participant-row').remove()" class="w-10 h-10 rounded-xl bg-rose-100 text-rose-600 hover:bg-rose-200"><i class="fas fa-trash"></i></button></div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <div class="mini-panel space-y-4">
                    <div class="flex items-center justify-between gap-3 flex-wrap">
                        <div><div class="section-kicker"><i class="fas fa-comments"></i> Forum</div><h3 class="section-title">Masukan / Pertanyaan Kepala Unit & Forum Diskusi</h3></div>
                        <button type="button" onclick="rdkAddFeedback()" class="action-btn bg-indigo-600 text-white text-sm hover:bg-indigo-700">
                            <i class="fas fa-comments mr-1"></i> Tambah Masukan
                        </button>
                    </div>
                    <div id="feedback-wrapper" class="space-y-3">
                        <?php foreach (($formData['feedbacks'] ?: []) as $feedback): ?>
                            <div class="feedback-row grid grid-cols-1 md:grid-cols-12 gap-3 border border-slate-200 rounded-2xl p-4 bg-slate-50">
                                <div class="md:col-span-2"><input type="text" name="feedback_name[]" value="<?= e($feedback['giver_name'] ?? '') ?>" placeholder="Nama pemberi masukan" class="w-full rounded-xl border-slate-300"></div>
                                <div class="md:col-span-2"><input type="text" name="feedback_unit[]" value="<?= e($feedback['giver_unit'] ?? '') ?>" placeholder="Unit" class="w-full rounded-xl border-slate-300"></div>
                                <div class="md:col-span-4"><textarea name="feedback_question[]" rows="3" placeholder="Masukan / pertanyaan" class="w-full rounded-xl border-slate-300"><?= e($feedback['question_or_input'] ?? '') ?></textarea></div>
                                <div class="md:col-span-3"><textarea name="feedback_followup[]" rows="3" placeholder="Jawaban / tindak lanjut" class="w-full rounded-xl border-slate-300"><?= e($feedback['followup_or_answer'] ?? '') ?></textarea></div>
                                <div class="md:col-span-1 flex items-center justify-end"><button type="button" onclick="this.closest('.feedback-row').remove()" class="w-10 h-10 rounded-xl bg-rose-100 text-rose-600 hover:bg-rose-200"><i class="fas fa-trash"></i></button></div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <div class="grid grid-cols-1 gap-4">
                    <textarea name="discussion_notes" rows="4" class="w-full rounded-2xl border-slate-300 compact-textarea" placeholder="Ringkasan diskusi forum"><?= e($formData['discussion_notes']) ?></textarea>
                    <textarea name="conclusion_text" rows="4" class="w-full rounded-2xl border-slate-300 compact-textarea" placeholder="Kesimpulan RDK"><?= e($formData['conclusion_text']) ?></textarea>
                    <textarea name="minutes_text" rows="4" class="w-full rounded-2xl border-slate-300 compact-textarea" placeholder="Notulen / poin notulensi"><?= e($formData['minutes_text']) ?></textarea>
                    <textarea name="director_proposal" rows="4" class="w-full rounded-2xl border-slate-300 compact-textarea" placeholder="Usulan rancangan perbaikan ke Direktur"><?= e($formData['director_proposal']) ?></textarea>
                </div>

                </div>
                </div>

                <div class="flex flex-col md:flex-row gap-3 md:items-center md:justify-between pt-2">
                    <div class="flex items-center gap-3">
                        <label class="text-sm font-semibold text-slate-700">Status</label>
                        <select name="status" class="rounded-xl border-slate-300">
                            <option value="draft" <?= ($formData['status'] ?? 'draft') === 'draft' ? 'selected' : '' ?>>Draft</option>
                            <option value="final" <?= ($formData['status'] ?? '') === 'final' ? 'selected' : '' ?>>Final</option>
                        </select>
                    </div>
                    <?php if (rdk_can_edit($currentRole)): ?>
                        <div class="flex gap-3">
                            <button type="submit" class="action-btn bg-sky-600 text-white hover:bg-sky-700 shadow-lg shadow-sky-200">
                                <i class="fas fa-save mr-2"></i>Simpan RDK
                            </button>
                        </div>
                    <?php endif; ?>
                </div>
            </form>
        </div>

        <div class="space-y-6">
            <div class="premium-panel rounded-[30px] overflow-hidden">
                <div class="px-5 py-4 premium-header">
                    <h3 class="font-bold text-slate-800">Riwayat RDK</h3>
                    <p class="text-sm text-slate-500">Seluruh RDK yang telah dilakukan.</p>
                </div>
                <div class="p-5">
                    <form method="get" class="space-y-3 mb-4">
                        <input type="hidden" name="module" value="rdk">
                        <input type="text" name="q" value="<?= e($keyword) ?>" placeholder="Cari diagnosis / fokus masalah" class="w-full rounded-2xl border-slate-300 compact-textarea">
                        <div class="grid grid-cols-2 gap-3">
                            <select name="status" class="w-full rounded-2xl border-slate-300 compact-textarea">
                                <option value="">Semua status</option>
                                <option value="draft" <?= $statusFilter === 'draft' ? 'selected' : '' ?>>Draft</option>
                                <option value="final" <?= $statusFilter === 'final' ? 'selected' : '' ?>>Final</option>
                            </select>
                            <select name="unit_filter" class="w-full rounded-2xl border-slate-300 compact-textarea">
                                <option value="0">Semua unit</option>
                                <?php foreach ($units as $unit): ?>
                                    <option value="<?= (int)$unit['id'] ?>" <?= $unitFilter === (int)$unit['id'] ? 'selected' : '' ?>><?= e($unit['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <button type="submit" class="w-full px-4 py-2 rounded-2xl bg-slate-900 text-white font-semibold">Filter</button>
                    </form>

                    <div class="space-y-3 max-h-[820px] overflow-y-auto pr-1">
                        <?php if (!$listRows): ?>
                            <div class="text-sm text-slate-500 bg-slate-50 rounded-2xl p-4">Belum ada data RDK.</div>
                        <?php endif; ?>
                        <?php foreach ($listRows as $row): ?>
                            <div class="history-card transition-all">
                                <div class="flex items-start justify-between gap-3">
                                    <div>
                                        <div class="text-xs font-semibold uppercase tracking-wide <?= $row['status'] === 'final' ? 'text-emerald-600' : 'text-amber-600' ?>"><?= e($row['status']) ?></div>
                                        <div class="font-bold text-slate-800 mt-1"><?= e($row['diagnosis']) ?></div>
                                        <div class="text-sm text-slate-500 mt-1"><?= e($row['unit_name']) ?> • <?= e($row['patient_initial']) ?> / RM <?= e($row['rm_last3']) ?></div>
                                        <div class="text-xs text-slate-400 mt-2"><?= e(rdk_date_id($row['meeting_date'])) ?> • Peserta <?= (int)$row['total_participants'] ?> • Masukan <?= (int)$row['total_feedbacks'] ?></div>
                                    </div>
                                </div>
                                <div class="history-actions mt-4 flex flex-wrap gap-2">
                                    <a href="index.php?module=rdk&view_id=<?= (int)$row['id'] ?>" class="px-3 py-2 rounded-xl bg-sky-50 text-sky-700 text-sm font-semibold hover:bg-sky-100">Lihat</a>
                                    <?php if (rdk_can_edit($currentRole)): ?>
                                        <a href="index.php?module=rdk&edit_id=<?= (int)$row['id'] ?>" class="px-3 py-2 rounded-xl bg-amber-50 text-amber-700 text-sm font-semibold hover:bg-amber-100">Edit</a>
                                    <?php endif; ?>
                                    <a href="modules/rdk/export_docx.php?id=<?= (int)$row['id'] ?>" target="_blank" class="px-3 py-2 rounded-xl bg-emerald-50 text-emerald-700 text-sm font-semibold hover:bg-emerald-100">DOCX</a>
                                    <a href="modules/rdk/print.php?id=<?= (int)$row['id'] ?>" target="_blank" class="px-3 py-2 rounded-xl bg-violet-50 text-violet-700 text-sm font-semibold hover:bg-violet-100">Print / PDF</a>
                                    <?php if (rdk_can_edit($currentRole)): ?>
                                        <a href="index.php?module=rdk&delete_id=<?= (int)$row['id'] ?>" onclick="return confirm('Hapus data RDK ini?')" class="px-3 py-2 rounded-xl bg-rose-50 text-rose-700 text-sm font-semibold hover:bg-rose-100">Hapus</a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <?php if ($detailData): ?>
        <div class="premium-panel rounded-[30px] overflow-hidden">
            <div class="px-6 py-5 premium-header flex items-center justify-between flex-wrap gap-3">
                <div>
                    <h2 class="text-lg font-bold text-slate-800">Detail RDK</h2>
                    <p class="text-sm text-slate-500">Ringkasan lengkap hasil refleksi, diskusi, dan tindak lanjut.</p>
                </div>
                <div class="flex flex-wrap gap-2">
                    <a href="modules/rdk/export_docx.php?id=<?= (int)$detailData['id'] ?>" target="_blank" class="px-4 py-2 rounded-xl bg-emerald-600 text-white text-sm font-semibold">Export DOCX</a>
                    <a href="modules/rdk/print.php?id=<?= (int)$detailData['id'] ?>" target="_blank" class="px-4 py-2 rounded-xl bg-violet-600 text-white text-sm font-semibold">Print / PDF</a>
                </div>
            </div>
            <div class="p-6 grid grid-cols-1 lg:grid-cols-2 gap-6 text-sm leading-7">
                <div class="space-y-4">
                    <div class="bg-slate-50 rounded-2xl p-4 border border-slate-200"><strong>Identitas Kasus:</strong><br>Inisial <?= e($detailData['patient_initial']) ?> • RM <?= e($detailData['rm_last3']) ?><br>Diagnosis: <?= e($detailData['diagnosis']) ?><br>Tanggal kejadian: <?= e(rdk_date_id($detailData['incident_date'])) ?><br>Unit: <?= e($detailData['unit_name']) ?></div>
                    <div class="bg-slate-50 rounded-2xl p-4 border border-slate-200"><strong>Resume Klinis</strong><br><?= nl2br(e($detailData['clinical_resume'])) ?><hr class="my-3">Pengkajian awal: <?= nl2br(e($detailData['initial_assessment'])) ?><hr class="my-3">Tindakan: <?= nl2br(e($detailData['nursing_actions'])) ?><hr class="my-3">Respon pasien: <?= nl2br(e($detailData['patient_response'])) ?></div>
                    <div class="bg-slate-50 rounded-2xl p-4 border border-slate-200"><strong>Gap Analysis</strong><br><?= nl2br(e($detailData['focused_problem'])) ?><hr class="my-3">Klinis: <?= nl2br(e($detailData['aspect_clinical'])) ?><hr class="my-3">Komunikasi: <?= nl2br(e($detailData['aspect_communication'])) ?><hr class="my-3">Prosedur: <?= nl2br(e($detailData['aspect_procedure'])) ?><hr class="my-3">Emosional: <?= nl2br(e($detailData['aspect_emotional'])) ?></div>
                </div>
                <div class="space-y-4">
                    <div class="bg-slate-50 rounded-2xl p-4 border border-slate-200"><strong>Referensi / SOP</strong><br>SOP: <?= nl2br(e($detailData['sop_reference'])) ?><hr class="my-3">Instruksi dokter: <?= nl2br(e($detailData['doctor_instruction'])) ?><hr class="my-3">Literatur: <?= nl2br(e($detailData['literature_reference'])) ?></div>
                    <div class="bg-slate-50 rounded-2xl p-4 border border-slate-200"><strong>Self Reflection</strong><br>Yang sudah baik: <?= nl2br(e($detailData['good_points'])) ?><hr class="my-3">Yang tersulit: <?= nl2br(e($detailData['difficult_points'])) ?><hr class="my-3">Perubahan yang diinginkan: <?= nl2br(e($detailData['improvement_plan'])) ?><hr class="my-3">Visual pendukung: <?= nl2br(e($detailData['visual_support'])) ?></div>
                    <div class="bg-slate-50 rounded-2xl p-4 border border-slate-200"><strong>Notulen & Tindak Lanjut</strong><br>Diskusi: <?= nl2br(e($detailData['discussion_notes'])) ?><hr class="my-3">Kesimpulan: <?= nl2br(e($detailData['conclusion_text'])) ?><hr class="my-3">Notulen: <?= nl2br(e($detailData['minutes_text'])) ?><hr class="my-3">Usulan ke Direktur: <?= nl2br(e($detailData['director_proposal'])) ?></div>
                </div>
            </div>

            <div class="px-6 pb-6 grid grid-cols-1 lg:grid-cols-2 gap-6">
                <div class="bg-white rounded-2xl border border-slate-200 overflow-hidden">
                    <div class="px-4 py-3 bg-slate-50 border-b border-slate-200 font-bold text-slate-800">Tim yang Ikut dalam RDK</div>
                    <div class="overflow-x-auto">
                        <table class="min-w-full text-sm">
                            <thead class="bg-slate-100 text-slate-700"><tr><th class="px-4 py-3 text-left">Nama</th><th class="px-4 py-3 text-left">Peran</th><th class="px-4 py-3 text-left">Unit</th><th class="px-4 py-3 text-left">Status</th><th class="px-4 py-3 text-left">Catatan</th></tr></thead>
                            <tbody>
                            <?php foreach ($detailData['participants'] as $p): ?>
                                <tr class="border-t border-slate-100"><td class="px-4 py-3"><?= e($p['participant_name']) ?></td><td class="px-4 py-3"><?= e($p['participant_role']) ?></td><td class="px-4 py-3"><?= e($p['participant_unit']) ?></td><td class="px-4 py-3"><?= e($p['attendance_status']) ?></td><td class="px-4 py-3"><?= e($p['notes']) ?></td></tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="bg-white rounded-2xl border border-slate-200 overflow-hidden">
                    <div class="px-4 py-3 bg-slate-50 border-b border-slate-200 font-bold text-slate-800">Masukan / Pertanyaan Forum</div>
                    <div class="overflow-x-auto">
                        <table class="min-w-full text-sm">
                            <thead class="bg-slate-100 text-slate-700"><tr><th class="px-4 py-3 text-left">Nama</th><th class="px-4 py-3 text-left">Unit</th><th class="px-4 py-3 text-left">Masukan</th><th class="px-4 py-3 text-left">Tindak Lanjut</th></tr></thead>
                            <tbody>
                            <?php foreach ($detailData['feedbacks'] as $f): ?>
                                <tr class="border-t border-slate-100"><td class="px-4 py-3"><?= e($f['giver_name']) ?></td><td class="px-4 py-3"><?= e($f['giver_unit']) ?></td><td class="px-4 py-3"><?= nl2br(e($f['question_or_input'])) ?></td><td class="px-4 py-3"><?= nl2br(e($f['followup_or_answer'])) ?></td></tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

<script>
function rdkAddParticipant() {
    const wrap = document.getElementById('participant-wrapper');
    const row = document.createElement('div');
    row.className = 'participant-row grid grid-cols-1 md:grid-cols-12 gap-3 border border-slate-200 rounded-2xl p-4 bg-slate-50';
    row.innerHTML = `
        <div class="md:col-span-3"><input type="text" name="participant_name[]" placeholder="Nama" class="w-full rounded-xl border-slate-300"></div>
        <div class="md:col-span-2"><input type="text" name="participant_role[]" placeholder="Peran/Jabatan" class="w-full rounded-xl border-slate-300"></div>
        <div class="md:col-span-2"><input type="text" name="participant_unit[]" placeholder="Unit" class="w-full rounded-xl border-slate-300"></div>
        <div class="md:col-span-2"><select name="participant_attendance[]" class="w-full rounded-xl border-slate-300"><option value="hadir">Hadir</option><option value="izin">Izin</option><option value="dinas">Dinas</option></select></div>
        <div class="md:col-span-2"><input type="text" name="participant_notes[]" placeholder="Catatan" class="w-full rounded-xl border-slate-300"></div>
        <div class="md:col-span-1 flex items-center justify-end"><button type="button" onclick="this.closest('.participant-row').remove()" class="w-10 h-10 rounded-xl bg-rose-100 text-rose-600 hover:bg-rose-200"><i class="fas fa-trash"></i></button></div>`;
    wrap.appendChild(row);
}
function rdkInitTabs() {
    const buttons = document.querySelectorAll('[data-rdk-tab]');
    const panes = document.querySelectorAll('[data-rdk-tab-pane]');
    buttons.forEach(btn => {
        btn.addEventListener('click', function(){
            const target = this.getAttribute('data-rdk-tab');
            buttons.forEach(b => b.classList.toggle('active', b === this));
            panes.forEach(p => p.classList.toggle('active', p.getAttribute('data-rdk-tab-pane') === target));
        });
    });
}

function rdkAddFeedback() {
    const wrap = document.getElementById('feedback-wrapper');
    const row = document.createElement('div');
    row.className = 'feedback-row grid grid-cols-1 md:grid-cols-12 gap-3 border border-slate-200 rounded-2xl p-4 bg-slate-50';
    row.innerHTML = `
        <div class="md:col-span-2"><input type="text" name="feedback_name[]" placeholder="Nama pemberi masukan" class="w-full rounded-xl border-slate-300"></div>
        <div class="md:col-span-2"><input type="text" name="feedback_unit[]" placeholder="Unit" class="w-full rounded-xl border-slate-300"></div>
        <div class="md:col-span-4"><textarea name="feedback_question[]" rows="3" placeholder="Masukan / pertanyaan" class="w-full rounded-xl border-slate-300"></textarea></div>
        <div class="md:col-span-3"><textarea name="feedback_followup[]" rows="3" placeholder="Jawaban / tindak lanjut" class="w-full rounded-xl border-slate-300"></textarea></div>
        <div class="md:col-span-1 flex items-center justify-end"><button type="button" onclick="this.closest('.feedback-row').remove()" class="w-10 h-10 rounded-xl bg-rose-100 text-rose-600 hover:bg-rose-200"><i class="fas fa-trash"></i></button></div>`;
    wrap.appendChild(row);
}
document.addEventListener('DOMContentLoaded', rdkInitTabs);
</script>
