<?php
declare(strict_types=1);

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

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

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$conn = getConnection();

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

function bulanIndo(int $bulan): string
{
    $arr = [
        1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April',
        5 => 'Mei', 6 => 'Juni', 7 => 'Juli', 8 => 'Agustus',
        9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember'
    ];
    return $arr[$bulan] ?? '-';
}

function getSectionColumns(string $code): array
{
    /* Kolom sesuai format Word laporan bulanan RS Balimed */
    return match ($code) {
        /* ── Level Unit ── */
        'ketenagaan'         => ['Nama Unit / Uraian', 'Jumlah Tenaga', 'Komposisi', 'Keterangan'],
        'jumlah_pasien'      => ['Uraian / Kelas Pasien', 'Jumlah Pasien', 'Jumlah Perawat', 'Rasio', 'Keterangan / BOR'],
        'keterlambatan_staf' => ['Nama Staf', 'Jumlah Staf Terlambat', 'Total Menit Terlambat', 'Keterangan'],
        'capaian_rka'        => ['No', 'Uraian Kegiatan / Project', 'Bulan', 'Capaian', 'Kendala'],
        'makp'               => ['No', 'Jumlah PP & PA', 'Tingkat Keberhasilan (%)', 'Kendala', 'RTL'],
        'permasalahan'       => ['No', 'Hari / Tgl', 'Permasalahan', 'Unit Terkait', 'Hasil Rapat', 'RTL / Realisasi'],
        'mutu'               => ['SPO / Indikator', 'Indikator / Monev SPO', 'Bulan', 'Capaian', 'Analisa / RTL'],
        'ikp'                => ['No', 'Jenis Insiden', 'Tanggal', 'Kronologi Singkat', 'Tindak Lanjut', 'Keterangan'],
        /* ── Level Kasubdiv/Kadiv (ada kolom Unit) ── */
        'analisa_kadiv'      => ['Area / Topik', 'Kesimpulan', 'Analisa Kadiv', 'Rekomendasi / RTL'],
        /* Legacy codes */
        'data_pelayanan'     => ['Jumlah Pasien / Bulan', 'Jumlah Staf', 'Jumlah Staf Sakit', 'Lama Sakit', 'Penyebab Sakit', 'Jumlah Staf Hamil', 'BOR Unit', 'Rasio Pasien : Perawat', 'Beban Kerja Unit'],
        'kejadian_keselamatan'=> ['Jenis Kejadian', 'Siapa yang Menemukan', 'Tindakan yang Sudah Dilakukan', 'Keterangan'],
        'permasalahan_unit'  => ['Permasalahan', 'Unit Terkait', 'Solusi', 'Keterangan'],
        default              => ['Uraian', 'Bulan', 'Capaian', 'Keterangan / RTL'],
    };
}

function getLevelLabel(array $header): string
{
    $level = strtolower((string)($header['report_level'] ?? ''));
    return match ($level) {
        'unit' => 'LAPORAN BULANAN UNIT',
        'kadiv' => 'LAPORAN BULANAN KADIV',
        default => 'LAPORAN BULANAN KASUBDIV',
    };
}

function getReportTypeLabel(array $header): string
{
    $type = strtolower((string)($header['report_type'] ?? ''));
    return match ($type) {
        'rajal' => 'Rawat Jalan',
        'ranap' => 'Rawat Inap',
        'gabungan' => 'Gabungan Rawat Jalan & Rawat Inap',
        default => strtoupper($type ?: '-'),
    };
}

function getIdentityLines(array $header): array
{
    $level = strtolower((string)($header['report_level'] ?? ''));
    $lines = [];

    if ($level === 'unit') {
        $lines[] = 'Unit: ' . ((string)($header['unit_name'] ?? '-') ?: '-');
        if (!empty($header['subdivision_name'])) {
            $lines[] = 'Kasubdiv: ' . (string)$header['subdivision_name'];
        }
        if (!empty($header['division_name'])) {
            $lines[] = 'Divisi: ' . (string)$header['division_name'];
        }
    } elseif ($level === 'kadiv') {
        if (!empty($header['division_name'])) {
            $lines[] = 'Divisi: ' . (string)$header['division_name'];
        }
        $lines[] = 'Ruang Lingkup: ' . getReportTypeLabel($header);
    } else {
        if (!empty($header['subdivision_name'])) {
            $lines[] = 'Kasubdiv: ' . (string)$header['subdivision_name'];
        }
        if (!empty($header['division_name'])) {
            $lines[] = 'Divisi: ' . (string)$header['division_name'];
        }
        $lines[] = 'Ruang Lingkup: ' . getReportTypeLabel($header);
    }

    $lines[] = 'Periode: ' . bulanIndo((int)$header['bulan']) . ' ' . (string)$header['tahun'];
    return $lines;
}


$reportId = (int)($_GET['report_id'] ?? 0);
if ($reportId <= 0) {
    exit('Report ID tidak valid.');
}

