<?php
declare(strict_types=1);

// jadwal_perawat_public.php
// Halaman publik jadwal perawat simple. Tidak perlu login.

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

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

$conn = function_exists('getAppConnection') ? getAppConnection() : getConnection();

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

$monthNames = [
    1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April', 5 => 'Mei', 6 => 'Juni',
    7 => 'Juli', 8 => 'Agustus', 9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember'
];
$dayNames = ['Minggu','Senin','Selasa','Rabu','Kamis','Jumat','Sabtu'];

function nurseScheduleDefaultUnitLegend(): string
{
    return implode("\n", [
        '1=IGD',
        '2=Canigara',
        '3=Cempaka',
        '4=Cendana',
        '5=Ruang Bayi',
        '6=NICU',
        '7=ICU',
        '8=Kamar Bersalin/VK',
        '9=HD',
        '10=OK/Kamar Operasi',
        '11=Poliklinik',
    ]);
}

function nurseScheduleParseUnitLegend(string $legend): array
{
    $items = [];
    foreach (preg_split('/\r\n|\r|\n/', $legend) as $line) {
        $line = trim((string)$line);
        if ($line === '') {
            continue;
        }
        $parts = preg_split('/\s*=\s*/', $line, 2);
        if (count($parts) === 2) {
            $items[] = ['code' => trim($parts[0]), 'unit' => trim($parts[1])];
        } else {
            $items[] = ['code' => '', 'unit' => $line];
        }
    }
    return $items;
}

$token = trim((string)($_GET['t'] ?? $_GET['token'] ?? ''));
$period = null;
$basePeriod = null;
$availablePeriods = [];
$rows = [];

$selectedMonth = (int)($_GET['bulan'] ?? $_GET['month'] ?? 0);
$selectedYear = (int)($_GET['tahun'] ?? $_GET['year'] ?? 0);
if ($selectedMonth < 1 || $selectedMonth > 12) {
    $selectedMonth = 0;
}
if ($selectedYear < 2000 || $selectedYear > 2100) {
    $selectedYear = 0;
}

