<?php
declare(strict_types=1);

// jadwal_orientasi_public.php
// Halaman publik jadwal orientasi staf baru tanpa login.

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

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

$conn = 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'
];

$roomMap = [
    '1' => 'PAV CANIGARA', '2' => 'PAV CEMPAKA', '3' => 'RUANG IGD', '4' => 'RUANG ICU',
    '5' => 'POLIKLINIK', '6' => 'PAV CENDANA', '7' => 'HEMODIALISIS', '8' => 'KAMAR OPERASI', '9' => 'R. BAYI',
];

$token = trim((string)($_GET['t'] ?? ''));
$month = max(1, min(12, (int)($_GET['month'] ?? date('n'))));
$year = max(2024, min(2100, (int)($_GET['year'] ?? date('Y'))));
$daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$startDate = sprintf('%04d-%02d-01', $year, $month);
$endDate = sprintf('%04d-%02d-%02d', $year, $month, $daysInMonth);

$staff = null;
if ($token !== '') {
    $stmt = $conn->prepare("\n        SELECT os.id, os.employee_id, os.manual_name, os.manual_identifier, os.phone, os.unit_text, os.token,\n               e.full_name, e.nik, e.phone AS emp_phone, u.name AS unit_name\n        FROM orientation_staff os\n        LEFT JOIN employees e ON e.id = os.employee_id\n        LEFT JOIN units u ON u.id = e.unit_id\n        WHERE os.token = ? AND os.is_active = 1\n        LIMIT 1\n    ");
    if ($stmt) {
        $stmt->bind_param('s', $token);
        $stmt->execute();
        $res = $stmt->get_result();
        $staff = $res ? $res->fetch_assoc() : null;
        $stmt->close();
    }
}

$schedules = [];
if ($staff) {
    $staffId = (int)$staff['id'];
    $stmt = $conn->prepare("\n        SELECT schedule_date, shift_code, shift_label, room_code, notes\n        FROM orientation_schedules\n        WHERE staff_id = ? AND schedule_date BETWEEN ? AND ?\n        ORDER BY schedule_date ASC\n    ");
    if ($stmt) {
        $stmt->bind_param('iss', $staffId, $startDate, $endDate);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($res && ($row = $res->fetch_assoc())) {
            $day = (int)date('j', strtotime((string)$row['schedule_date']));
            $schedules[$day] = $row;
        }
        $stmt->close();
    }
}

