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

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

if (function_exists('checkAuth')) {
    checkAuth();
}

$conn = getConnection();

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

if (!function_exists('current_user_id')) {
    function current_user_id(): int {
        return (int)($_SESSION['user_id'] ?? $_SESSION['user']['id'] ?? 0);
    }
}

function p3k_units(): array {
    return ["IGD", "Canigara", "Cempaka", "Cendana", "VK", "OK", "ICU", "Poli", "HD", "Bayi"];
}

function generate_request_code(): string {
    return 'REQ-' . date('YmdHis') . '-' . rand(100, 999);
}

function schedule_exists(mysqli $conn, string $date): bool {
    $stmt = $conn->prepare("SELECT id FROM p3k_schedule WHERE schedule_date = ? LIMIT 1");
    $stmt->bind_param("s", $date);
    $stmt->execute();
    $res = $stmt->get_result();
    return $res && $res->num_rows > 0;
}

function generate_annual_schedule(mysqli $conn, int $year): void {
    $units = p3k_units();

    $start = new DateTime($year . '-01-01');
    $end = new DateTime(($year + 1) . '-01-01');

    for ($date = clone $start; $date < $end; $date->modify('+1 day')) {
        $currentDate = $date->format('Y-m-d');

        if (schedule_exists($conn, $currentDate)) {
            continue;
        }

        $shuffled = $units;
        shuffle($shuffled);
        $assigned = array_slice($shuffled, 0, 3);

        $stmt = $conn->prepare("
            INSERT INTO p3k_schedule (schedule_date, unit_1, unit_2, unit_3)
            VALUES (?, ?, ?, ?)
        ");
        $stmt->bind_param("ssss", $currentDate, $assigned[0], $assigned[1], $assigned[2]);
        $stmt->execute();
    }
}

function get_schedule_for_date(mysqli $conn, string $date): ?array {
    $stmt = $conn->prepare("
        SELECT schedule_date, unit_1, unit_2, unit_3
        FROM p3k_schedule
        WHERE schedule_date = ?
        LIMIT 1
    ");
    $stmt->bind_param("s", $date);
    $stmt->execute();
    $res = $stmt->get_result();
    $row = $res ? $res->fetch_assoc() : null;

    if (!$row) return null;

    return [
        'date' => $row['schedule_date'],
        'units' => [$row['unit_1'], $row['unit_2'], $row['unit_3']]
    ];
}

function get_open_requests(mysqli $conn): array {
    $rows = [];
    $sql = "SELECT * FROM p3k_requests WHERE status = 'open' ORDER BY tanggal ASC, waktu_mulai ASC, id ASC";
    $res = $conn->query($sql);
    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $rows[] = $row;
        }
    }
    return $rows;
}

