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

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

$autoload = dirname(__DIR__, 2) . '/vendor/autoload.php';
if (!file_exists($autoload)) {
    http_response_code(500);
    exit('vendor/autoload.php tidak ditemukan. Install PhpWord terlebih dahulu.');
}
require_once $autoload;

if (!class_exists('\PhpOffice\PhpWord\PhpWord')) {
    http_response_code(500);
    exit('Library PhpWord tidak tersedia.');
}

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

function rdk_doc_e($v): string { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
function rdk_doc_date($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();
}

$phpWord = new \PhpOffice\PhpWord\PhpWord();
$phpWord->setDefaultFontName('Times New Roman');
$phpWord->setDefaultFontSize(11);

$section = $phpWord->addSection([
    'marginTop' => 900,
    'marginBottom' => 900,
    'marginLeft' => 1000,
    'marginRight' => 900,
]);

$logo = 'https://balimedhospital.co.id/wp-content/uploads/elementor/thumbs/logo-dark-o9cm6tnx14hcrnest1hge1pwnqj0yaumij7qohadlm.png';
$logoTemp = tempnam(sys_get_temp_dir(), 'rdk_logo_');
$img = @file_get_contents($logo);
if ($img) {
    file_put_contents($logoTemp, $img);
    $section->addImage($logoTemp, ['width' => 90, 'alignment' => \PhpOffice\PhpWord\SimpleType\Jc::CENTER]);
}

$title = ['bold' => true, 'size' => 14];
$head = ['bold' => true, 'size' => 11];
$normal = ['size' => 11];
$center = ['align' => 'center'];
$justify = ['align' => 'both'];
$tableName = 'RdkTable';
$phpWord->addTableStyle($tableName, ['borderSize' => 6, 'borderColor' => '888888', 'cellMargin' => 70], ['bgColor' => 'DDEBF7']);

$section->addText('RDK / REFLEKSI DISKUSI KASUS KEPERAWATAN', $title, $center);
$section->addText('RS BaliMed Denpasar', $head, $center);
$section->addTextBreak(1);

$section->addText('I. IDENTITAS KASUS (ANONIM)', $head);
$section->addText('Inisial Pasien: ' . $data['patient_initial'], $normal);
$section->addText('No. RM (3 angka terakhir): ' . ($data['rm_last3'] ?: '-'), $normal);
$section->addText('Diagnosis Medis: ' . $data['diagnosis'], $normal);
$section->addText('Tanggal Kejadian: ' . rdk_doc_date($data['incident_date']), $normal);
$section->addText('Unit/Ruangan: ' . $data['unit_name'], $normal);
$section->addText('Tanggal RDK: ' . rdk_doc_date($data['meeting_date']), $normal);
$section->addText('Penyaji: ' . $data['presenter_name'], $normal);
$section->addTextBreak(1);

$blocks = [
    'II. RESUME KLINIS (KRONOLOGI)' => [
        'Perjalanan pasien sejak masuk hingga masalah muncul:' => $data['clinical_resume'],
        'Kondisi utama saat pengkajian awal:' => $data['initial_assessment'],
        'Tindakan keperawatan yang sudah diberikan:' => $data['nursing_actions'],
        'Respon pasien terhadap tindakan:' => $data['patient_response'],
    ],
    'III. MASALAH YANG DIFOKUSKAN (GAP ANALYSIS)' => [
        'Masalah utama:' => $data['focused_problem'],
        'Aspek Klinis:' => $data['aspect_clinical'],
        'Aspek Komunikasi:' => $data['aspect_communication'],
        'Aspek Prosedur:' => $data['aspect_procedure'],
        'Aspek Emosional:' => $data['aspect_emotional'],
    ],
    'IV. DASAR PEMIKIRAN (REFERENSI / SOP)' => [
        'Standar/SOP:' => $data['sop_reference'],
        'Instruksi dokter:' => $data['doctor_instruction'],
        'Literatur / guideline:' => $data['literature_reference'],
    ],
    'V. ANALISIS DIRI (SELF-REFLECTION)' => [
        'Apa yang sudah berjalan dengan baik?' => $data['good_points'],
        'Apa yang paling sulit dilakukan?' => $data['difficult_points'],
        'Jika kejadian yang sama terulang, apa yang ingin diubah?' => $data['improvement_plan'],
        'Visual pendukung / lampiran:' => $data['visual_support'],
    ],
    'VI. HASIL DISKUSI, KESIMPULAN, DAN NOTULEN' => [
        'Ringkasan diskusi:' => $data['discussion_notes'],
        'Kesimpulan:' => $data['conclusion_text'],
        'Notulen:' => $data['minutes_text'],
        'Usulan rancangan perbaikan ke Direktur:' => $data['director_proposal'],
    ],
];

foreach ($blocks as $titleBlock => $items) {
    $section->addText($titleBlock, $head);
    foreach ($items as $label => $content) {
        $section->addText($label, ['bold' => true, 'size' => 11]);
        $section->addText((string)($content ?: '-'), $normal, $justify);
        $section->addTextBreak(1);
    }
}

$section->addText('VII. TIM YANG IKUT DALAM RDK', $head);
$table = $section->addTable($tableName);
$table->addRow();
$table->addCell(800)->addText('No', ['bold' => true]);
$table->addCell(2500)->addText('Nama', ['bold' => true]);
$table->addCell(1800)->addText('Peran/Jabatan', ['bold' => true]);
$table->addCell(1800)->addText('Unit', ['bold' => true]);
$table->addCell(1100)->addText('Status', ['bold' => true]);
$table->addCell(2000)->addText('Catatan', ['bold' => true]);
foreach ($participants as $i => $p) {
    $table->addRow();
    $table->addCell(800)->addText((string)($i + 1));
    $table->addCell(2500)->addText($p['participant_name']);
    $table->addCell(1800)->addText((string)$p['participant_role']);
    $table->addCell(1800)->addText((string)$p['participant_unit']);
    $table->addCell(1100)->addText((string)$p['attendance_status']);
    $table->addCell(2000)->addText((string)$p['notes']);
}
$section->addTextBreak(1);

$section->addText('VIII. MASUKAN / PERTANYAAN FORUM', $head);
$table2 = $section->addTable($tableName);
$table2->addRow();
$table2->addCell(800)->addText('No', ['bold' => true]);
$table2->addCell(2200)->addText('Nama', ['bold' => true]);
$table2->addCell(1800)->addText('Unit', ['bold' => true]);
$table2->addCell(3500)->addText('Masukan / Pertanyaan', ['bold' => true]);
$table2->addCell(3500)->addText('Jawaban / Tindak Lanjut', ['bold' => true]);
foreach ($feedbacks as $i => $f) {
    $table2->addRow();
    $table2->addCell(800)->addText((string)($i + 1));
    $table2->addCell(2200)->addText((string)$f['giver_name']);
    $table2->addCell(1800)->addText((string)$f['giver_unit']);
    $table2->addCell(3500)->addText((string)$f['question_or_input']);
    $table2->addCell(3500)->addText((string)$f['followup_or_answer']);
}

$section->addTextBreak(2);
$section->addText('Denpasar, ' . rdk_doc_date(date('Y-m-d')), $normal, ['align' => 'right']);
$section->addText('Mengetahui,', $normal, ['align' => 'right']);
$section->addText('Tim RDK Keperawatan RS BaliMed', $normal, ['align' => 'right']);
$section->addTextBreak(3);
$section->addText($data['presenter_name'], ['bold' => true], ['align' => 'right']);

$tempFile = tempnam(sys_get_temp_dir(), 'rdk_docx_');
$writer = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$writer->save($tempFile);

if (ob_get_length()) ob_end_clean();
$filename = 'RDK_' . preg_replace('/[^A-Za-z0-9\-_]+/', '_', $data['patient_initial']) . '_' . date('Ymd', strtotime((string)$data['meeting_date'])) . '.docx';
header('Content-Description: File Transfer');
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($tempFile));
readfile($tempFile);
@unlink($tempFile);
if (isset($logoTemp) && is_file($logoTemp)) @unlink($logoTemp);
exit;