if ($conn instanceof mysqli && $token !== '') {
    $stmt = $conn->prepare('SELECT * FROM nurse_schedule_periods WHERE token = ? AND is_public = 1 LIMIT 1');
    if ($stmt) {
        $stmt->bind_param('s', $token);
        $stmt->execute();
        $res = $stmt->get_result();
        $basePeriod = $res ? $res->fetch_assoc() : null;
        $stmt->close();
    }

    if ($basePeriod) {
        // Satu link publik bisa dipakai untuk memilih bulan lain.
        // Demi keamanan, daftar bulan dibatasi pada unit yang sama dengan token awal.
        $baseUnit = trim((string)($basePeriod['unit_name'] ?? ''));
        if ($baseUnit !== '') {
            $stmt = $conn->prepare('SELECT id, title, unit_name, schedule_month, schedule_year, updated_at FROM nurse_schedule_periods WHERE is_public = 1 AND unit_name = ? ORDER BY schedule_year DESC, schedule_month DESC, id DESC');
            if ($stmt) {
                $stmt->bind_param('s', $baseUnit);
                $stmt->execute();
                $res = $stmt->get_result();
                while ($res && ($row = $res->fetch_assoc())) {
                    $availablePeriods[] = $row;
                }
                $stmt->close();
            }
        } else {
            $res = $conn->query("SELECT id, title, unit_name, schedule_month, schedule_year, updated_at FROM nurse_schedule_periods WHERE is_public = 1 AND (unit_name IS NULL OR unit_name = '') ORDER BY schedule_year DESC, schedule_month DESC, id DESC");
            while ($res && ($row = $res->fetch_assoc())) {
                $availablePeriods[] = $row;
            }
        }

        $period = $basePeriod;
        if ($selectedMonth > 0 && $selectedYear > 0) {
            if ($baseUnit !== '') {
                $stmt = $conn->prepare('SELECT * FROM nurse_schedule_periods WHERE is_public = 1 AND unit_name = ? AND schedule_month = ? AND schedule_year = ? ORDER BY id DESC LIMIT 1');
                if ($stmt) {
                    $stmt->bind_param('sii', $baseUnit, $selectedMonth, $selectedYear);
                    $stmt->execute();
                    $res = $stmt->get_result();
                    $selectedPeriod = $res ? $res->fetch_assoc() : null;
                    if ($selectedPeriod) {
                        $period = $selectedPeriod;
                    }
                    $stmt->close();
                }
            } else {
                $stmt = $conn->prepare("SELECT * FROM nurse_schedule_periods WHERE is_public = 1 AND (unit_name IS NULL OR unit_name = '') AND schedule_month = ? AND schedule_year = ? ORDER BY id DESC LIMIT 1");
                if ($stmt) {
                    $stmt->bind_param('ii', $selectedMonth, $selectedYear);
                    $stmt->execute();
                    $res = $stmt->get_result();
                    $selectedPeriod = $res ? $res->fetch_assoc() : null;
                    if ($selectedPeriod) {
                        $period = $selectedPeriod;
                    }
                    $stmt->close();
                }
            }
        }

        if ($period) {
            $periodId = (int)$period['id'];
            $stmt = $conn->prepare('SELECT * FROM nurse_schedule_rows WHERE period_id = ? ORDER BY sort_order ASC, id ASC');
            if ($stmt) {
                $stmt->bind_param('i', $periodId);
                $stmt->execute();
                $res = $stmt->get_result();
                while ($res && ($row = $res->fetch_assoc())) {
                    $row['cells'] = [];
                    $rows[(int)$row['id']] = $row;
                }
                $stmt->close();
            }
            if ($rows) {
                $ids = implode(',', array_map('intval', array_keys($rows)));
                $res = $conn->query("SELECT * FROM nurse_schedule_cells WHERE row_id IN ({$ids}) ORDER BY schedule_date ASC");
                while ($res && ($cell = $res->fetch_assoc())) {
                    $day = (int)date('j', strtotime((string)$cell['schedule_date']));
                    $rows[(int)$cell['row_id']]['cells'][$day] = $cell;
                }
            }
        }
    }
}