function get_assignment_history(mysqli $conn, int $limit = 10): array {
    $rows = [];
    $stmt = $conn->prepare("
        SELECT kegiatan, tanggal, nurse_names, nurse_units, nurse_phones, assigned_at
        FROM p3k_requests
        WHERE status = 'assigned'
        ORDER BY assigned_at DESC, id DESC
        LIMIT ?
    ");
    $stmt->bind_param("i", $limit);
    $stmt->execute();
    $res = $stmt->get_result();
    while ($row = $res->fetch_assoc()) {
        $rows[] = $row;
    }
    return $rows;
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $postAction = $_POST['post_action'] ?? '';

    if ($postAction === 'generate_schedule') {
        $year = (int)($_POST['year'] ?? date('Y'));
        generate_annual_schedule($conn, $year);
        $message = "Jadwal tahun {$year} berhasil dibuat.";
    }

    if ($postAction === 'save_request') {
        $divisi        = trim($_POST['divisi'] ?? '');
        $kegiatan      = trim($_POST['kegiatan'] ?? '');
        $penyelenggara = trim($_POST['penyelenggara'] ?? '');
        $tanggal       = trim($_POST['tanggal'] ?? '');
        $waktuMulai    = trim($_POST['waktu_mulai'] ?? '');
        $waktuSelesai  = trim($_POST['waktu_selesai'] ?? '');
        $lokasi        = trim($_POST['lokasi'] ?? '');
        $jumlahStaf    = (int)($_POST['jumlah_staf'] ?? 1);
        $jumlahPeserta = (int)($_POST['jumlah_peserta'] ?? 0);
        $alat          = trim($_POST['alat'] ?? '');

        if (
            $divisi === '' || $kegiatan === '' || $penyelenggara === '' ||
            $tanggal === '' || $waktuMulai === '' || $waktuSelesai === '' || $lokasi === ''
        ) {
            $message = 'Semua field wajib harus diisi.';
            $messageType = 'error';
        } else {
            $requestCode = generate_request_code();

            $stmt = $conn->prepare("
                INSERT INTO p3k_requests
                (request_code, divisi, kegiatan, penyelenggara, tanggal, waktu_mulai, waktu_selesai, lokasi, jumlah_staf, jumlah_peserta, alat, status)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'open')
            ");
            $stmt->bind_param(
                "ssssssssiis",
                $requestCode,
                $divisi,
                $kegiatan,
                $penyelenggara,
                $tanggal,
                $waktuMulai,
                $waktuSelesai,
                $lokasi,
                $jumlahStaf,
                $jumlahPeserta,
                $alat
            );

            if ($stmt->execute()) {
                $message = "Permintaan berhasil dikirim. Kode: {$requestCode}";
            } else {
                $message = "Gagal menyimpan data: " . $stmt->error;
                $messageType = 'error';
            }
        }
    }

    if ($postAction === 'assign_request') {
        $requestId = (int)($_POST['request_id'] ?? 0);

        $nurseNames  = $_POST['nurse_name'] ?? [];
        $nurseUnits  = $_POST['nurse_unit'] ?? [];
        $nursePhones = $_POST['nurse_phone'] ?? [];

        $validNames = [];
        $validUnits = [];
        $validPhones = [];

        $total = max(count($nurseNames), count($nurseUnits), count($nursePhones));

        for ($i = 0; $i < $total; $i++) {
            $nama = trim($nurseNames[$i] ?? '');
            $unit = trim($nurseUnits[$i] ?? '');
            $telp = trim($nursePhones[$i] ?? '');

            if ($nama !== '' && $unit !== '' && $telp !== '') {
                $validNames[] = $nama;
                $validUnits[] = $unit;
                $validPhones[] = $telp;
            }
        }

        if ($requestId <= 0 || count($validNames) === 0) {
            $message = 'Data penugasan belum lengkap.';
            $messageType = 'error';
        } else {
            $joinedNames  = implode("\n", $validNames);
            $joinedUnits  = implode("\n", $validUnits);
            $joinedPhones = implode("\n", $validPhones);
            $assignedBy   = current_user_id();

            $stmt = $conn->prepare("
                UPDATE p3k_requests
                SET nurse_names = ?, nurse_units = ?, nurse_phones = ?, status = 'assigned',
                    assigned_at = NOW(), assigned_by = ?
                WHERE id = ?
            ");
            $stmt->bind_param("sssii", $joinedNames, $joinedUnits, $joinedPhones, $assignedBy, $requestId);

            if ($stmt->execute()) {
                $message = 'Perawat berhasil ditugaskan.';
            } else {
                $message = 'Gagal menugaskan perawat: ' . $stmt->error;
                $messageType = 'error';
            }
        }
    }
}

$selectedDate = $_GET['schedule_date'] ?? date('Y-m-d');
$scheduleData = get_schedule_for_date($conn, $selectedDate);
$openRequests = get_open_requests($conn);
$historyRows  = get_assignment_history($conn, 10);
?>

<div class="space-y-6">
    <div class="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden">
        <div class="p-6 bg-gradient-to-r from-blue-600 to-indigo-600 text-white">
            <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
                <div>
                    <h1 class="text-2xl font-bold">Penugasan P3K</h1>
                    <p class="text-blue-100 mt-1">Jadwal unit PJ P3K, permintaan kegiatan, dan penugasan perawat.</p>
                </div>
                <img src="<?= defined('LOGO_URL') ? LOGO_URL : 'https://balimedhospital.co.id/wp-content/uploads/elementor/thumbs/logo-dark-o9cm6tnx14hcrnest1hge1pwnqj0yaumij7qohadlm.png' ?>" class="h-14 w-auto bg-white rounded-xl p-2" alt="Logo">
            </div>
        </div>

        <div class="p-6">
            <?php if ($message !== ''): ?>
                <div class="mb-4 rounded-xl px-4 py-3 <?= $messageType === 'error' ? 'bg-red-50 text-red-700 border border-red-200' : 'bg-green-50 text-green-700 border border-green-200' ?>">
                    <?= e($message) ?>
                </div>
            <?php endif; ?>

            <div class="flex flex-wrap gap-2 mb-6">
                <button type="button" class="tab-btn active px-4 py-2 rounded-xl border bg-blue-600 text-white" data-tab="tab-dashboard">Dashboard</button>
                <button type="button" class="tab-btn px-4 py-2 rounded-xl border" data-tab="tab-form">Form Permintaan</button>
                <button type="button" class="tab-btn px-4 py-2 rounded-xl border" data-tab="tab-schedule">Jadwal</button>
                <button type="button" class="tab-btn px-4 py-2 rounded-xl border" data-tab="tab-history">Riwayat</button>
            </div>

            <div id="tab-dashboard" class="tab-content space-y-6">
                <div class="grid grid-cols-1 xl:grid-cols-3 gap-6">
                    <div class="xl:col-span-2 bg-slate-50 border rounded-2xl p-5">
                        <div class="flex items-center justify-between mb-4">
                            <h2 class="text-xl font-bold text-slate-800">Permintaan P3K Masuk</h2>
                            <span class="text-sm bg-blue-100 text-blue-700 px-3 py-1 rounded-full"><?= count($openRequests) ?> request</span>
                        </div>

                        <?php if (empty($openRequests)): ?>
                            <div class="rounded-xl bg-green-50 border border-green-200 text-green-700 p-4">
                                Tidak ada permintaan P3K yang belum ditugaskan.
                            </div>
                        <?php else: ?>
                            <div class="space-y-5">
                                <?php foreach ($openRequests as $req): ?>
                                    <div class="bg-white rounded-2xl border border-slate-200 p-5 shadow-sm">
                                        <div class="flex flex-col lg:flex-row lg:items-start lg:justify-between gap-4">
                                            <div>
                                                <h3 class="text-lg font-bold text-slate-800"><?= e($req['kegiatan']) ?></h3>
                                                <p class="text-sm text-slate-500"><?= e($req['divisi']) ?> กค <?= e($req['penyelenggara']) ?></p>
                                            </div>
                                            <div class="text-sm bg-yellow-50 text-yellow-700 px-3 py-1 rounded-full border border-yellow-200">
                                                <?= e($req['request_code']) ?>
                                            </div>
                                        </div>

                                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mt-4 text-sm">
                                            <div class="bg-slate-50 rounded-xl p-3">
                                                <div class="text-slate-500">Tanggal</div>
                                                <div class="font-semibold"><?= date('d-m-Y', strtotime($req['tanggal'])) ?></div>
                                            </div>
                                            <div class="bg-slate-50 rounded-xl p-3">
                                                <div class="text-slate-500">Waktu</div>
                                                <div class="font-semibold"><?= substr($req['waktu_mulai'], 0, 5) ?> - <?= substr($req['waktu_selesai'], 0, 5) ?></div>
                                            </div>
                                            <div class="bg-slate-50 rounded-xl p-3">
                                                <div class="text-slate-500">Lokasi</div>
                                                <div class="font-semibold"><?= e($req['lokasi']) ?></div>
                                            </div>
                                            <div class="bg-slate-50 rounded-xl p-3">
                                                <div class="text-slate-500">Butuh Staf</div>
                                                <div class="font-semibold"><?= (int)$req['jumlah_staf'] ?> orang</div>
                                            </div>
                                        </div>

                                        <?php $autoSchedule = get_schedule_for_date($conn, $req['tanggal']); ?>
                                        <div class="mt-4 p-4 rounded-xl bg-blue-50 border border-blue-100">
                                            <div class="font-semibold text-blue-800 mb-2">Saran Unit PJ Tanggal <?= date('d-m-Y', strtotime($req['tanggal'])) ?></div>
                                            <?php if ($autoSchedule): ?>
                                                <ul class="list-disc list-inside text-blue-700">
                                                    <?php foreach ($autoSchedule['units'] as $u): ?>
                                                        <li><?= e($u) ?></li>
                                                    <?php endforeach; ?>
                                                </ul>
                                            <?php else: ?>
                                                <div class="text-red-600">Jadwal belum tersedia untuk tanggal ini.</div>
                                            <?php endif; ?>
                                        </div>

                                        <form method="post" class="assign-form mt-5 space-y-3" data-target="nurse-box-<?= (int)$req['id'] ?>">
                                            <input type="hidden" name="post_action" value="assign_request">
                                            <input type="hidden" name="request_id" value="<?= (int)$req['id'] ?>">

                                            <div id="nurse-box-<?= (int)$req['id'] ?>" class="space-y-3">
                                                <div class="grid grid-cols-1 md:grid-cols-3 gap-3">
                                                    <input type="text" name="nurse_name[]" placeholder="Nama Perawat" class="px-4 py-3 rounded-xl border border-slate-300" required>
                                                    <input type="text" name="nurse_unit[]" placeholder="Unit" class="px-4 py-3 rounded-xl border border-slate-300" required>
                                                    <input type="text" name="nurse_phone[]" placeholder="No. Telepon" class="px-4 py-3 rounded-xl border border-slate-300" required>
                                                </div>
                                            </div>

                                            <div class="flex flex-wrap gap-3">
                                                <button type="button" class="add-nurse-btn px-4 py-2 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-700">
                                                    + Tambah Perawat
                                                </button>
                                                <button type="submit" class="px-5 py-2 rounded-xl bg-green-600 hover:bg-green-700 text-white font-semibold">
                                                    Tugaskan
                                                </button>
                                            </div>
                                        </form>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>

                    <div class="space-y-6">
                        <div class="bg-slate-50 border rounded-2xl p-5">
                            <h2 class="text-xl font-bold text-slate-800 mb-4">Lihat Jadwal</h2>
                            <form method="get" class="space-y-3">
                                <input type="hidden" name="module" value="p3k">
                                <input type="date" name="schedule_date" value="<?= e($selectedDate) ?>" class="w-full px-4 py-3 rounded-xl border border-slate-300">
                                <button type="submit" class="w-full px-4 py-3 rounded-xl bg-blue-600 hover:bg-blue-700 text-white font-semibold">
                                    Tampilkan Jadwal
                                </button>
                            </form>

                            <div class="mt-4 p-4 rounded-xl bg-white border">
                                <?php if ($scheduleData): ?>
                                    <div class="font-semibold text-slate-800 mb-2">
                                        Unit bertugas tanggal <?= date('d-m-Y', strtotime($scheduleData['date'])) ?>
                                    </div>
                                    <ul class="list-disc list-inside text-blue-700">
                                        <?php foreach ($scheduleData['units'] as $unit): ?>
                                            <li><?= e($unit) ?></li>
                                        <?php endforeach; ?>
                                    </ul>
                                <?php else: ?>
                                    <div class="text-red-600">Jadwal tidak ditemukan.</div>
                                <?php endif; ?>
                            </div>
                        </div>

                        <div class="bg-slate-50 border rounded-2xl p-5">
                            <h2 class="text-xl font-bold text-slate-800 mb-4">Generate Jadwal Tahunan</h2>
                            <form method="post" class="space-y-3">
                                <input type="hidden" name="post_action" value="generate_schedule">
                                <input type="number" name="year" value="<?= date('Y') ?>" class="w-full px-4 py-3 rounded-xl border border-slate-300">
                                <button type="submit" class="w-full px-4 py-3 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white font-semibold">
                                    Generate
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

            <div id="tab-form" class="tab-content hidden">
                <div class="max-w-4xl mx-auto bg-slate-50 border rounded-2xl p-6">
                    <h2 class="text-2xl font-bold text-slate-800 mb-6">Form Permintaan P3K</h2>

                    <form method="post" class="space-y-6">
                        <input type="hidden" name="post_action" value="save_request">

                        <div>
                            <label class="block text-sm font-medium text-slate-700 mb-2">Nama Divisi Peminta</label>
                            <input type="text" name="divisi" required class="w-full px-4 py-3 rounded-xl border border-slate-300">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-slate-700 mb-2">Nama Kegiatan</label>
                            <input type="text" name="kegiatan" required class="w-full px-4 py-3 rounded-xl border border-slate-300">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-slate-700 mb-2">Penyelenggara</label>
                            <input type="text" name="penyelenggara" required class="w-full px-4 py-3 rounded-xl border border-slate-300">
                        </div>

                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-slate-700 mb-2">Tanggal</label>
                                <input type="date" name="tanggal" required class="w-full px-4 py-3 rounded-xl border border-slate-300">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-slate-700 mb-2">Dari Jam</label>
                                <input type="time" name="waktu_mulai" required class="w-full px-4 py-3 rounded-xl border border-slate-300">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-slate-700 mb-2">Sampai Jam</label>
                                <input type="time" name="waktu_selesai" required class="w-full px-4 py-3 rounded-xl border border-slate-300">
                            </div>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-slate-700 mb-2">Lokasi</label>
                            <input type="text" name="lokasi" required class="w-full px-4 py-3 rounded-xl border border-slate-300">
                        </div>

                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-slate-700 mb-2">Jumlah Staf Medis Dibutuhkan</label>
                                <input type="number" name="jumlah_staf" min="1" required class="w-full px-4 py-3 rounded-xl border border-slate-300">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-slate-700 mb-2">Jumlah Peserta Hadir</label>
                                <input type="number" name="jumlah_peserta" min="0" required class="w-full px-4 py-3 rounded-xl border border-slate-300">
                            </div>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-slate-700 mb-2">Alat yang Diperlukan</label>
                            <textarea name="alat" rows="4" class="w-full px-4 py-3 rounded-xl border border-slate-300"></textarea>
                        </div>

                        <div>
                            <button type="submit" class="w-full px-4 py-3 rounded-xl bg-blue-600 hover:bg-blue-700 text-white font-semibold text-lg">
                                Kirim Permintaan
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <div id="tab-schedule" class="tab-content hidden">
                <div class="max-w-3xl mx-auto bg-slate-50 border rounded-2xl p-6">
                    <h2 class="text-2xl font-bold text-slate-800 mb-6">Jadwal Penanggung Jawab P3K</h2>

                    <div class="bg-white border rounded-2xl p-5">
                        <?php if ($scheduleData): ?>
                            <div class="mb-3 text-slate-700">
                                <strong>Tanggal:</strong> <?= date('d-m-Y', strtotime($scheduleData['date'])) ?>
                            </div>
                            <ul class="list-disc list-inside text-lg text-blue-700 space-y-2">
                                <?php foreach ($scheduleData['units'] as $unit): ?>
                                    <li><?= e($unit) ?></li>
                                <?php endforeach; ?>
                            </ul>
                        <?php else: ?>
                            <div class="text-red-600">Jadwal untuk tanggal ini belum tersedia.</div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <div id="tab-history" class="tab-content hidden">
                <div class="max-w-5xl mx-auto bg-slate-50 border rounded-2xl p-6">
                    <h2 class="text-2xl font-bold text-slate-800 mb-6">Riwayat Penugasan</h2>

                    <?php if (empty($historyRows)): ?>
                        <div class="rounded-xl bg-white border p-4 text-slate-600">
                            Belum ada riwayat penugasan.
                        </div>
                    <?php else: ?>
                        <div class="space-y-4">
                            <?php foreach ($historyRows as $row): ?>
                                <div class="bg-white border rounded-2xl p-5 shadow-sm">
                                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                                        <div>
                                            <div class="text-slate-500 text-sm">Kegiatan</div>
                                            <div class="font-semibold text-slate-800"><?= e($row['kegiatan']) ?></div>
                                        </div>
                                        <div>
                                            <div class="text-slate-500 text-sm">Tanggal</div>
                                            <div class="font-semibold text-slate-800"><?= date('d-m-Y', strtotime($row['tanggal'])) ?></div>
                                        </div>
                                        <div>
                                            <div class="text-slate-500 text-sm">Assigned At</div>
                                            <div class="font-semibold text-slate-800"><?= e($row['assigned_at'] ?? '-') ?></div>
                                        </div>
                                    </div>

                                    <?php
                                    $names  = array_values(array_filter(array_map('trim', preg_split('/\r\n|\r|\n/', (string)($row['nurse_names'] ?? '')))));
                                    $units  = array_values(array_filter(array_map('trim', preg_split('/\r\n|\r|\n/', (string)($row['nurse_units'] ?? '')))));
                                    $phones = array_values(array_filter(array_map('trim', preg_split('/\r\n|\r|\n/', (string)($row['nurse_phones'] ?? '')))));

                                    $maxRows = max(count($names), count($units), count($phones));
                                    ?>

                                    <div class="mt-4 bg-slate-50 rounded-xl p-4">
                                        <div class="text-slate-600 text-sm font-medium mb-3">Detail Petugas</div>

                                        <?php if ($maxRows > 0): ?>
                                            <div class="overflow-x-auto">
                                                <table class="min-w-full text-sm border border-slate-200 rounded-xl overflow-hidden">
                                                    <thead class="bg-slate-100">
                                                        <tr>
                                                            <th class="px-4 py-2 text-left font-semibold text-slate-700 border-b">No</th>
                                                            <th class="px-4 py-2 text-left font-semibold text-slate-700 border-b">Nama</th>
                                                            <th class="px-4 py-2 text-left font-semibold text-slate-700 border-b">Unit</th>
                                                            <th class="px-4 py-2 text-left font-semibold text-slate-700 border-b">No. HP</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php for ($i = 0; $i < $maxRows; $i++): ?>
                                                            <tr class="bg-white hover:bg-slate-50">
                                                                <td class="px-4 py-2 border-b text-slate-600"><?= $i + 1 ?></td>
                                                                <td class="px-4 py-2 border-b text-slate-800"><?= e($names[$i] ?? '-') ?></td>
                                                                <td class="px-4 py-2 border-b text-slate-800"><?= e($units[$i] ?? '-') ?></td>
                                                                <td class="px-4 py-2 border-b text-slate-800"><?= e($phones[$i] ?? '-') ?></td>
                                                            </tr>
                                                        <?php endfor; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                        <?php else: ?>
                                            <div class="text-slate-500 text-sm">Belum ada detail petugas.</div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

        </div>
    </div>
</div>

<script>
document.querySelectorAll('.tab-btn').forEach(btn => {
    btn.addEventListener('click', function () {
        document.querySelectorAll('.tab-btn').forEach(b => {
            b.classList.remove('active', 'bg-blue-600', 'text-white');
        });
        document.querySelectorAll('.tab-content').forEach(tab => tab.classList.add('hidden'));

        this.classList.add('active', 'bg-blue-600', 'text-white');
        document.getElementById(this.dataset.tab).classList.remove('hidden');
    });
});

document.querySelectorAll('.add-nurse-btn').forEach(btn => {
    btn.addEventListener('click', function () {
        const form = this.closest('.assign-form');
        const targetId = form.getAttribute('data-target');
        const container = document.getElementById(targetId);

        const row = document.createElement('div');
        row.className = 'grid grid-cols-1 md:grid-cols-3 gap-3';
        row.innerHTML = `
            <input type="text" name="nurse_name[]" placeholder="Nama Perawat" class="px-4 py-3 rounded-xl border border-slate-300" required>
            <input type="text" name="nurse_unit[]" placeholder="Unit" class="px-4 py-3 rounded-xl border border-slate-300" required>
            <input type="text" name="nurse_phone[]" placeholder="No. Telepon" class="px-4 py-3 rounded-xl border border-slate-300" required>
        `;
        container.appendChild(row);
    });
});
</script>