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

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

checkAuth();
$conn = getConnection();

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

$module = 'beban_kerja';
$action = $_GET['action'] ?? 'list';
$id     = isset($_GET['id']) ? (int)$_GET['id'] : 0;

$filter_unit  = isset($_GET['unit_id']) ? (int)$_GET['unit_id'] : 0;
$filter_bulan = isset($_GET['bulan']) ? (int)$_GET['bulan'] : (int)date('n');
$filter_tahun = isset($_GET['tahun']) ? (int)$_GET['tahun'] : (int)date('Y');

$bulan_nama = [
    1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April',
    5 => 'Mei', 6 => 'Juni', 7 => 'Juli', 8 => 'Agustus',
    9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember'
];

// =========================
// GET UNITS
// =========================
$units = [];
if (function_exists('getUnits')) {
    $units = getUnits();
} else {
    $resultUnits = $conn->query("SELECT id, name FROM units WHERE is_active = 1 ORDER BY name ASC");
    if ($resultUnits) {
        while ($row = $resultUnits->fetch_assoc()) {
            $units[] = $row;
        }
    }
}

// =========================
// HANDLE DELETE
// =========================
if ($action === 'delete' && $id > 0) {
    $stmt = $conn->prepare("DELETE FROM beban_kerja WHERE id = ?");
    $stmt->bind_param("i", $id);

    if ($stmt->execute()) {
        if (function_exists('logActivity')) {
            logActivity('delete', 'beban_kerja', $id, "Menghapus data beban kerja ID: {$id}");
        }
        echo "<script>alert('Data berhasil dihapus!'); window.location.href='?module={$module}';</script>";
        exit;
    } else {
        echo "<script>alert('Gagal menghapus data: " . addslashes($stmt->error) . "'); window.location.href='?module={$module}';</script>";
        exit;
    }
}