$month = $period ? (int)$period['schedule_month'] : (int)date('n');
$year = $period ? (int)$period['schedule_year'] : (int)date('Y');
$daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$unitLegendText = trim((string)($period['unit_code_legend'] ?? ''));
if ($unitLegendText === '') {
    $unitLegendText = nurseScheduleDefaultUnitLegend();
}
$unitLegendItems = nurseScheduleParseUnitLegend($unitLegendText);
?>
<!doctype html>
<html lang="id">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= $period ? e($period['title']) : 'Jadwal Perawat' ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Poppins', sans-serif; }

        /* Optimasi cetak jadwal: semua tanggal masuk 1 halaman lebar kertas */
        @page {
            size: A4 landscape;
            margin: 7mm;
        }

        @media print {
            html, body {
                width: 297mm;
                background: #fff !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }

            .no-print { display: none !important; }

            main {
                padding: 0 !important;
                margin: 0 !important;
                max-width: none !important;
                width: 100% !important;
            }

            section {
                box-shadow: none !important;
                border: 0 !important;
                border-radius: 0 !important;
                overflow: visible !important;
            }

            section > div:first-child {
                padding: 7px 10px !important;
                background: #fff !important;
                color: #0f172a !important;
                border-bottom: 1px solid #cbd5e1 !important;
            }

            section > div:first-child p,
            section > div:first-child h1 {
                color: #0f172a !important;
            }

            section > div:first-child h1 {
                font-size: 16px !important;
                line-height: 1.15 !important;
                margin-top: 2px !important;
            }

            section > div:first-child p {
                font-size: 8px !important;
                line-height: 1.2 !important;
                margin-top: 2px !important;
            }

            section > div:first-child img {
                width: 38mm !important;
                max-width: 38mm !important;
                height: auto !important;
                padding: 1px !important;
                box-shadow: none !important;
                border: 1px solid #e2e8f0 !important;
            }

            .p-5, .md\:p-8 {
                padding: 7px 0 0 0 !important;
            }

            .print-table-wrap {
                overflow: visible !important;
                border-radius: 0 !important;
                border: 1px solid #334155 !important;
                width: 100% !important;
            }

            table.print-schedule-table {
                width: 100% !important;
                min-width: 0 !important;
                table-layout: fixed !important;
                border-collapse: collapse !important;
                font-size: 6.2px !important;
                line-height: 1.05 !important;
            }

            table.print-schedule-table th,
            table.print-schedule-table td {
                padding: 1.5px 1px !important;
                border: 0.5px solid #64748b !important;
                white-space: normal !important;
                word-break: break-word !important;
                overflow: hidden !important;
                vertical-align: middle !important;
            }

            table.print-schedule-table th:first-child,
            table.print-schedule-table td:first-child {
                position: static !important;
                width: 32mm !important;
                min-width: 0 !important;
                font-size: 5.8px !important;
                text-align: left !important;
            }

            table.print-schedule-table th:nth-child(2),
            table.print-schedule-table td:nth-child(2) {
                width: 18mm !important;
                min-width: 0 !important;
                font-size: 5.7px !important;
                text-align: left !important;
            }

            table.print-schedule-table th:nth-child(n+3),
            table.print-schedule-table td:nth-child(n+3) {
                width: auto !important;
                min-width: 0 !important;
                text-align: center !important;
            }

            table.print-schedule-table thead {
                display: table-header-group;
            }

            table.print-schedule-table tr {
                page-break-inside: avoid;
            }

            table.print-schedule-table .text-\[10px\] {
                font-size: 5px !important;
            }

            .print-legend {
                display: grid !important;
                grid-template-columns: 0.9fr 1.1fr !important;
                gap: 5px !important;
                margin-top: 6px !important;
                font-size: 6.5px !important;
                line-height: 1.15 !important;
            }

            .print-legend > div {
                padding: 5px !important;
                border-radius: 6px !important;
                page-break-inside: avoid;
            }

            .print-legend .grid {
                grid-template-columns: repeat(4, minmax(0, 1fr)) !important;
                gap: 3px !important;
            }

            .print-legend .rounded-xl {
                padding: 3px !important;
                border-radius: 4px !important;
            }

            .print-footer {
                margin-top: 4px !important;
                font-size: 6px !important;
            }
        }
    </style>
</head>
<body class="min-h-screen bg-gradient-to-br from-blue-50 via-white to-cyan-50 text-slate-800">
<?php if (!$period): ?>
    <main class="max-w-xl mx-auto px-5 py-16">
        <div class="bg-white rounded-3xl shadow-xl border border-red-100 p-8 text-center">
            <div class="text-5xl mb-4">⚠️</div>
            <h1 class="text-2xl font-bold text-red-700">Link jadwal tidak valid / nonaktif</h1>
            <p class="mt-3 text-slate-600">Silakan hubungi admin keperawatan untuk mendapatkan link jadwal terbaru.</p>
        </div>
    </main>
<?php else: ?>
    <main class="max-w-7xl mx-auto px-4 py-6 md:py-10">
        <section class="bg-white rounded-3xl shadow-xl border border-blue-100 overflow-hidden">
            <div class="bg-gradient-to-r from-indigo-700 via-blue-700 to-cyan-600 p-6 md:p-8 text-white">
                <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-5">
                    <div>
                        <p class="uppercase tracking-[.25em] text-blue-100 text-xs font-semibold">RS BaliMéd Denpasar</p>
                        <h1 class="text-2xl md:text-4xl font-extrabold mt-2"><?= e($period['title']) ?></h1>
                        <p class="text-blue-100 mt-2">
                            <?= e(($period['unit_name'] ?: 'Unit Keperawatan')) ?> • <?= e(($monthNames[$month] ?? '-') . ' ' . $year) ?>
                        </p>
                    </div>
                    <?php if (defined('LOGO_URL')): ?>
                        <img src="<?= e(LOGO_URL) ?>" alt="Logo" class="h-14 md:h-16 bg-white rounded-2xl p-2 shadow">
                    <?php endif; ?>
                </div>
            </div>

            <div class="p-5 md:p-8">
                <div class="no-print grid grid-cols-1 lg:grid-cols-[1fr_auto] gap-4 mb-5 items-end">
                    <form method="get" class="rounded-2xl bg-slate-50 border border-slate-200 p-4">
                        <input type="hidden" name="t" value="<?= e($token) ?>">
                        <label class="block text-sm font-bold text-slate-700 mb-2">Pilih Bulan Jadwal</label>
                        <div class="flex flex-col sm:flex-row gap-3">
                            <select name="bulan_tahun" onchange="const v=this.value.split('-'); this.form.bulan.value=v[1]||''; this.form.tahun.value=v[0]||''; this.form.submit();" class="w-full sm:w-80 rounded-xl border border-slate-300 px-4 py-3 bg-white font-semibold focus:ring-2 focus:ring-blue-500 outline-none">
                                <?php foreach ($availablePeriods as $ap): ?>
                                    <?php $value = sprintf('%04d-%02d', (int)$ap['schedule_year'], (int)$ap['schedule_month']); ?>
                                    <option value="<?= e($value) ?>" <?= ((int)$ap['schedule_month'] === $month && (int)$ap['schedule_year'] === $year) ? 'selected' : '' ?>>
                                        <?= e(($monthNames[(int)$ap['schedule_month']] ?? '-') . ' ' . $ap['schedule_year']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <input type="hidden" name="bulan" value="<?= (int)$month ?>">
                            <input type="hidden" name="tahun" value="<?= (int)$year ?>">
                            <button type="submit" class="px-5 py-3 rounded-xl bg-blue-700 text-white font-semibold hover:bg-blue-800">Tampilkan</button>
                        </div>
                        <div class="mt-2 text-xs text-slate-500">Cukup share satu link ini. Bulan lain yang sudah dibuat akan muncul di pilihan ini.</div>
                    </form>
                    <button onclick="window.print()" class="px-5 py-3 rounded-xl bg-slate-900 text-white font-semibold hover:bg-slate-800">Print Jadwal</button>
                </div>

                <?php if (trim((string)$period['notes']) !== ''): ?>
                    <div class="mb-5 rounded-2xl bg-blue-50 border border-blue-100 p-4 text-blue-800 text-sm">
                        <strong>Catatan:</strong> <?= e($period['notes']) ?>
                    </div>
                <?php endif; ?>

                <?php if (!$rows): ?>
                    <div class="mb-5 rounded-2xl bg-amber-50 border border-amber-200 p-4 text-amber-800 text-sm">
                        Jadwal bulan ini belum memiliki baris perawat/bidan. Silakan pilih bulan lain atau hubungi admin keperawatan.
                    </div>
                <?php endif; ?>

                <div class="print-table-wrap overflow-auto rounded-2xl border border-slate-200">
                    <table class="print-schedule-table w-full min-w-[1200px] border-collapse text-xs md:text-sm">
                        <thead class="bg-slate-900 text-white">
                            <tr>
                                <th class="p-3 border border-slate-700 text-left sticky left-0 bg-slate-900 min-w-[230px]">Nama Perawat/Bidan</th>
                                <th class="p-3 border border-slate-700 text-left min-w-[130px]">Keterangan</th>
                                <?php for ($day = 1; $day <= $daysInMonth; $day++): ?>
                                    <?php $ts = strtotime(sprintf('%04d-%02d-%02d', $year, $month, $day)); ?>
                                    <th class="p-2 border border-slate-700 text-center min-w-[54px]">
                                        <div class="font-bold"><?= $day ?></div>
                                        <div class="text-[10px] text-slate-300"><?= e(substr($dayNames[(int)date('w', $ts)], 0, 3)) ?></div>
                                    </th>
                                <?php endfor; ?>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($rows as $row): ?>
                                <tr class="odd:bg-white even:bg-slate-50">
                                    <td class="p-3 border border-slate-200 font-bold sticky left-0 bg-inherit"><?= e($row['nurse_name']) ?></td>
                                    <td class="p-3 border border-slate-200 text-slate-600"><?= e($row['position_title'] ?: '-') ?></td>
                                    <?php for ($day = 1; $day <= $daysInMonth; $day++): ?>
                                        <?php
                                        $cell = $row['cells'][$day] ?? null;
                                        $shift = $cell ? trim((string)$cell['shift_code']) : '';
                                        $note = $cell ? trim((string)$cell['notes']) : '';
                                        ?>
                                        <td class="p-2 border border-slate-200 text-center <?= $shift !== '' ? 'bg-blue-50/60' : '' ?>">
                                            <div class="font-extrabold text-slate-800"><?= e($shift !== '' ? $shift : '-') ?></div>
                                            <?php if ($note !== ''): ?>
                                                <div class="text-[10px] text-slate-500 mt-1"><?= e($note) ?></div>
                                            <?php endif; ?>
                                        </td>
                                    <?php endfor; ?>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <div class="print-legend mt-6 grid grid-cols-1 lg:grid-cols-2 gap-4 text-xs md:text-sm">
                    <div class="rounded-2xl bg-blue-50 border border-blue-100 p-4">
                        <div class="font-extrabold text-blue-900 mb-3">Keterangan Shift</div>
                        <div class="grid grid-cols-2 md:grid-cols-3 gap-2">
                            <div class="rounded-xl bg-white border border-blue-100 p-3"><b>P</b> = Pagi</div>
                            <div class="rounded-xl bg-white border border-blue-100 p-3"><b>S</b> = Sore</div>
                            <div class="rounded-xl bg-white border border-blue-100 p-3"><b>M</b> = Malam</div>
                            <div class="rounded-xl bg-white border border-blue-100 p-3"><b>L/OFF</b> = Libur</div>
                            <div class="rounded-xl bg-white border border-blue-100 p-3"><b>CT</b> = Cuti</div>
                            <div class="rounded-xl bg-white border border-blue-100 p-3"><b>P1</b> = Pagi kode unit 1</div>
                        </div>
                    </div>
                    <div class="rounded-2xl bg-indigo-50 border border-indigo-100 p-4">
                        <div class="font-extrabold text-indigo-900 mb-3">Keterangan Kode Unit</div>
                        <div class="grid grid-cols-2 md:grid-cols-3 gap-2">
                            <?php foreach ($unitLegendItems as $item): ?>
                                <div class="rounded-xl bg-white border border-indigo-100 p-3">
                                    <?php if ($item['code'] !== ''): ?>
                                        <b><?= e($item['code']) ?></b> = <?= e($item['unit']) ?>
                                    <?php else: ?>
                                        <?= e($item['unit']) ?>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        <div class="mt-3 text-indigo-800"><strong>Contoh:</strong> P1 = Pagi IGD, S2 = Sore Canigara, M7 = Malam ICU.</div>
                    </div>
                </div>

                <p class="print-footer mt-6 text-xs text-slate-500 text-center">Dicetak/diakses dari link publik jadwal perawat RS BaliMéd Denpasar.</p>
            </div>
        </section>
    </main>
<?php endif; ?>
</body>
</html>