$displayName = '-';
$identifier = '-';
$unitText = '-';
$phone = '-';
if ($staff) {
    $displayName = trim((string)($staff['full_name'] ?: $staff['manual_name'] ?: '-'));
    $identifier = trim((string)($staff['nik'] ?: $staff['manual_identifier'] ?: '-'));
    $unitText = trim((string)($staff['unit_name'] ?: $staff['unit_text'] ?: '-'));
    $phone = trim((string)($staff['emp_phone'] ?: $staff['phone'] ?: '-'));
}
?>
<!doctype html>
<html lang="id">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Jadwal Orientasi Staf Baru</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; }
        @media print { .no-print { display:none!important; } body { background:#fff!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 (!$staff): ?>
    <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</h1>
            <p class="mt-3 text-slate-600">Silakan hubungi admin keperawatan untuk mendapatkan link jadwal orientasi yang benar.</p>
        </div>
    </main>
<?php else: ?>
    <main class="max-w-6xl 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">Jadwal Orientasi Staf Baru</h1>
                        <p class="text-blue-100 mt-2">Bulan <?= e($monthNames[$month]) ?> <?= (int)$year ?></p>
                    </div>
                    <img src="<?= e(LOGO_URL) ?>" alt="Logo" class="h-14 md:h-16 bg-white rounded-2xl p-2 shadow">
                </div>
            </div>

            <div class="p-5 md:p-8">
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
                    <div class="rounded-2xl bg-slate-50 border border-slate-100 p-4">
                        <div class="text-xs text-slate-500">Nama</div>
                        <div class="font-bold text-slate-800 mt-1"><?= e($displayName) ?></div>
                    </div>
                    <div class="rounded-2xl bg-slate-50 border border-slate-100 p-4">
                        <div class="text-xs text-slate-500">NIK / Identitas</div>
                        <div class="font-bold text-slate-800 mt-1"><?= e($identifier) ?></div>
                    </div>
                    <div class="rounded-2xl bg-slate-50 border border-slate-100 p-4">
                        <div class="text-xs text-slate-500">Unit</div>
                        <div class="font-bold text-slate-800 mt-1"><?= e($unitText) ?></div>
                    </div>
                    <div class="rounded-2xl bg-slate-50 border border-slate-100 p-4">
                        <div class="text-xs text-slate-500">No. HP</div>
                        <div class="font-bold text-slate-800 mt-1"><?= e($phone) ?></div>
                    </div>
                </div>

                <div class="no-print flex flex-col md:flex-row md:items-center md:justify-between gap-3 mb-5">
                    <form method="get" class="flex flex-wrap gap-3 items-end">
                        <input type="hidden" name="t" value="<?= e($token) ?>">
                        <div>
                            <label class="block text-xs font-semibold text-slate-500 mb-1">Bulan</label>
                            <select name="month" class="rounded-xl border-slate-300">
                                <?php foreach ($monthNames as $num => $label): ?>
                                    <option value="<?= $num ?>" <?= $month === $num ? 'selected' : '' ?>><?= e($label) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div>
                            <label class="block text-xs font-semibold text-slate-500 mb-1">Tahun</label>
                            <input type="number" name="year" value="<?= (int)$year ?>" min="2024" max="2100" class="w-28 rounded-xl border-slate-300">
                        </div>
                        <button class="px-4 py-2 rounded-xl bg-blue-600 text-white font-semibold hover:bg-blue-700">Tampilkan</button>
                    </form>
                    <button onclick="window.print()" class="px-4 py-2 rounded-xl bg-slate-900 text-white font-semibold hover:bg-slate-800">Print Jadwal</button>
                </div>

                <div class="overflow-auto rounded-2xl border border-slate-200">
                    <table class="w-full min-w-[900px] border-collapse text-sm">
                        <thead class="bg-slate-900 text-white">
                            <tr>
                                <th class="p-3 border border-slate-700 text-left w-28">Tanggal</th>
                                <th class="p-3 border border-slate-700 text-left w-36">Hari</th>
                                <th class="p-3 border border-slate-700 text-center w-24">Kode</th>
                                <th class="p-3 border border-slate-700 text-left">Ruangan</th>
                                <th class="p-3 border border-slate-700 text-left">Catatan</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php for ($day = 1; $day <= $daysInMonth; $day++): ?>
                                <?php
                                $date = sprintf('%04d-%02d-%02d', $year, $month, $day);
                                $ts = strtotime($date);
                                $hari = ['Minggu','Senin','Selasa','Rabu','Kamis','Jumat','Sabtu'][(int)date('w', $ts)];
                                $row = $schedules[$day] ?? null;
                                $label = trim((string)($row['shift_label'] ?? ''));
                                $roomCode = trim((string)($row['room_code'] ?? ''));
                                $roomLabel = $roomCode !== '' && isset($roomMap[$roomCode]) ? $roomMap[$roomCode] : '-';
                                $notes = trim((string)($row['notes'] ?? ''));
                                ?>
                                <tr class="<?= $label === '' ? 'bg-white' : 'bg-blue-50/50' ?>">
                                    <td class="p-3 border border-slate-200 font-semibold"><?= sprintf('%02d-%02d-%04d', $day, $month, $year) ?></td>
                                    <td class="p-3 border border-slate-200"><?= e($hari) ?></td>
                                    <td class="p-3 border border-slate-200 text-center">
                                        <span class="inline-flex min-w-12 justify-center rounded-xl px-3 py-1 font-bold <?= $label === '' ? 'bg-slate-100 text-slate-400' : 'bg-blue-600 text-white' ?>"><?= e($label !== '' ? $label : '-') ?></span>
                                    </td>
                                    <td class="p-3 border border-slate-200"><?= e($roomLabel) ?></td>
                                    <td class="p-3 border border-slate-200"><?= e($notes !== '' ? $notes : '-') ?></td>
                                </tr>
                            <?php endfor; ?>
                        </tbody>
                    </table>
                </div>

                <div class="mt-6 grid grid-cols-2 md:grid-cols-5 gap-3 text-xs md:text-sm">
                    <div class="rounded-xl bg-blue-50 border border-blue-100 p-3"><b>P</b> = Pagi</div>
                    <div class="rounded-xl bg-amber-50 border border-amber-100 p-3"><b>S</b> = Sore</div>
                    <div class="rounded-xl bg-indigo-50 border border-indigo-100 p-3"><b>M</b> = Malam</div>
                    <div class="rounded-xl bg-pink-50 border border-pink-100 p-3"><b>PS</b> = PS</div>
                    <div class="rounded-xl bg-emerald-50 border border-emerald-100 p-3"><b>L/OFF</b> = Libur</div>
                </div>

                <p class="mt-6 text-xs text-slate-500 text-center">Link ini hanya untuk melihat jadwal. Staf tidak perlu login dan tidak dapat mengubah jadwal.</p>
            </div>
        </section>
    </main>
<?php endif; ?>
</body>
</html>