// =========================
// HANDLE SAVE
// =========================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $form_action    = $_POST['form_action'] ?? 'save';
    $save_id        = isset($_POST['id']) ? (int)$_POST['id'] : 0;
    $unit_id        = isset($_POST['unit_id']) ? (int)$_POST['unit_id'] : 0;
    $bulan          = isset($_POST['bulan']) ? (int)$_POST['bulan'] : (int)date('n');
    $tahun          = isset($_POST['tahun']) ? (int)$_POST['tahun'] : (int)date('Y');
    $jumlah_staf    = isset($_POST['jumlah_staf']) ? (int)$_POST['jumlah_staf'] : 0;
    $jumlah_pasien  = isset($_POST['jumlah_pasien']) ? (int)$_POST['jumlah_pasien'] : 0;
    $standar_rasio  = isset($_POST['standar_rasio']) ? (float)$_POST['standar_rasio'] : 5;
    $catatan        = trim($_POST['catatan'] ?? '');
    $user_id        = (int)($_SESSION['user_id'] ?? 0);

    if ($unit_id <= 0 || $bulan < 1 || $bulan > 12 || $tahun < 2000) {
        echo "<script>alert('Data unit, bulan, dan tahun wajib diisi dengan benar!'); history.back();</script>";
        exit;
    }

    if ($jumlah_staf < 0 || $jumlah_pasien < 0) {
        echo "<script>alert('Jumlah staf dan jumlah pasien tidak boleh negatif!'); history.back();</script>";
        exit;
    }

    $rasio = $jumlah_staf > 0 ? round($jumlah_pasien / $jumlah_staf, 2) : 0;
    $status_rasio = ($jumlah_staf > 0 && $rasio <= $standar_rasio) ? 'Aman' : 'Berlebih';

    if ($form_action === 'add') {
        $stmtCheck = $conn->prepare("SELECT id FROM beban_kerja WHERE unit_id = ? AND bulan = ? AND tahun = ? LIMIT 1");
        $stmtCheck->bind_param("iii", $unit_id, $bulan, $tahun);
        $stmtCheck->execute();
        $resCheck = $stmtCheck->get_result();
        $existing = $resCheck->fetch_assoc();
        $stmtCheck->close();

        if ($existing) {
            echo "<script>alert('Data untuk unit dan periode ini sudah ada. Silakan edit data yang sudah ada.'); window.location.href='?module={$module}&action=edit&id=" . (int)$existing['id'] . "';</script>";
            exit;
        }

        $stmt = $conn->prepare("
            INSERT INTO beban_kerja
            (unit_id, bulan, tahun, jumlah_staf, jumlah_pasien, rasio, standar_rasio, status_rasio, catatan, created_by, updated_by)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->bind_param(
            "iiiiiddssii",
            $unit_id,
            $bulan,
            $tahun,
            $jumlah_staf,
            $jumlah_pasien,
            $rasio,
            $standar_rasio,
            $status_rasio,
            $catatan,
            $user_id,
            $user_id
        );

        if ($stmt->execute()) {
            $new_id = $conn->insert_id;
            if (function_exists('logActivity')) {
                logActivity('create', 'beban_kerja', $new_id, "Menambah data beban kerja");
            }
            echo "<script>alert('Data beban kerja berhasil disimpan!'); window.location.href='?module={$module}';</script>";
            exit;
        } else {
            echo "<script>alert('Gagal menyimpan data: " . addslashes($stmt->error) . "'); history.back();</script>";
            exit;
        }
    }

    if ($form_action === 'edit' && $save_id > 0) {
        $stmtCheck = $conn->prepare("SELECT id FROM beban_kerja WHERE unit_id = ? AND bulan = ? AND tahun = ? AND id <> ? LIMIT 1");
        $stmtCheck->bind_param("iiii", $unit_id, $bulan, $tahun, $save_id);
        $stmtCheck->execute();
        $resCheck = $stmtCheck->get_result();
        $existing = $resCheck->fetch_assoc();
        $stmtCheck->close();

        if ($existing) {
            echo "<script>alert('Periode untuk unit ini sudah dipakai data lain.'); history.back();</script>";
            exit;
        }

        $stmt = $conn->prepare("
            UPDATE beban_kerja
            SET unit_id = ?, bulan = ?, tahun = ?, jumlah_staf = ?, jumlah_pasien = ?, rasio = ?, standar_rasio = ?, status_rasio = ?, catatan = ?, updated_by = ?
            WHERE id = ?
        ");
        $stmt->bind_param(
            "iiiiiddssii",
            $unit_id,
            $bulan,
            $tahun,
            $jumlah_staf,
            $jumlah_pasien,
            $rasio,
            $standar_rasio,
            $status_rasio,
            $catatan,
            $user_id,
            $save_id
        );

        if ($stmt->execute()) {
            if (function_exists('logActivity')) {
                logActivity('update', 'beban_kerja', $save_id, "Mengubah data beban kerja ID: {$save_id}");
            }
            echo "<script>alert('Data beban kerja berhasil diubah!'); window.location.href='?module={$module}';</script>";
            exit;
        } else {
            echo "<script>alert('Gagal mengubah data: " . addslashes($stmt->error) . "'); history.back();</script>";
            exit;
        }
    }
}

// =========================
// GET EDIT DATA
// =========================
$editData = null;
if ($action === 'edit' && $id > 0) {
    $stmt = $conn->prepare("SELECT * FROM beban_kerja WHERE id = ? LIMIT 1");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $res = $stmt->get_result();
    $editData = $res->fetch_assoc();
    $stmt->close();

    if (!$editData) {
        echo "<script>alert('Data tidak ditemukan!'); window.location.href='?module={$module}';</script>";
        exit;
    }
}

// =========================
// FILTER & LIST DATA
// =========================
$data = [];
$sql = "
    SELECT bk.*, u.name AS unit_name
    FROM beban_kerja bk
    LEFT JOIN units u ON bk.unit_id = u.id
    WHERE 1=1
";
$params = [];
$types = "";

if ($filter_unit > 0) {
    $sql .= " AND bk.unit_id = ?";
    $params[] = $filter_unit;
    $types .= "i";
}

if ($filter_bulan > 0) {
    $sql .= " AND bk.bulan = ?";
    $params[] = $filter_bulan;
    $types .= "i";
}

if ($filter_tahun > 0) {
    $sql .= " AND bk.tahun = ?";
    $params[] = $filter_tahun;
    $types .= "i";
}

$sql .= " ORDER BY bk.tahun DESC, bk.bulan DESC, u.name ASC";

$stmt = $conn->prepare($sql);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$res = $stmt->get_result();
while ($row = $res->fetch_assoc()) {
    $data[] = $row;
}
$stmt->close();

// =========================
// SUMMARY
// =========================
$total_staf = 0;
$total_pasien = 0;
$rata_rasio = 0;
$total_aman = 0;
$total_berlebih = 0;

foreach ($data as $row) {
    $total_staf += (int)$row['jumlah_staf'];
    $total_pasien += (int)$row['jumlah_pasien'];
    if ($row['status_rasio'] === 'Aman') {
        $total_aman++;
    } else {
        $total_berlebih++;
    }
}
$rata_rasio = $total_staf > 0 ? round($total_pasien / $total_staf, 2) : 0;

// =========================
// CHART DATA
// =========================
$chart_labels = [];
$chart_staf = [];
$chart_pasien = [];
$chart_rasio = [];

foreach ($data as $row) {
    $label = ($filter_unit > 0)
        ? (($bulan_nama[(int)$row['bulan']] ?? $row['bulan']) . ' ' . $row['tahun'])
        : ($row['unit_name'] ?? 'Unit');

    $chart_labels[] = $label;
    $chart_staf[] = (int)$row['jumlah_staf'];
    $chart_pasien[] = (int)$row['jumlah_pasien'];
    $chart_rasio[] = (float)$row['rasio'];
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Analisis Beban Kerja</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        body { font-family: 'Poppins', sans-serif; background: #f8fafc; }
    </style>
</head>
<body class="p-6">
    <div class="mb-6 flex justify-between items-center">
        <div>
            <h1 class="text-2xl font-bold text-gray-800">Analisis Beban Kerja</h1>
            <p class="text-gray-600">Input jumlah staf dan pasien lalu hitung rasio</p>
        </div>
        <a href="?module=<?= e($module) ?>&action=add"
           class="bg-gradient-to-r from-blue-600 to-indigo-600 text-white px-4 py-2 rounded-lg hover:from-blue-700 hover:to-indigo-700 transition-all">
            <i class="fas fa-plus mr-2"></i> Input Beban Kerja
        </a>
    </div>

    <?php if ($action === 'add' || $action === 'edit'): ?>
        <?php
        $formData = $editData ?: [
            'id' => 0,
            'unit_id' => '',
            'bulan' => date('n'),
            'tahun' => date('Y'),
            'jumlah_staf' => 0,
            'jumlah_pasien' => 0,
            'standar_rasio' => 5,
            'catatan' => '',
        ];
        $rasioForm = ((int)$formData['jumlah_staf'] > 0) ? round($formData['jumlah_pasien'] / $formData['jumlah_staf'], 2) : 0;
        ?>
        <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
            <h2 class="text-lg font-semibold mb-4">
                <?= $action === 'add' ? 'Input Data Beban Kerja' : 'Edit Data Beban Kerja' ?>
            </h2>

            <form method="POST" action="?module=<?= e($module) ?>&action=<?= e($action) ?><?= $action === 'edit' ? '&id=' . (int)$formData['id'] : '' ?>" class="space-y-6">
                <input type="hidden" name="form_action" value="<?= e($action) ?>">
                <input type="hidden" name="id" value="<?= (int)$formData['id'] ?>">

                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Unit *</label>
                        <select name="unit_id" required class="w-full px-4 py-2 border border-gray-300 rounded-lg">
                            <option value="">Pilih Unit</option>
                            <?php foreach ($units as $unit): ?>
                                <option value="<?= (int)$unit['id'] ?>" <?= (int)$formData['unit_id'] === (int)$unit['id'] ? 'selected' : '' ?>>
                                    <?= e($unit['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Bulan *</label>
                        <select name="bulan" required class="w-full px-4 py-2 border border-gray-300 rounded-lg">
                            <?php for ($i = 1; $i <= 12; $i++): ?>
                                <option value="<?= $i ?>" <?= (int)$formData['bulan'] === $i ? 'selected' : '' ?>>
                                    <?= e($bulan_nama[$i]) ?>
                                </option>
                            <?php endfor; ?>
                        </select>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Tahun *</label>
                        <select name="tahun" required class="w-full px-4 py-2 border border-gray-300 rounded-lg">
                            <?php for ($i = date('Y') - 2; $i <= date('Y') + 2; $i++): ?>
                                <option value="<?= $i ?>" <?= (int)$formData['tahun'] === (int)$i ? 'selected' : '' ?>>
                                    <?= $i ?>
                                </option>
                            <?php endfor; ?>
                        </select>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Standar Rasio *</label>
                        <input type="number" step="0.01" min="0" name="standar_rasio" id="standar_rasio"
                               value="<?= e($formData['standar_rasio']) ?>"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg">
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Jumlah Staf *</label>
                        <input type="number" min="0" name="jumlah_staf" id="jumlah_staf"
                               value="<?= (int)$formData['jumlah_staf'] ?>"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg"
                               oninput="hitungRasio()">
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Jumlah Pasien *</label>
                        <input type="number" min="0" name="jumlah_pasien" id="jumlah_pasien"
                               value="<?= (int)$formData['jumlah_pasien'] ?>"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg"
                               oninput="hitungRasio()">
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Rasio Otomatis</label>
                        <input type="text" id="rasio_preview"
                               value="1 : <?= $rasioForm ?>"
                               readonly
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg bg-gray-50 font-semibold text-blue-700">
                    </div>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Catatan</label>
                    <textarea name="catatan" rows="4" class="w-full px-4 py-2 border border-gray-300 rounded-lg"><?= e($formData['catatan']) ?></textarea>
                </div>

                <div class="flex justify-end space-x-2">
                    <a href="?module=<?= e($module) ?>" class="px-6 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50">Batal</a>
                    <button type="submit" class="px-6 py-2 bg-gradient-to-r from-blue-600 to-indigo-600 text-white rounded-lg hover:from-blue-700 hover:to-indigo-700">
                        <?= $action === 'add' ? 'Simpan Data' : 'Update Data' ?>
                    </button>
                </div>
            </form>
        </div>

        <script>
            function hitungRasio() {
                const staf = parseFloat(document.getElementById('jumlah_staf').value) || 0;
                const pasien = parseFloat(document.getElementById('jumlah_pasien').value) || 0;
                const rasioEl = document.getElementById('rasio_preview');

                let rasio = 0;
                if (staf > 0) {
                    rasio = (pasien / staf).toFixed(2);
                }

                rasioEl.value = '1 : ' + rasio;
            }
        </script>

    <?php else: ?>
        <!-- FILTER -->
        <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
            <form method="GET" action="" class="grid grid-cols-1 md:grid-cols-4 gap-4">
                <input type="hidden" name="module" value="<?= e($module) ?>">

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Unit</label>
                    <select name="unit_id" class="w-full px-4 py-2 border border-gray-300 rounded-lg">
                        <option value="0">Semua Unit</option>
                        <?php foreach ($units as $unit): ?>
                            <option value="<?= (int)$unit['id'] ?>" <?= $filter_unit === (int)$unit['id'] ? 'selected' : '' ?>>
                                <?= e($unit['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Bulan</label>
                    <select name="bulan" class="w-full px-4 py-2 border border-gray-300 rounded-lg">
                        <?php for ($i = 1; $i <= 12; $i++): ?>
                            <option value="<?= $i ?>" <?= $filter_bulan === $i ? 'selected' : '' ?>>
                                <?= e($bulan_nama[$i]) ?>
                            </option>
                        <?php endfor; ?>
                    </select>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Tahun</label>
                    <select name="tahun" class="w-full px-4 py-2 border border-gray-300 rounded-lg">
                        <?php for ($i = date('Y') - 2; $i <= date('Y') + 2; $i++): ?>
                            <option value="<?= $i ?>" <?= $filter_tahun === (int)$i ? 'selected' : '' ?>>
                                <?= $i ?>
                            </option>
                        <?php endfor; ?>
                    </select>
                </div>

                <div class="flex items-end">
                    <button type="submit" class="w-full bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700">
                        <i class="fas fa-search mr-2"></i>Tampilkan
                    </button>
                </div>
            </form>
        </div>

        <!-- SUMMARY -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
            <div class="bg-white rounded-xl shadow-lg p-5">
                <p class="text-sm text-gray-500">Total Staf</p>
                <p class="text-3xl font-bold text-blue-600"><?= $total_staf ?></p>
            </div>
            <div class="bg-white rounded-xl shadow-lg p-5">
                <p class="text-sm text-gray-500">Total Pasien</p>
                <p class="text-3xl font-bold text-green-600"><?= $total_pasien ?></p>
            </div>
            <div class="bg-white rounded-xl shadow-lg p-5">
                <p class="text-sm text-gray-500">Rata-rata Rasio</p>
                <p class="text-3xl font-bold text-indigo-600">1 : <?= $rata_rasio ?></p>
            </div>
            <div class="bg-white rounded-xl shadow-lg p-5">
                <p class="text-sm text-gray-500">Status Data</p>
                <p class="text-lg font-bold text-gray-800"><?= $total_aman ?> Aman / <?= $total_berlebih ?> Berlebih</p>
            </div>
        </div>

        <!-- CHART -->
        <?php if (!empty($data)): ?>
        <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
            <h3 class="text-lg font-semibold mb-4">Grafik Beban Kerja</h3>
            <div class="h-[420px]">
                <canvas id="bebanKerjaChart"></canvas>
            </div>
        </div>
        <?php endif; ?>

        <!-- TABLE -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden">
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead class="bg-gray-50 border-b border-gray-200">
                        <tr>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">No</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Unit</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Periode</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Jumlah Staf</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Jumlah Pasien</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Rasio</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Standar</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Catatan</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Aksi</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-200">
                        <?php if (empty($data)): ?>
                            <tr>
                                <td colspan="10" class="px-4 py-8 text-center text-gray-500">
                                    Belum ada data beban kerja untuk filter ini.
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php $no = 1; foreach ($data as $row): ?>
                                <?php $warna = $row['status_rasio'] === 'Aman' ? 'green' : 'red'; ?>
                                <tr class="hover:bg-gray-50">
                                    <td class="px-4 py-3 text-sm"><?= $no++ ?></td>
                                    <td class="px-4 py-3 text-sm font-medium"><?= e($row['unit_name'] ?? '-') ?></td>
                                    <td class="px-4 py-3 text-sm"><?= e($bulan_nama[(int)$row['bulan']] ?? $row['bulan']) ?> <?= (int)$row['tahun'] ?></td>
                                    <td class="px-4 py-3 text-sm"><?= (int)$row['jumlah_staf'] ?></td>
                                    <td class="px-4 py-3 text-sm"><?= (int)$row['jumlah_pasien'] ?></td>
                                    <td class="px-4 py-3 text-sm font-semibold">1 : <?= e($row['rasio']) ?></td>
                                    <td class="px-4 py-3 text-sm">1 : <?= e($row['standar_rasio']) ?></td>
                                    <td class="px-4 py-3">
                                        <span class="px-2 py-1 text-xs rounded-full bg-<?= $warna ?>-100 text-<?= $warna ?>-800">
                                            <?= e($row['status_rasio']) ?>
                                        </span>
                                    </td>
                                    <td class="px-4 py-3 text-sm"><?= e($row['catatan'] ?: '-') ?></td>
                                    <td class="px-4 py-3 text-sm space-x-2">
                                        <a href="?module=<?= e($module) ?>&action=edit&id=<?= (int)$row['id'] ?>" class="text-blue-600 hover:text-blue-800" title="Edit">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <a href="?module=<?= e($module) ?>&action=delete&id=<?= (int)$row['id'] ?>"
                                           onclick="return confirm('Yakin ingin menghapus data ini?')"
                                           class="text-red-600 hover:text-red-800" title="Hapus">
                                            <i class="fas fa-trash"></i>
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <?php if (!empty($data)): ?>
        <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
        <script>
            const chartLabels = <?= json_encode($chart_labels) ?>;
            const chartStaf = <?= json_encode($chart_staf) ?>;
            const chartPasien = <?= json_encode($chart_pasien) ?>;
            const chartRasio = <?= json_encode($chart_rasio) ?>;

            const ctx = document.getElementById('bebanKerjaChart').getContext('2d');
            new Chart(ctx, {
                data: {
                    labels: chartLabels,
                    datasets: [
                        {
                            type: 'bar',
                            label: 'Jumlah Staf',
                            data: chartStaf,
                            backgroundColor: 'rgba(59, 130, 246, 0.6)',
                            borderColor: 'rgba(59, 130, 246, 1)',
                            borderWidth: 1,
                            yAxisID: 'y'
                        },
                        {
                            type: 'bar',
                            label: 'Jumlah Pasien',
                            data: chartPasien,
                            backgroundColor: 'rgba(16, 185, 129, 0.6)',
                            borderColor: 'rgba(16, 185, 129, 1)',
                            borderWidth: 1,
                            yAxisID: 'y'
                        },
                        {
                            type: 'line',
                            label: 'Rasio',
                            data: chartRasio,
                            borderColor: 'rgba(239, 68, 68, 1)',
                            backgroundColor: 'rgba(239, 68, 68, 0.15)',
                            fill: false,
                            tension: 0.3,
                            yAxisID: 'y1'
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    interaction: {
                        mode: 'index',
                        intersect: false
                    },
                    stacked: false,
                    scales: {
                        y: {
                            type: 'linear',
                            display: true,
                            position: 'left',
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: 'Jumlah'
                            }
                        },
                        y1: {
                            type: 'linear',
                            display: true,
                            position: 'right',
                            beginAtZero: true,
                            grid: {
                                drawOnChartArea: false
                            },
                            title: {
                                display: true,
                                text: 'Rasio'
                            }
                        }
                    }
                }
            });
        </script>
        <?php endif; ?>
    <?php endif; ?>
</body>
</html>