$stmt = $conn->prepare("
    SELECT h.*, 
           u.name AS unit_name,
           ns.name AS subdivision_name, 
           nd.name AS division_name
    FROM monthly_report_headers h
    LEFT JOIN units u ON u.id = h.unit_id
    LEFT JOIN nursing_subdivisions ns ON ns.id = h.subdivision_id
    LEFT JOIN nursing_divisions nd ON nd.id = h.division_id
    WHERE h.id = ? LIMIT 1
");
$stmt->bind_param('i', $reportId);
$stmt->execute();
$header = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$header) {
    exit('Laporan tidak ditemukan.');
}

$sections = [];
$stmt = $conn->prepare("SELECT * FROM monthly_report_sections WHERE report_id = ? ORDER BY urut ASC, id ASC");
$stmt->bind_param('i', $reportId);
$stmt->execute();
$res = $stmt->get_result();
while ($row = $res->fetch_assoc()) {
    $sections[] = $row;
}
$stmt->close();

foreach ($sections as &$section) {
    $rows = [];
    $stmt = $conn->prepare("SELECT * FROM monthly_report_rows WHERE section_id = ? ORDER BY urut ASC, id ASC");
    $stmt->bind_param('i', $section['id']);
    $stmt->execute();
    $res = $stmt->get_result();
    while ($r = $res->fetch_assoc()) {
        $rows[] = $r;
    }
    $stmt->close();
    $section['rows'] = $rows;
}
unset($section);

$identityLines = getIdentityLines($header);
?><!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="utf-8">
    <title><?= e($header['title']) ?></title>
    <style>
        body{font-family:Arial,sans-serif;font-size:14px;color:#111;line-height:1.45}
        .center{text-align:center}
        .section{margin-top:24px}
        table{width:100%;border-collapse:collapse;margin-top:10px}
        th,td{border:1px solid #333;padding:6px;vertical-align:top;font-size:13px}
        th{background:#f1f5f9}
        .signature{margin-top:60px;width:320px;margin-left:auto;text-align:center}
        .muted{color:#555}
        @media print { body{margin:15mm} }
    </style>
</head>
<body>
    <div class="center">
        <div style="font-weight:bold;font-size:16px;"><?= e(getLevelLabel($header)) ?></div>
        <h2><?= e($header['title']) ?></h2>
        <div class="muted" style="margin-top:6px;">
            <?php foreach ($identityLines as $line): ?>
                <div><?= e($line) ?></div>
            <?php endforeach; ?>
        </div>
    </div>

    <div class="section">
        <h3>BAB I. PENDAHULUAN</h3>
        <div><?= nl2br(e($header['pendahuluan'] ?? '')) ?></div>
    </div>

    <div class="section">
        <h3>BAB II. PEMBAHASAN</h3>

        <?php foreach ($sections as $section): ?>
            <div style="margin-top:20px;">
                <h4><?= e($section['section_title']) ?></h4>

                <?php if (!empty($section['intro_text'])): ?>
                    <div style="margin-bottom:8px;"><?= nl2br(e($section['intro_text'])) ?></div>
                <?php endif; ?>

                <?php $cols = getSectionColumns((string)$section['section_code']); ?>

                <table>
                    <thead>
                        <tr>
                            <th style="width:40px">No</th>
                            <?php foreach ($cols as $col): ?>
                                <th><?= e($col) ?></th>
                            <?php endforeach; ?>
                            <th>Catatan</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($section['rows'])): ?>
                            <tr>
                                <td colspan="<?= count($cols) + 2 ?>" class="center">Belum ada data</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($section['rows'] as $i => $row): ?>
                                <tr>
                                    <td><?= $i + 1 ?></td>
                                    <?php for ($c = 1; $c <= count($cols); $c++): ?>
                                        <td><?= nl2br(e($row["col{$c}"] ?? '')) ?></td>
                                    <?php endfor; ?>
                                    <td><?= nl2br(e($row['notes'] ?? '')) ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        <?php endforeach; ?>
    </div>

    <div class="section">
        <h3>BAB III. SIMPULAN</h3>
        <div><?= nl2br(e($header['simpulan'] ?? '')) ?></div>
    </div>

    <?php if (!empty($header['penutup'])): ?>
        <div class="section">
            <h3>PENUTUP</h3>
            <div><?= nl2br(e($header['penutup'])) ?></div>
        </div>
    <?php endif; ?>

    <div class="signature">
        <div>Denpasar, <?= date('d') ?> <?= bulanIndo((int)date('n')) ?> <?= date('Y') ?></div>
        <div style="margin-top:10px;"><?= e($header['signed_position'] ?? '') ?></div>
        <div style="height:80px;"></div>
        <div><strong><?= e($header['signed_name'] ?? '') ?></strong></div>
        <?php if (!empty($header['status'])): ?>
            <div style="margin-top:10px;font-size:12px;color:#555;">Status Dokumen: <?= e(strtoupper((string)$header['status'])) ?></div>
        <?php endif; ?>
    </div>
</body>
</html>
