<?php
declare(strict_types=1);

/**
 * Modul: Kalender Kegiatan Keperawatan
 * Lokasi: modules/kalender_kegiatan_keperawatan.php
 * Kompatibel dengan app perawat.itcprogram.com berbasis index.php include module.
 */

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

if (!function_exists('kk_is_mysqli')) {
    function kk_is_mysqli($conn): bool
    {
        return $conn instanceof mysqli;
    }
}

if (!function_exists('kk_is_pdo')) {
    function kk_is_pdo($conn): bool
    {
        return $conn instanceof PDO;
    }
}

if (!function_exists('kk_fetch_all')) {
    function kk_fetch_all($conn, string $sql, array $params = [], string $types = ''): array
    {
        try {
            if (kk_is_mysqli($conn)) {
                if (!$params) {
                    $res = $conn->query($sql);
                    return $res ? ($res->fetch_all(MYSQLI_ASSOC) ?: []) : [];
                }

                $stmt = $conn->prepare($sql);
                if (!$stmt) {
                    return [];
                }
                if ($types === '') {
                    $types = str_repeat('s', count($params));
                }
                $stmt->bind_param($types, ...$params);
                $stmt->execute();
                $res = $stmt->get_result();
                return $res ? ($res->fetch_all(MYSQLI_ASSOC) ?: []) : [];
            }

            if (kk_is_pdo($conn)) {
                $stmt = $conn->prepare($sql);
                $stmt->execute($params);
                return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
            }
        } catch (Throwable $e) {
            return [];
        }

        return [];
    }
}

if (!function_exists('kk_fetch_one')) {
    function kk_fetch_one($conn, string $sql, array $params = [], string $types = ''): ?array
    {
        $rows = kk_fetch_all($conn, $sql, $params, $types);
        return $rows[0] ?? null;
    }
}

if (!function_exists('kk_execute')) {
    function kk_execute($conn, string $sql, array $params = [], string $types = ''): bool
    {
        try {
            if (kk_is_mysqli($conn)) {
                if (!$params) {
                    return (bool)$conn->query($sql);
                }
                $stmt = $conn->prepare($sql);
                if (!$stmt) {
                    return false;
                }
                if ($types === '') {
                    $types = str_repeat('s', count($params));
                }
                $stmt->bind_param($types, ...$params);
                return $stmt->execute();
            }

            if (kk_is_pdo($conn)) {
                $stmt = $conn->prepare($sql);
                return $stmt->execute($params);
            }
        } catch (Throwable $e) {
            return false;
        }

        return false;
    }
}

if (!function_exists('kk_scalar')) {
    function kk_scalar($conn, string $sql, array $params = [], string $types = '', int $default = 0): int
    {
        $row = kk_fetch_one($conn, $sql, $params, $types);
        if (!$row) {
            return $default;
        }
        return (int)array_values($row)[0];
    }
}

if (!function_exists('kk_month_name_id')) {
    function kk_month_name_id(int $month): string
    {
        $names = [
            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 $names[$month] ?? '';
    }
}

if (!function_exists('kk_date_id')) {
    function kk_date_id(?string $date): string
    {
        if (!$date || $date === '0000-00-00') {
            return '-';
        }
        $ts = strtotime($date);
        if (!$ts) {
            return '-';
        }
        return date('d', $ts) . ' ' . kk_month_name_id((int)date('n', $ts)) . ' ' . date('Y', $ts);
    }
}

if (!function_exists('kk_time')) {
    function kk_time(?string $time): string
    {
        if (!$time || $time === '00:00:00') {
            return '-';
        }
        return substr($time, 0, 5);
    }
}

if (!function_exists('kk_badge')) {
    function kk_badge(string $value, string $type = 'status'): string
    {
        $v = strtolower(trim($value));
        $map = [
            'planned' => 'bg-blue-50 text-blue-700 border-blue-200',
            'ongoing' => 'bg-amber-50 text-amber-700 border-amber-200',
            'done' => 'bg-emerald-50 text-emerald-700 border-emerald-200',
            'cancelled' => 'bg-rose-50 text-rose-700 border-rose-200',
            'normal' => 'bg-slate-50 text-slate-700 border-slate-200',
            'important' => 'bg-purple-50 text-purple-700 border-purple-200',
            'urgent' => 'bg-red-50 text-red-700 border-red-200',
        ];
        $class = $map[$v] ?? 'bg-slate-50 text-slate-700 border-slate-200';
        $labelMap = [
            'planned' => 'Terjadwal',
            'ongoing' => 'Berjalan',
            'done' => 'Selesai',
            'cancelled' => 'Batal',
            'normal' => 'Normal',
            'important' => 'Penting',
            'urgent' => 'Urgent',
        ];
        $label = $labelMap[$v] ?? $value;
        return '<span class="inline-flex items-center px-2.5 py-1 rounded-full border text-xs font-bold ' . $class . '">' . kkh($label) . '</span>';
    }
}

// Ambil koneksi database dari index.php atau dari helper config/database.php.
// Modul di-include dari dalam function loadModule(), sehingga variabel $conn dari index.php
// kadang tidak otomatis masuk ke scope modul. Fallback ini mencegah error koneksi kosong.
if (!isset($conn) || !(($conn instanceof mysqli) || ($conn instanceof PDO))) {
    if (isset($GLOBALS['conn']) && (($GLOBALS['conn'] instanceof mysqli) || ($GLOBALS['conn'] instanceof PDO))) {
        $conn = $GLOBALS['conn'];
    } elseif (function_exists('getConnection')) {
        $conn = getConnection();
    } elseif (function_exists('getAppConnection')) {
        $conn = getAppConnection();
    } elseif (function_exists('db')) {
        $conn = db();
    } elseif (class_exists('Database')) {
        $database = new Database();
        if (method_exists($database, 'getConnection')) {
            $conn = $database->getConnection();
        } elseif (method_exists($database, 'connect')) {
            $conn = $database->connect();
        }
    }
}

if (!isset($conn) || !(($conn instanceof mysqli) || ($conn instanceof PDO))) {
    echo '<div class="p-4 rounded-xl bg-red-50 border border-red-200 text-red-700 font-semibold">Koneksi database belum tersedia. Pastikan config/database.php sudah berisi function getConnection().</div>';
    return;
}


$role = strtolower((string)($_SESSION['user_role'] ?? $_SESSION['user']['role'] ?? 'user'));
$isSuperAdmin = ($role === 'superadmin');
$isAdmin = in_array($role, ['admin', 'superadmin'], true);
$canManage = in_array($role, ['admin', 'superadmin', 'editor'], true);
$currentEmployeeId = (int)($_SESSION['employee_id'] ?? $_SESSION['user']['employee_id'] ?? $_SESSION['user_id'] ?? 0);
$currentName = (string)($_SESSION['full_name'] ?? $_SESSION['user']['full_name'] ?? $_SESSION['user']['nama'] ?? '');

$message = '';
$messageType = 'success';

$activityTypes = [
    'rapat' => 'Rapat',
    'supervisi' => 'Supervisi',
    'audit' => 'Audit',
    'pelatihan' => 'Pelatihan',
    'orientasi' => 'Orientasi',
    'morning_report' => 'Morning Report',
    'mutu' => 'Mutu & Akreditasi',
    'p3k' => 'P3K',
    'lainnya' => 'Lainnya',
];

$statusLabels = [
    'planned' => 'Terjadwal',
    'ongoing' => 'Berjalan',
    'done' => 'Selesai',
    'cancelled' => 'Batal',
];

$priorityLabels = [
    'normal' => 'Normal',
    'important' => 'Penting',
    'urgent' => 'Urgent',
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = trim((string)($_POST['action'] ?? ''));

    if ($action === 'save_event' && $canManage) {
        $id = (int)($_POST['id'] ?? 0);
        $title = trim((string)($_POST['title'] ?? ''));
        $activityType = trim((string)($_POST['activity_type'] ?? 'lainnya'));
        $eventDate = trim((string)($_POST['event_date'] ?? ''));
        $endDate = trim((string)($_POST['end_date'] ?? ''));
        $startTime = trim((string)($_POST['start_time'] ?? ''));
        $endTime = trim((string)($_POST['end_time'] ?? ''));
        $unitId = (int)($_POST['unit_id'] ?? 0);
        $picEmployeeId = (int)($_POST['pic_employee_id'] ?? 0);
        $location = trim((string)($_POST['location'] ?? ''));
        $status = trim((string)($_POST['status'] ?? 'planned'));
        $priority = trim((string)($_POST['priority'] ?? 'normal'));
        $visibility = trim((string)($_POST['visibility'] ?? 'all'));
        $description = trim((string)($_POST['description'] ?? ''));
        $notes = trim((string)($_POST['notes'] ?? ''));

        if (!isset($activityTypes[$activityType])) {
            $activityType = 'lainnya';
        }
        if (!isset($statusLabels[$status])) {
            $status = 'planned';
        }
        if (!isset($priorityLabels[$priority])) {
            $priority = 'normal';
        }
        if (!in_array($visibility, ['all', 'unit'], true)) {
            $visibility = 'all';
        }
        if ($endDate === '') {
            $endDate = $eventDate;
        }
        if ($startTime === '') {
            $startTime = null;
        }
        if ($endTime === '') {
            $endTime = null;
        }
        if ($unitId <= 0) {
            $unitId = null;
        }
        if ($picEmployeeId <= 0) {
            $picEmployeeId = null;
        }

        if ($title === '' || $eventDate === '') {
            $message = 'Judul kegiatan dan tanggal mulai wajib diisi.';
            $messageType = 'error';
        } elseif ($endDate < $eventDate) {
            $message = 'Tanggal selesai tidak boleh lebih awal dari tanggal mulai.';
            $messageType = 'error';
        } else {
            if ($id > 0) {
                $ok = kk_execute(
                    $conn,
                    "UPDATE nursing_calendar_events
                     SET title=?, activity_type=?, event_date=?, end_date=?, start_time=?, end_time=?, unit_id=?, pic_employee_id=?, location=?, status=?, priority=?, visibility=?, description=?, notes=?, updated_by=?, updated_at=NOW()
                     WHERE id=?",
                    [$title, $activityType, $eventDate, $endDate, $startTime, $endTime, $unitId, $picEmployeeId, $location, $status, $priority, $visibility, $description, $notes, $currentEmployeeId, $id],
                    'ssssssiissssssii'
                );
                $message = $ok ? 'Kegiatan berhasil diperbarui.' : 'Gagal memperbarui kegiatan.';
                $messageType = $ok ? 'success' : 'error';
            } else {
                $ok = kk_execute(
                    $conn,
                    "INSERT INTO nursing_calendar_events
                     (title, activity_type, event_date, end_date, start_time, end_time, unit_id, pic_employee_id, location, status, priority, visibility, description, notes, created_by, updated_by)
                     VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                    [$title, $activityType, $eventDate, $endDate, $startTime, $endTime, $unitId, $picEmployeeId, $location, $status, $priority, $visibility, $description, $notes, $currentEmployeeId, $currentEmployeeId],
                    'ssssssiissssssii'
                );
                $message = $ok ? 'Kegiatan berhasil ditambahkan ke kalender.' : 'Gagal menyimpan kegiatan.';
                $messageType = $ok ? 'success' : 'error';
            }
        }
    }

    if ($action === 'delete_event' && $isSuperAdmin) {
        $id = (int)($_POST['id'] ?? 0);
        $ok = $id > 0 ? kk_execute($conn, "DELETE FROM nursing_calendar_events WHERE id=?", [$id], 'i') : false;
        $message = $ok ? 'Kegiatan berhasil dihapus.' : 'Gagal menghapus kegiatan.';
        $messageType = $ok ? 'success' : 'error';
    }
}

$selectedMonth = trim((string)($_GET['month'] ?? date('Y-m')));
if (!preg_match('/^\d{4}-\d{2}$/', $selectedMonth)) {
    $selectedMonth = date('Y-m');
}
$monthStart = $selectedMonth . '-01';
$monthEnd = date('Y-m-t', strtotime($monthStart));
$prevMonth = date('Y-m', strtotime($monthStart . ' -1 month'));
$nextMonth = date('Y-m', strtotime($monthStart . ' +1 month'));

$filterType = trim((string)($_GET['type'] ?? ''));
$filterStatus = trim((string)($_GET['status'] ?? ''));
$filterUnit = (int)($_GET['unit_id'] ?? 0);
$q = trim((string)($_GET['q'] ?? ''));
$editId = (int)($_GET['edit'] ?? 0);

$units = kk_fetch_all($conn, "SELECT id, name FROM units WHERE is_active=1 ORDER BY name ASC");
$employees = kk_fetch_all($conn, "
    SELECT e.id, e.nik, e.full_name, COALESCE(u.name, '-') AS unit_name
    FROM employees e
    LEFT JOIN units u ON u.id=e.unit_id
    WHERE e.employment_status='aktif'
    ORDER BY e.full_name ASC
");

$where = ["e.event_date <= ?", "COALESCE(e.end_date, e.event_date) >= ?"];
$params = [$monthEnd, $monthStart];
$types = 'ss';

if ($filterType !== '' && isset($activityTypes[$filterType])) {
    $where[] = "e.activity_type=?";
    $params[] = $filterType;
    $types .= 's';
}
if ($filterStatus !== '' && isset($statusLabels[$filterStatus])) {
    $where[] = "e.status=?";
    $params[] = $filterStatus;
    $types .= 's';
}
if ($filterUnit > 0) {
    $where[] = "e.unit_id=?";
    $params[] = $filterUnit;
    $types .= 'i';
}
if ($q !== '') {
    $where[] = "(e.title LIKE ? OR e.location LIKE ? OR e.description LIKE ? OR emp.full_name LIKE ? OR u.name LIKE ?)";
    $like = '%' . $q . '%';
    array_push($params, $like, $like, $like, $like, $like);
    $types .= 'sssss';
}

$sqlEvents = "
    SELECT e.*, COALESCE(u.name, 'Semua Unit') AS unit_name,
           COALESCE(emp.full_name, '-') AS pic_name,
           COALESCE(emp.nik, '-') AS pic_nik
    FROM nursing_calendar_events e
    LEFT JOIN units u ON u.id=e.unit_id
    LEFT JOIN employees emp ON emp.id=e.pic_employee_id
    WHERE " . implode(' AND ', $where) . "
    ORDER BY e.event_date ASC, COALESCE(e.start_time, '00:00:00') ASC, e.id DESC
";
$events = kk_fetch_all($conn, $sqlEvents, $params, $types);

$editData = null;
if ($editId > 0 && $canManage) {
    $editData = kk_fetch_one($conn, "SELECT * FROM nursing_calendar_events WHERE id=?", [$editId], 'i');
}

$totalMonth = kk_scalar($conn, "SELECT COUNT(*) FROM nursing_calendar_events WHERE event_date <= ? AND COALESCE(end_date,event_date) >= ?", [$monthEnd, $monthStart], 'ss');
$totalToday = kk_scalar($conn, "SELECT COUNT(*) FROM nursing_calendar_events WHERE event_date <= CURDATE() AND COALESCE(end_date,event_date) >= CURDATE() AND status NOT IN ('done','cancelled')");
$totalUrgent = kk_scalar($conn, "SELECT COUNT(*) FROM nursing_calendar_events WHERE event_date <= ? AND COALESCE(end_date,event_date) >= ? AND priority='urgent' AND status NOT IN ('done','cancelled')", [$monthEnd, $monthStart], 'ss');
$totalDone = kk_scalar($conn, "SELECT COUNT(*) FROM nursing_calendar_events WHERE event_date <= ? AND COALESCE(end_date,event_date) >= ? AND status='done'", [$monthEnd, $monthStart], 'ss');

$eventsByDate = [];
foreach ($events as $ev) {
    $start = strtotime((string)$ev['event_date']);
    $end = strtotime((string)($ev['end_date'] ?: $ev['event_date']));
    if (!$start || !$end) continue;
    for ($ts = $start; $ts <= $end; $ts += 86400) {
        $day = date('Y-m-d', $ts);
        if ($day >= $monthStart && $day <= $monthEnd) {
            $eventsByDate[$day][] = $ev;
        }
    }
}

$firstWeekday = (int)date('N', strtotime($monthStart));
$daysInMonth = (int)date('t', strtotime($monthStart));
$calendarCells = [];
for ($i = 1; $i < $firstWeekday; $i++) {
    $calendarCells[] = null;
}
for ($d = 1; $d <= $daysInMonth; $d++) {
    $calendarCells[] = sprintf('%s-%02d', $selectedMonth, $d);
}
while (count($calendarCells) % 7 !== 0) {
    $calendarCells[] = null;
}

$form = [
    'id' => (int)($editData['id'] ?? 0),
    'title' => (string)($editData['title'] ?? ''),
    'activity_type' => (string)($editData['activity_type'] ?? 'rapat'),
    'event_date' => (string)($editData['event_date'] ?? date('Y-m-d')),
    'end_date' => (string)($editData['end_date'] ?? ''),
    'start_time' => $editData && !empty($editData['start_time']) ? substr((string)$editData['start_time'], 0, 5) : '',
    'end_time' => $editData && !empty($editData['end_time']) ? substr((string)$editData['end_time'], 0, 5) : '',
    'unit_id' => (int)($editData['unit_id'] ?? 0),
    'pic_employee_id' => (int)($editData['pic_employee_id'] ?? 0),
    'location' => (string)($editData['location'] ?? ''),
    'status' => (string)($editData['status'] ?? 'planned'),
    'priority' => (string)($editData['priority'] ?? 'normal'),
    'visibility' => (string)($editData['visibility'] ?? 'all'),
    'description' => (string)($editData['description'] ?? ''),
    'notes' => (string)($editData['notes'] ?? ''),
];
?>
<style>
    .kk-card { background:#fff; border:1px solid #e2e8f0; border-radius:24px; box-shadow:0 14px 36px rgba(15,23,42,.06); }
    .kk-hero { background:linear-gradient(135deg,#0ea5e9,#2563eb,#7c3aed); border-radius:28px; color:#fff; overflow:hidden; position:relative; }
    .kk-hero::after { content:''; position:absolute; width:240px; height:240px; border-radius:999px; background:rgba(255,255,255,.10); right:-80px; top:-90px; }
    .kk-input { width:100%; border:1px solid #cbd5e1; border-radius:14px; padding:.78rem .9rem; background:#fff; outline:none; transition:.15s; }
    .kk-input:focus { border-color:#2563eb; box-shadow:0 0 0 4px rgba(37,99,235,.10); }
    .kk-label { display:block; font-size:.76rem; font-weight:800; color:#334155; text-transform:uppercase; letter-spacing:.03em; margin-bottom:.35rem; }
    .kk-btn { display:inline-flex; align-items:center; justify-content:center; gap:.45rem; border-radius:14px; padding:.78rem 1rem; font-weight:800; transition:.18s; text-decoration:none; border:1px solid transparent; }
    .kk-btn:hover { transform:translateY(-1px); }
    .kk-btn-primary { color:#fff; background:linear-gradient(135deg,#2563eb,#4f46e5); box-shadow:0 12px 24px rgba(37,99,235,.18); }
    .kk-btn-soft { color:#1e293b; background:#f8fafc; border-color:#e2e8f0; }
    .kk-day { min-height:132px; border:1px solid #e2e8f0; background:#fff; padding:.65rem; vertical-align:top; }
    .kk-day.today { background:linear-gradient(180deg,#eff6ff,#fff); border-color:#93c5fd; }
    .kk-event { display:block; border-left:4px solid #2563eb; background:#f8fafc; border-radius:12px; padding:.5rem .55rem; margin-top:.45rem; font-size:.76rem; line-height:1.25; color:#0f172a; }
    .kk-event.urgent { border-left-color:#ef4444; background:#fff1f2; }
    .kk-event.important { border-left-color:#7c3aed; background:#f5f3ff; }
    .kk-table th { background:#f8fafc; color:#475569; font-size:.76rem; text-transform:uppercase; letter-spacing:.03em; }
    .kk-table th, .kk-table td { padding:.9rem; border-bottom:1px solid #e2e8f0; vertical-align:top; }
    @media print { .kk-no-print, .top-bar { display:none!important; } body { background:#fff!important; overflow:visible!important; } .content-area { padding:0!important; } .kk-card, .kk-hero { box-shadow:none!important; } }
</style>

<div class="space-y-6">
    <div class="kk-hero p-6 md:p-8 kk-no-print">
        <div class="relative z-10 flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
            <div>
                <div class="text-sm font-bold uppercase tracking-wider text-blue-100 mb-2">Kalender Bersama Divisi Keperawatan</div>
                <h2 class="text-2xl md:text-4xl font-extrabold leading-tight">Kalender Kegiatan Keperawatan</h2>
                <p class="mt-2 text-blue-50 max-w-3xl">Satu halaman untuk memantau rapat, supervisi, audit, pelatihan, orientasi, P3K, dan kegiatan penting lain agar semua tim tahu jadwal kegiatan.</p>
            </div>
            <div class="flex flex-wrap gap-2">
                <a href="index.php?module=kalender_kegiatan_keperawatan&month=<?= kkh($prevMonth) ?>" class="kk-btn bg-white/15 text-white border-white/20"><i class="fas fa-chevron-left"></i> Bulan Sebelumnya</a>
                <a href="index.php?module=kalender_kegiatan_keperawatan&month=<?= date('Y-m') ?>" class="kk-btn bg-white text-blue-700"><i class="fas fa-calendar-day"></i> Bulan Ini</a>
                <a href="index.php?module=kalender_kegiatan_keperawatan&month=<?= kkh($nextMonth) ?>" class="kk-btn bg-white/15 text-white border-white/20">Bulan Berikutnya <i class="fas fa-chevron-right"></i></a>
            </div>
        </div>
    </div>

    <?php if ($message !== ''): ?>
        <div class="kk-no-print rounded-2xl border p-4 font-semibold <?= $messageType === 'success' ? 'bg-emerald-50 border-emerald-200 text-emerald-700' : 'bg-red-50 border-red-200 text-red-700' ?>">
            <?= kkh($message) ?>
        </div>
    <?php endif; ?>

    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 kk-no-print">
        <div class="kk-card p-5"><div class="text-xs font-bold text-slate-500 uppercase">Total Bulan Ini</div><div class="text-3xl font-extrabold text-slate-900 mt-1"><?= (int)$totalMonth ?></div></div>
        <div class="kk-card p-5"><div class="text-xs font-bold text-blue-600 uppercase">Kegiatan Hari Ini</div><div class="text-3xl font-extrabold text-blue-700 mt-1"><?= (int)$totalToday ?></div></div>
        <div class="kk-card p-5"><div class="text-xs font-bold text-red-600 uppercase">Urgent Aktif</div><div class="text-3xl font-extrabold text-red-700 mt-1"><?= (int)$totalUrgent ?></div></div>
        <div class="kk-card p-5"><div class="text-xs font-bold text-emerald-600 uppercase">Selesai Bulan Ini</div><div class="text-3xl font-extrabold text-emerald-700 mt-1"><?= (int)$totalDone ?></div></div>
    </div>

    <div class="grid grid-cols-1 xl:grid-cols-12 gap-6">
        <div class="xl:col-span-8 space-y-6">
            <div class="kk-card p-5 kk-no-print">
                <form method="get" class="grid grid-cols-1 md:grid-cols-7 gap-3 items-end">
                    <input type="hidden" name="module" value="kalender_kegiatan_keperawatan">
                    <div>
                        <label class="kk-label">Bulan</label>
                        <input type="month" name="month" value="<?= kkh($selectedMonth) ?>" class="kk-input">
                    </div>
                    <div>
                        <label class="kk-label">Jenis</label>
                        <select name="type" class="kk-input">
                            <option value="">Semua Jenis</option>
                            <?php foreach ($activityTypes as $key => $label): ?>
                                <option value="<?= kkh($key) ?>" <?= $filterType === $key ? 'selected' : '' ?>><?= kkh($label) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="kk-label">Status</label>
                        <select name="status" class="kk-input">
                            <option value="">Semua Status</option>
                            <?php foreach ($statusLabels as $key => $label): ?>
                                <option value="<?= kkh($key) ?>" <?= $filterStatus === $key ? 'selected' : '' ?>><?= kkh($label) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="kk-label">Unit</label>
                        <select name="unit_id" class="kk-input">
                            <option value="0">Semua Unit</option>
                            <?php foreach ($units as $u): ?>
                                <option value="<?= (int)$u['id'] ?>" <?= $filterUnit === (int)$u['id'] ? 'selected' : '' ?>><?= kkh($u['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="md:col-span-2">
                        <label class="kk-label">Pencarian</label>
                        <input type="text" name="q" value="<?= kkh($q) ?>" class="kk-input" placeholder="Cari judul, lokasi, PIC, unit...">
                    </div>
                    <div class="flex gap-2">
                        <button class="kk-btn kk-btn-primary w-full" type="submit"><i class="fas fa-filter"></i> Filter</button>
                        <button class="kk-btn kk-btn-soft" type="button" onclick="window.print()"><i class="fas fa-print"></i></button>
                    </div>
                </form>
            </div>

            <div class="kk-card overflow-hidden">
                <div class="p-5 border-b border-slate-200 flex items-center justify-between gap-3 flex-wrap">
                    <div>
                        <h3 class="text-xl font-extrabold text-slate-900">Kalender <?= kk_month_name_id((int)date('n', strtotime($monthStart))) ?> <?= date('Y', strtotime($monthStart)) ?></h3>
                        <p class="text-sm text-slate-500">Klik tombol edit pada daftar kegiatan untuk mengubah agenda.</p>
                    </div>
                    <div class="text-sm text-slate-500 font-semibold"><?= count($events) ?> agenda tampil</div>
                </div>
                <div class="overflow-x-auto">
                    <table class="w-full border-collapse" style="min-width:980px;">
                        <thead>
                            <tr class="bg-slate-50">
                                <?php foreach (['Senin','Selasa','Rabu','Kamis','Jumat','Sabtu','Minggu'] as $dayName): ?>
                                    <th class="p-3 text-sm font-extrabold text-slate-600 border border-slate-200 text-left"><?= $dayName ?></th>
                                <?php endforeach; ?>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach (array_chunk($calendarCells, 7) as $week): ?>
                                <tr>
                                    <?php foreach ($week as $day): ?>
                                        <?php $isToday = $day === date('Y-m-d'); ?>
                                        <td class="kk-day <?= $isToday ? 'today' : '' ?>">
                                            <?php if ($day): ?>
                                                <div class="flex items-center justify-between">
                                                    <div class="font-extrabold <?= $isToday ? 'text-blue-700' : 'text-slate-700' ?>"><?= (int)date('d', strtotime($day)) ?></div>
                                                    <?php if ($isToday): ?><span class="text-[10px] font-bold bg-blue-600 text-white rounded-full px-2 py-0.5">Hari ini</span><?php endif; ?>
                                                </div>
                                                <?php foreach (array_slice($eventsByDate[$day] ?? [], 0, 4) as $ev): ?>
                                                    <div class="kk-event <?= kkh((string)$ev['priority']) ?>" title="<?= kkh((string)$ev['title']) ?>">
                                                        <div class="font-extrabold truncate"><?= kkh((string)$ev['title']) ?></div>
                                                        <div class="text-slate-500 mt-0.5"><i class="far fa-clock"></i> <?= kkh(kk_time($ev['start_time'] ?? null)) ?> • <?= kkh($activityTypes[$ev['activity_type']] ?? $ev['activity_type']) ?></div>
                                                        <div class="text-slate-500 truncate"><i class="fas fa-map-marker-alt"></i> <?= kkh($ev['location'] ?: '-') ?></div>
                                                    </div>
                                                <?php endforeach; ?>
                                                <?php if (count($eventsByDate[$day] ?? []) > 4): ?>
                                                    <div class="mt-2 text-xs font-bold text-slate-500">+<?= count($eventsByDate[$day]) - 4 ?> agenda lagi</div>
                                                <?php endif; ?>
                                            <?php endif; ?>
                                        </td>
                                    <?php endforeach; ?>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="xl:col-span-4 kk-no-print">
            <div class="kk-card p-5 sticky top-24">
                <div class="flex items-start justify-between gap-3 mb-4">
                    <div>
                        <h3 class="text-xl font-extrabold text-slate-900"><?= $form['id'] > 0 ? 'Edit Kegiatan' : 'Input Kegiatan' ?></h3>
                        <p class="text-sm text-slate-500">Isi agenda agar terbaca semua tim.</p>
                    </div>
                    <?php if ($form['id'] > 0): ?>
                        <a class="kk-btn kk-btn-soft py-2" href="index.php?module=kalender_kegiatan_keperawatan&month=<?= kkh($selectedMonth) ?>">Baru</a>
                    <?php endif; ?>
                </div>

                <?php if (!$canManage): ?>
                    <div class="rounded-2xl bg-slate-50 border border-slate-200 p-4 text-slate-600 font-semibold">Akun ini hanya dapat melihat kalender kegiatan.</div>
                <?php else: ?>
                <form method="post" class="space-y-3">
                    <input type="hidden" name="action" value="save_event">
                    <input type="hidden" name="id" value="<?= (int)$form['id'] ?>">

                    <div>
                        <label class="kk-label">Judul Kegiatan</label>
                        <input type="text" name="title" required value="<?= kkh($form['title']) ?>" class="kk-input" placeholder="Contoh: Rapat Koordinasi Kepala Unit">
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <div>
                            <label class="kk-label">Jenis</label>
                            <select name="activity_type" class="kk-input">
                                <?php foreach ($activityTypes as $key => $label): ?>
                                    <option value="<?= kkh($key) ?>" <?= $form['activity_type'] === $key ? 'selected' : '' ?>><?= kkh($label) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div>
                            <label class="kk-label">Prioritas</label>
                            <select name="priority" class="kk-input">
                                <?php foreach ($priorityLabels as $key => $label): ?>
                                    <option value="<?= kkh($key) ?>" <?= $form['priority'] === $key ? 'selected' : '' ?>><?= kkh($label) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <div>
                            <label class="kk-label">Tanggal Mulai</label>
                            <input type="date" name="event_date" required value="<?= kkh($form['event_date']) ?>" class="kk-input">
                        </div>
                        <div>
                            <label class="kk-label">Tanggal Selesai</label>
                            <input type="date" name="end_date" value="<?= kkh($form['end_date']) ?>" class="kk-input">
                        </div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <div>
                            <label class="kk-label">Jam Mulai</label>
                            <input type="time" name="start_time" value="<?= kkh($form['start_time']) ?>" class="kk-input">
                        </div>
                        <div>
                            <label class="kk-label">Jam Selesai</label>
                            <input type="time" name="end_time" value="<?= kkh($form['end_time']) ?>" class="kk-input">
                        </div>
                    </div>

                    <div>
                        <label class="kk-label">Unit Terkait</label>
                        <select name="unit_id" class="kk-input">
                            <option value="0">Semua Unit / Divisi Keperawatan</option>
                            <?php foreach ($units as $u): ?>
                                <option value="<?= (int)$u['id'] ?>" <?= $form['unit_id'] === (int)$u['id'] ? 'selected' : '' ?>><?= kkh($u['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div>
                        <label class="kk-label">PIC / Penanggung Jawab</label>
                        <select name="pic_employee_id" class="kk-input">
                            <option value="0">- Pilih PIC -</option>
                            <?php foreach ($employees as $emp): ?>
                                <option value="<?= (int)$emp['id'] ?>" <?= $form['pic_employee_id'] === (int)$emp['id'] ? 'selected' : '' ?>><?= kkh($emp['full_name']) ?> — <?= kkh($emp['unit_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div>
                        <label class="kk-label">Lokasi</label>
                        <input type="text" name="location" value="<?= kkh($form['location']) ?>" class="kk-input" placeholder="Ruang rapat, aula, unit, dll">
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <div>
                            <label class="kk-label">Status</label>
                            <select name="status" class="kk-input">
                                <?php foreach ($statusLabels as $key => $label): ?>
                                    <option value="<?= kkh($key) ?>" <?= $form['status'] === $key ? 'selected' : '' ?>><?= kkh($label) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div>
                            <label class="kk-label">Visibilitas</label>
                            <select name="visibility" class="kk-input">
                                <option value="all" <?= $form['visibility'] === 'all' ? 'selected' : '' ?>>Semua Tim</option>
                                <option value="unit" <?= $form['visibility'] === 'unit' ? 'selected' : '' ?>>Unit Terkait</option>
                            </select>
                        </div>
                    </div>

                    <div>
                        <label class="kk-label">Deskripsi Kegiatan</label>
                        <textarea name="description" rows="4" class="kk-input" placeholder="Detail kegiatan, agenda, atau informasi penting..."><?= kkh($form['description']) ?></textarea>
                    </div>

                    <div>
                        <label class="kk-label">Catatan Internal</label>
                        <textarea name="notes" rows="2" class="kk-input" placeholder="Catatan tambahan bila ada..."><?= kkh($form['notes']) ?></textarea>
                    </div>

                    <button type="submit" class="kk-btn kk-btn-primary w-full"><i class="fas fa-save"></i> Simpan Kegiatan</button>
                </form>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="kk-card overflow-hidden">
        <div class="p-5 border-b border-slate-200 flex items-center justify-between gap-3 flex-wrap">
            <div>
                <h3 class="text-xl font-extrabold text-slate-900">Daftar Kegiatan</h3>
                <p class="text-sm text-slate-500">Rekap kegiatan sesuai filter bulan.</p>
            </div>
        </div>
        <div class="overflow-x-auto">
            <table class="w-full kk-table" style="min-width:1100px;">
                <thead>
                    <tr>
                        <th class="text-left">Tanggal</th>
                        <th class="text-left">Kegiatan</th>
                        <th class="text-left">Jenis</th>
                        <th class="text-left">Unit</th>
                        <th class="text-left">PIC</th>
                        <th class="text-left">Status</th>
                        <th class="text-left">Prioritas</th>
                        <th class="text-left kk-no-print">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!$events): ?>
                        <tr><td colspan="8" class="text-center text-slate-500 py-8">Belum ada kegiatan pada periode ini.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($events as $ev): ?>
                        <tr>
                            <td>
                                <div class="font-extrabold text-slate-800"><?= kkh(kk_date_id($ev['event_date'])) ?></div>
                                <?php if (!empty($ev['end_date']) && $ev['end_date'] !== $ev['event_date']): ?>
                                    <div class="text-xs text-slate-500">s/d <?= kkh(kk_date_id($ev['end_date'])) ?></div>
                                <?php endif; ?>
                                <div class="text-xs text-slate-500 mt-1"><?= kkh(kk_time($ev['start_time'] ?? null)) ?> - <?= kkh(kk_time($ev['end_time'] ?? null)) ?></div>
                            </td>
                            <td>
                                <div class="font-extrabold text-slate-900"><?= kkh($ev['title']) ?></div>
                                <div class="text-sm text-slate-500 mt-1"><i class="fas fa-map-marker-alt"></i> <?= kkh($ev['location'] ?: '-') ?></div>
                                <?php if (!empty($ev['description'])): ?><div class="text-sm text-slate-600 mt-1 max-w-lg"><?= nl2br(kkh($ev['description'])) ?></div><?php endif; ?>
                            </td>
                            <td><?= kkh($activityTypes[$ev['activity_type']] ?? $ev['activity_type']) ?></td>
                            <td><?= kkh($ev['unit_name']) ?></td>
                            <td>
                                <div class="font-bold text-slate-800"><?= kkh($ev['pic_name']) ?></div>
                                <div class="text-xs text-slate-500">NIK: <?= kkh($ev['pic_nik']) ?></div>
                            </td>
                            <td><?= kk_badge((string)$ev['status']) ?></td>
                            <td><?= kk_badge((string)$ev['priority']) ?></td>
                            <td class="kk-no-print">
                                <div class="flex flex-wrap gap-2">
                                    <?php if ($canManage): ?>
                                        <a class="kk-btn kk-btn-soft py-2" href="index.php?module=kalender_kegiatan_keperawatan&month=<?= kkh($selectedMonth) ?>&edit=<?= (int)$ev['id'] ?>"><i class="fas fa-edit text-amber-500"></i> Edit</a>
                                    <?php endif; ?>
                                    <?php if ($isSuperAdmin): ?>
                                        <form method="post" onsubmit="return confirm('Yakin hapus kegiatan ini?')">
                                            <input type="hidden" name="action" value="delete_event">
                                            <input type="hidden" name="id" value="<?= (int)$ev['id'] ?>">
                                            <button class="kk-btn py-2 bg-red-50 text-red-700 border-red-200" type="submit"><i class="fas fa-trash"></i> Hapus</button>
                                        </form>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
