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

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

if (file_exists(__DIR__ . '/../config/app.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');
    }
}

$userRole = strtolower((string)($_SESSION['user_role'] ?? $_SESSION['user']['role'] ?? 'user'));
$isAdmin  = in_array($userRole, ['admin', 'superadmin'], true);

$logo = defined('LOGO_URL')
    ? LOGO_URL
    : 'https://balimedhospital.co.id/wp-content/uploads/elementor/thumbs/logo-dark-o9cm6tnx14hcrnest1hge1pwnqj0yaumij7qohadlm.png';

function soExec(mysqli $conn, string $sql): void
{
    try {
        $conn->query($sql);
    } catch (Throwable $e) {
        // Diamkan agar aman di shared hosting. Error tidak menghentikan halaman.
    }
}

function soEnsureSchema(mysqli $conn): void
{
    soExec($conn, "CREATE TABLE IF NOT EXISTS app_settings (
        id INT AUTO_INCREMENT PRIMARY KEY,
        setting_key VARCHAR(120) NOT NULL UNIQUE,
        setting_value TEXT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
}

soEnsureSchema($conn);

function getAppSetting(mysqli $conn, string $key, ?string $default = null): ?string
{
    $sql = "SELECT setting_value FROM app_settings WHERE setting_key = ? LIMIT 1";
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        return $default;
    }

    $stmt->bind_param('s', $key);
    $stmt->execute();
    $res = $stmt->get_result();
    $row = $res ? $res->fetch_assoc() : null;
    $stmt->close();

    return isset($row['setting_value']) ? (string)$row['setting_value'] : $default;
}

function setAppSetting(mysqli $conn, string $key, string $value): bool
{
    $sql = "INSERT INTO app_settings (setting_key, setting_value)
            VALUES (?, ?)
            ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)";
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        return false;
    }

    $stmt->bind_param('ss', $key, $value);
    $ok = $stmt->execute();
    $stmt->close();

    return $ok;
}

function soPhoto(?string $path, string $text = 'Foto'): string
{
    $path = trim((string)$path);
    if ($path !== '') {
        return $path;
    }

    return 'https://ui-avatars.com/api/?name=' . rawurlencode($text) . '&background=e2e8f0&color=334155&size=160';
}

function soEmployeeFallback(string $title): array
{
    return [
        'id' => 0,
        'full_name' => 'Belum dipilih',
        'photo_path' => null,
        'position_name' => $title,
        'unit_name' => '',
    ];
}

function soGetEmployeeById(mysqli $conn, int $employeeId, string $title = ''): array
{
    if ($employeeId <= 0) {
        return soEmployeeFallback($title);
    }

    $sql = "SELECT e.id, e.full_name, e.photo_path, e.position_name, COALESCE(u.name, '') unit_name
            FROM employees e
            LEFT JOIN units u ON u.id = e.unit_id
            WHERE e.id = ?
              AND (e.employment_status = 'aktif' OR e.employment_status IS NULL OR e.employment_status = '')
            LIMIT 1";

    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        return soEmployeeFallback($title);
    }

    $stmt->bind_param('i', $employeeId);
    $stmt->execute();
    $res = $stmt->get_result();
    $row = $res ? $res->fetch_assoc() : null;
    $stmt->close();

    return $row ?: soEmployeeFallback($title);
}

function soGetEmployeeByExactPosition(mysqli $conn, string $positionName, string $title = ''): array
{
    $sql = "SELECT e.id, e.full_name, e.photo_path, e.position_name, COALESCE(u.name, '') unit_name
            FROM employees e
            LEFT JOIN units u ON u.id = e.unit_id
            WHERE e.position_name = ?
              AND (e.employment_status = 'aktif' OR e.employment_status IS NULL OR e.employment_status = '')
            ORDER BY e.id ASC
            LIMIT 1";

    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        return soEmployeeFallback($title ?: $positionName);
    }

    $stmt->bind_param('s', $positionName);
    $stmt->execute();
    $res = $stmt->get_result();
    $row = $res ? $res->fetch_assoc() : null;
    $stmt->close();

    return $row ?: soEmployeeFallback($title ?: $positionName);
}

function soGetHeadByUnit(mysqli $conn, int $unitId, string $title): array
{
    $sql = "SELECT e.id, e.full_name, e.photo_path, e.position_name, COALESCE(u.name, '') unit_name
            FROM employees e
            LEFT JOIN units u ON u.id = e.unit_id
            WHERE e.unit_id = ?
              AND (e.employment_status = 'aktif' OR e.employment_status IS NULL OR e.employment_status = '')
              AND (
                    e.position_name LIKE '%Kepala Unit%'
                    OR e.position_name = 'Ka.Unit'
                    OR e.position_name LIKE '%Ka Unit%'
                    OR e.position_name LIKE '%Karu%'
                    OR e.position_name LIKE '%Kepala Ruangan%'
                  )
            ORDER BY e.id ASC
            LIMIT 1";

    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        return soEmployeeFallback($title);
    }

    $stmt->bind_param('i', $unitId);
    $stmt->execute();
    $res = $stmt->get_result();
    $row = $res ? $res->fetch_assoc() : null;
    $stmt->close();

    return $row ?: soEmployeeFallback($title);
}

function soGetSlotPerson(mysqli $conn, string $slotKey, string $title, array $fallbackPositions = [], int $unitId = 0): array
{
    $settingKey = 'struktur_org_employee_' . $slotKey;
    $savedId = (int)(getAppSetting($conn, $settingKey, '0') ?? 0);

    if ($savedId > 0) {
        $person = soGetEmployeeById($conn, $savedId, $title);
        if ((int)($person['id'] ?? 0) > 0) {
            return $person;
        }
    }

    foreach ($fallbackPositions as $position) {
        $person = soGetEmployeeByExactPosition($conn, $position, $title);
        if ((int)($person['id'] ?? 0) > 0) {
            return $person;
        }
    }

    if ($unitId > 0) {
        $person = soGetHeadByUnit($conn, $unitId, $title);
        if ((int)($person['id'] ?? 0) > 0) {
            return $person;
        }
    }

    // Kompatibilitas data lama khusus Direktur bila sebelumnya pernah diisi manual.
    if ($slotKey === 'direktur') {
        $oldName = getAppSetting($conn, 'direktur_nama', '');
        $oldJob  = getAppSetting($conn, 'direktur_jabatan', '');
        $oldFoto = getAppSetting($conn, 'direktur_foto', '');
        if (trim((string)$oldName) !== '') {
            return [
                'id' => 0,
                'full_name' => (string)$oldName,
                'photo_path' => (string)$oldFoto,
                'position_name' => trim((string)$oldJob) !== '' ? (string)$oldJob : $title,
                'unit_name' => '',
            ];
        }
    }

    return soEmployeeFallback($title);
}

function soEmployeeOptions(mysqli $conn): array
{
    $rows = [];
    $sql = "SELECT e.id, e.full_name, COALESCE(e.position_name, '') position_name, COALESCE(u.name, '') unit_name
            FROM employees e
            LEFT JOIN units u ON u.id = e.unit_id
            WHERE (e.employment_status = 'aktif' OR e.employment_status IS NULL OR e.employment_status = '')
            ORDER BY e.full_name ASC
            LIMIT 1500";

    $res = $conn->query($sql);
    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $rows[] = $row;
        }
    }

    return $rows;
}

function soSafeSlotKey(string $key): string
{
    $key = strtolower(trim($key));
    $key = preg_replace('/[^a-z0-9_]+/', '_', $key) ?: '';
    return trim($key, '_');
}

function soPositionCard(string $slotKey, string $title, array $person, string $theme = 'blue', bool $isAdmin = false, string $size = 'large'): string
{
    $slotKey = soSafeSlotKey($slotKey);
    $name = (string)($person['full_name'] ?? 'Belum dipilih');
    $photo = soPhoto((string)($person['photo_path'] ?? ''), $name);
    $positionName = (string)($person['position_name'] ?? $title);
    $employeeId = (int)($person['id'] ?? 0);

    $themeClass = match ($theme) {
        'cyan' => 'from-cyan-500 to-sky-600 text-white',
        'emerald' => 'from-emerald-500 to-green-600 text-white',
        'violet' => 'from-violet-500 to-purple-600 text-white',
        'amber' => 'from-amber-400 to-orange-500 text-white',
        'slate' => 'from-slate-600 to-slate-800 text-white',
        default => 'from-blue-500 to-indigo-600 text-white',
    };

    $avatarClass = $size === 'small' ? 'so-avatar-small' : 'so-avatar';

    ob_start();
    ?>
    <div class="so-org-card relative w-full <?= $size === 'small' ? 'max-w-xs p-4' : 'max-w-sm p-6' ?> text-center bg-gradient-to-br <?= e($themeClass) ?> shadow-xl">
        <?php if ($isAdmin): ?>
            <button
                type="button"
                onclick="openStrukturModal('<?= e($slotKey) ?>', '<?= e(addslashes($title)) ?>', '<?= $employeeId ?>')"
                class="absolute top-3 right-3 w-10 h-10 rounded-full bg-white/90 text-slate-700 hover:text-blue-600 shadow-lg z-20"
                title="Pilih nama pejabat"
            >
                <i class="fas fa-user-edit"></i>
            </button>
        <?php endif; ?>

        <div class="relative z-10">
            <img src="<?= e($photo) ?>" class="<?= e($avatarClass) ?> mx-auto border-4 border-white shadow-xl" alt="<?= e($title) ?>">
            <div class="<?= $size === 'small' ? 'mt-3 text-base' : 'mt-4 text-xl' ?> font-extrabold"><?= e($name) ?></div>
            <div class="text-sm opacity-90 mt-1"><?= e($title) ?></div>
            <?php if ($employeeId > 0 && trim($positionName) !== '' && trim($positionName) !== trim($title)): ?>
                <div class="text-xs opacity-80 mt-1">Profile: <?= e($positionName) ?></div>
            <?php endif; ?>
        </div>
    </div>
    <?php
    return (string)ob_get_clean();
}

$employees = soEmployeeOptions($conn);

$slotTitles = [
    'direktur' => 'Direktur RS BaliMed',
    'kadiv_keperawatan' => 'Kepala Divisi Keperawatan',
    'kasubdiv_rajal' => 'Kasubdiv Keperawatan Rawat Jalan',
    'kasubdiv_ranap' => 'Kasubdiv Keperawatan Rawat Inap',
];

if ($isAdmin && $_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'update_structure_slot') {
    $slotKey = soSafeSlotKey((string)($_POST['slot_key'] ?? ''));
    $employeeId = (int)($_POST['employee_id'] ?? 0);

    if ($slotKey !== '') {
        setAppSetting($conn, 'struktur_org_employee_' . $slotKey, $employeeId > 0 ? (string)$employeeId : '0');
    }

    echo "<script>alert('Pejabat struktur berhasil diperbarui');window.location.href='?module=struktur_organisasi';</script>";
    exit;
}

$direktur = soGetSlotPerson($conn, 'direktur', 'Direktur RS BaliMed', ['Direktur RS BaliMed', 'Direktur']);
$kadiv = soGetSlotPerson($conn, 'kadiv_keperawatan', 'Kepala Divisi Keperawatan', ['Kepala Divisi Keperawatan']);
$kasubdivRajal = soGetSlotPerson($conn, 'kasubdiv_rajal', 'Kasubdiv Keperawatan Rawat Jalan', ['Kasubdiv Keperawatan Rawat Jalan']);
$kasubdivRanap = soGetSlotPerson($conn, 'kasubdiv_ranap', 'Kasubdiv Keperawatan Rawat Inap', ['Kasubdiv Keperawatan Rawat Inap']);

$rajalKeywords = ['igd', 'kamar bersalin', 'vk', 'hemodialisis', 'hemodialisa', 'hd', 'poliklinik', 'poli', 'kamar operasi', 'ok'];
$ranapKeywords = ['pav.canigara', 'canigara', 'pav.cempaka', 'cempaka', 'pav.cendana', 'cendana', 'rawat inap', 'ruang bayi', 'bayi', 'nicu', 'icu'];

function soUnitCanonicalKey(string $unitName): string
{
    $lower = strtolower(trim($unitName));
    $lower = preg_replace('/\s+/', ' ', $lower) ?: $lower;

    return match (true) {
        str_contains($lower, 'dokter umum') => 'dokter_umum',
        str_contains($lower, 'igd') => 'igd',
        str_contains($lower, 'hemodialisis') || str_contains($lower, 'hemodialisa') || $lower === 'hd' => 'hd',
        str_contains($lower, 'kamar operasi') || preg_match('/\bok\b/', $lower) => 'ok',
        str_contains($lower, 'kamar bersalin') || preg_match('/\bvk\b/', $lower) => 'vk',
        str_contains($lower, 'poliklinik') || str_contains($lower, 'poli') => 'poliklinik',
        str_contains($lower, 'canigara') => 'canigara',
        str_contains($lower, 'cempaka') => 'cempaka',
        str_contains($lower, 'cendana') => 'cendana',
        str_contains($lower, 'nicu') && (str_contains($lower, 'bayi') || str_contains($lower, 'r. bayi')) => 'bayi_nicu_gabungan',
        str_contains($lower, 'nicu') => 'nicu',
        str_contains($lower, 'icu') => 'icu',
        str_contains($lower, 'ruang bayi') || str_contains($lower, 'r. bayi') || $lower === 'bayi' => 'ruang_bayi',
        default => soSafeSlotKey($unitName),
    };
}

function soShouldSkipUnit(string $unitName, bool $hasSeparateBayi, bool $hasSeparateNicu): bool
{
    $lower = strtolower(trim($unitName));

    if (str_contains($lower, 'kasubdiv')) {
        return true;
    }

    if (str_contains($lower, 'dokter umum')) {
        return true;
    }

    if ((str_contains($lower, 'bayi') || str_contains($lower, 'r. bayi')) && str_contains($lower, 'nicu') && $hasSeparateBayi && $hasSeparateNicu) {
        return true;
    }

    return false;
}

$units = [];
$unitResult = $conn->query("SELECT id, name FROM units WHERE is_active = 1 ORDER BY name ASC");
if ($unitResult) {
    while ($row = $unitResult->fetch_assoc()) {
        $units[] = $row;
    }
}

$rajalUnits = [];
$ranapUnits = [];

$unitNamesLower = array_map(static fn($u) => strtolower((string)($u['name'] ?? '')), $units);
$hasSeparateBayi = false;
$hasSeparateNicu = false;
foreach ($unitNamesLower as $n) {
    if (str_contains($n, 'ruang bayi') || $n === 'bayi') {
        $hasSeparateBayi = true;
    }
    if (str_contains($n, 'nicu') && !str_contains($n, 'bayi')) {
        $hasSeparateNicu = true;
    }
}

$seenRajal = [];
$seenRanap = [];

foreach ($units as $unit) {
    $unitId = (int)$unit['id'];
    $unitName = trim((string)$unit['name']);
    $lower = strtolower($unitName);

    if (soShouldSkipUnit($unitName, $hasSeparateBayi, $hasSeparateNicu)) {
        continue;
    }

    $slotKey = 'unit_' . $unitId;
    $title = 'Kepala Unit ' . $unitName;
    $matched = false;
    $canonical = soUnitCanonicalKey($unitName);

    foreach ($rajalKeywords as $kw) {
        if (strpos($lower, $kw) !== false) {
            if (isset($seenRajal[$canonical])) {
                $matched = true;
                break;
            }
            $rajalUnits[] = [
                'id' => $unitId,
                'nama' => $unitName,
                'slot_key' => $slotKey,
                'title' => $title,
                'person' => soGetSlotPerson($conn, $slotKey, $title, [], $unitId),
            ];
            $seenRajal[$canonical] = true;
            $matched = true;
            break;
        }
    }

    if ($matched) {
        continue;
    }

    foreach ($ranapKeywords as $kw) {
        if (strpos($lower, $kw) !== false) {
            if (isset($seenRanap[$canonical])) {
                break;
            }
            $ranapUnits[] = [
                'id' => $unitId,
                'nama' => $unitName,
                'slot_key' => $slotKey,
                'title' => $title,
                'person' => soGetSlotPerson($conn, $slotKey, $title, [], $unitId),
            ];
            $seenRanap[$canonical] = true;
            break;
        }
    }
}

usort($rajalUnits, fn($a, $b) => strcmp($a['nama'], $b['nama']));
usort($ranapUnits, fn($a, $b) => strcmp($a['nama'], $b['nama']));

foreach ($rajalUnits as $u) {
    $slotTitles[$u['slot_key']] = $u['title'];
}
foreach ($ranapUnits as $u) {
    $slotTitles[$u['slot_key']] = $u['title'];
}

function soUnitCard(array $unit, string $theme, bool $isAdmin): string
{
    $person = $unit['person'] ?? [];
    $name = (string)($person['full_name'] ?? 'Belum dipilih');
    $photo = soPhoto((string)($person['photo_path'] ?? ''), $name);
    $employeeId = (int)($person['id'] ?? 0);
    $slotKey = (string)$unit['slot_key'];
    $title = (string)$unit['title'];

    $iconClass = $theme === 'emerald'
        ? 'from-emerald-500 to-green-600'
        : 'from-violet-500 to-purple-600';

    ob_start();
    ?>
    <div class="so-unit-card p-4 relative">
        <?php if ($isAdmin): ?>
            <button
                type="button"
                onclick="openStrukturModal('<?= e($slotKey) ?>', '<?= e(addslashes($title)) ?>', '<?= $employeeId ?>')"
                class="absolute top-3 right-3 w-8 h-8 rounded-full bg-slate-100 text-slate-600 hover:bg-blue-600 hover:text-white"
                title="Pilih Kepala Unit"
            >
                <i class="fas fa-edit text-xs"></i>
            </button>
        <?php endif; ?>

        <div class="flex items-start gap-3 pr-8">
            <img src="<?= e($photo) ?>" class="w-14 h-14 rounded-2xl object-cover border border-slate-200 shadow-sm" alt="<?= e($title) ?>">
            <div class="flex-1">
                <div class="font-bold text-slate-800 leading-tight"><?= e($unit['nama'] ?? '-') ?></div>
                <div class="text-xs text-slate-400 mt-1">Kepala Unit</div>
                <div class="text-sm text-slate-700 mt-1 font-semibold"><?= e($name) ?></div>
                <?php if (!empty($person['position_name']) && (string)$person['position_name'] !== $title): ?>
                    <div class="text-xs text-slate-400 mt-1"><?= e($person['position_name']) ?></div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <?php
    return (string)ob_get_clean();
}
?>

<style>
    .so-page {
        --so-blue: #2563eb;
        --so-indigo: #4f46e5;
        --so-cyan: #0891b2;
        --so-green: #059669;
        --so-purple: #7c3aed;
        --so-slate: #334155;
    }

    .so-shell {
        background:
            radial-gradient(circle at top left, rgba(37, 99, 235, 0.08), transparent 24%),
            radial-gradient(circle at top right, rgba(124, 58, 237, 0.08), transparent 20%),
            linear-gradient(180deg, #f8fbff 0%, #f8fafc 100%);
        border-radius: 32px;
    }

    .so-main-card {
        border-radius: 30px;
        background: rgba(255,255,255,0.94);
        backdrop-filter: blur(10px);
        border: 1px solid rgba(226,232,240,0.9);
        box-shadow: 0 24px 60px rgba(15, 23, 42, 0.08);
    }

    .so-org-card {
        position: relative;
        overflow: hidden;
        border-radius: 24px;
        transition: all 0.25s ease;
    }

    .so-org-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 18px 40px rgba(15,23,42,0.10);
    }

    .so-org-card::before {
        content: '';
        position: absolute;
        inset: auto -40px -40px auto;
        width: 120px;
        height: 120px;
        border-radius: 999px;
        background: rgba(255,255,255,0.18);
    }

    .so-avatar {
        width: 104px;
        height: 104px;
        object-fit: cover;
        border-radius: 999px;
    }

    .so-avatar-small {
        width: 88px;
        height: 88px;
        object-fit: cover;
        border-radius: 999px;
    }

    .so-line-vertical {
        width: 4px;
        height: 34px;
        margin: 0 auto;
        border-radius: 999px;
        background: linear-gradient(180deg, #cbd5e1, #94a3b8);
    }

    .so-branch-line {
        position: relative;
        height: 34px;
        margin: 0 auto 10px auto;
        max-width: 760px;
    }

    .so-branch-line::before {
        content: '';
        position: absolute;
        left: 25%;
        right: 25%;
        top: 0;
        height: 4px;
        border-radius: 999px;
        background: linear-gradient(90deg, #cbd5e1, #94a3b8, #cbd5e1);
    }

    .so-branch-line .left,
    .so-branch-line .right {
        position: absolute;
        top: 0;
        width: 4px;
        height: 34px;
        border-radius: 999px;
        background: linear-gradient(180deg, #cbd5e1, #94a3b8);
    }

    .so-branch-line .left { left: 25%; }
    .so-branch-line .right { right: 25%; }

    .so-unit-card {
        border-radius: 20px;
        background: rgba(255,255,255,0.92);
        border: 1px solid rgba(226,232,240,0.8);
        box-shadow: 0 10px 24px rgba(15,23,42,0.05);
        transition: all 0.2s ease;
    }

    .so-unit-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 16px 30px rgba(15,23,42,0.08);
    }

    .so-btn {
        border-radius: 16px;
        padding: 0.8rem 1.1rem;
        font-weight: 700;
        transition: all 0.2s ease;
        display: inline-flex;
        align-items: center;
        gap: 0.55rem;
    }

    .so-btn:hover {
        transform: translateY(-1px);
    }

    .so-select {
        width: 100%;
        border-radius: 18px;
        border: 1px solid #cbd5e1;
        padding: .85rem 1rem;
        outline: none;
    }

    .so-select:focus {
        border-color: #2563eb;
        box-shadow: 0 0 0 4px rgba(37,99,235,.12);
    }

    @media print {
        .no-print { display: none !important; }
        .so-shell, .so-main-card, .so-org-card, .so-unit-card {
            box-shadow: none !important;
        }
        .so-page {
            max-width: none !important;
            padding: 0 !important;
        }
    }

    @media (max-width: 768px) {
        .so-branch-line {
            display: none;
        }

        .so-avatar {
            width: 92px;
            height: 92px;
        }
    }
</style>

<div class="so-page max-w-7xl mx-auto p-4 md:p-6">
    <div class="so-shell p-3 md:p-4">
        <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4 mb-5 no-print">
            <div>
                <h1 class="text-2xl md:text-3xl font-extrabold text-slate-800">Struktur Organisasi Divisi Keperawatan</h1>
                <p class="text-slate-500 text-sm mt-1">
                    Title jabatan sudah disiapkan. Admin tinggal pilih nama pegawai, lalu sistem otomatis menampilkan nama dan foto profile picture.
                </p>
            </div>

            <div class="flex flex-wrap gap-2">
                <a href="?module=dashboard" class="so-btn bg-slate-200 text-slate-700 hover:bg-slate-300">
                    <i class="fas fa-arrow-left"></i>
                    Kembali
                </a>
                <button type="button" onclick="window.print()" class="so-btn bg-red-600 text-white hover:bg-red-700">
                    <i class="fas fa-print"></i>
                    Print / PDF
                </button>
            </div>
        </div>

        <?php if ($isAdmin): ?>
            <div class="no-print mb-5 rounded-3xl border border-blue-100 bg-blue-50 p-4 text-blue-800">
                <div class="flex items-start gap-3">
                    <div class="w-10 h-10 rounded-2xl bg-blue-600 text-white flex items-center justify-center">
                        <i class="fas fa-info"></i>
                    </div>
                    <div>
                        <div class="font-extrabold">Mode admin aktif</div>
                        <div class="text-sm text-blue-700 mt-1">
                            Klik ikon pensil pada setiap jabatan untuk memilih nama dari data pegawai aktif. Foto otomatis mengikuti <b>photo_path</b> di profile pegawai.
                        </div>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <div class="so-main-card p-5 md:p-8">
            <div class="text-center mb-10">
                <img src="<?= e($logo) ?>" class="h-16 md:h-20 mx-auto mb-3" alt="Logo BaliMed">
                <h2 class="text-2xl md:text-3xl font-extrabold tracking-wide text-slate-800">STRUKTUR ORGANISASI</h2>
                <h3 class="text-lg md:text-xl font-semibold text-slate-700">DIVISI KEPERAWATAN</h3>
                <p class="text-slate-500">RS BaliMed Denpasar</p>
            </div>

            <div class="flex justify-center">
                <?= soPositionCard('direktur', 'Direktur RS BaliMed', $direktur, 'blue', $isAdmin, 'large') ?>
            </div>

            <div class="so-line-vertical mt-3"></div>

            <div class="flex justify-center mt-3">
                <?= soPositionCard('kadiv_keperawatan', 'Kepala Divisi Keperawatan', $kadiv, 'cyan', $isAdmin, 'large') ?>
            </div>

            <div class="so-line-vertical mt-3"></div>
            <div class="so-branch-line"><span class="left"></span><span class="right"></span></div>

            <div class="grid grid-cols-1 xl:grid-cols-2 gap-8 mt-3">
                <div class="rounded-[28px] border border-emerald-100 bg-gradient-to-br from-emerald-50 via-white to-emerald-50 p-5 md:p-6 shadow-sm">
                    <div class="flex justify-center mb-5">
                        <?= soPositionCard('kasubdiv_rajal', 'Kasubdiv Keperawatan Rawat Jalan', $kasubdivRajal, 'emerald', $isAdmin, 'small') ?>
                    </div>

                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-extrabold text-emerald-700">Unit Rawat Jalan</h3>
                        <span class="px-3 py-1 rounded-full bg-emerald-100 text-emerald-700 text-xs font-semibold">
                            <?= count($rajalUnits) ?> Unit
                        </span>
                    </div>

                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                        <?php if (!empty($rajalUnits)): ?>
                            <?php foreach ($rajalUnits as $unit): ?>
                                <?= soUnitCard($unit, 'emerald', $isAdmin) ?>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div class="text-sm text-slate-500">Tidak ada unit rawat jalan yang cocok dari master unit aktif.</div>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="rounded-[28px] border border-violet-100 bg-gradient-to-br from-violet-50 via-white to-violet-50 p-5 md:p-6 shadow-sm">
                    <div class="flex justify-center mb-5">
                        <?= soPositionCard('kasubdiv_ranap', 'Kasubdiv Keperawatan Rawat Inap', $kasubdivRanap, 'violet', $isAdmin, 'small') ?>
                    </div>

                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-extrabold text-violet-700">Unit Rawat Inap</h3>
                        <span class="px-3 py-1 rounded-full bg-violet-100 text-violet-700 text-xs font-semibold">
                            <?= count($ranapUnits) ?> Unit
                        </span>
                    </div>

                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                        <?php if (!empty($ranapUnits)): ?>
                            <?php foreach ($ranapUnits as $unit): ?>
                                <?= soUnitCard($unit, 'violet', $isAdmin) ?>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div class="text-sm text-slate-500">Tidak ada unit rawat inap yang cocok dari master unit aktif.</div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <hr class="my-8 border-slate-200">

            <div class="grid grid-cols-1 md:grid-cols-2 gap-5 items-end">
                <div class="text-sm text-slate-500">
                    <div class="font-bold text-slate-700 mb-1">Catatan</div>
                    <p>Jika nama belum muncul, pastikan pegawai sudah ada pada master pegawai, status aktif, dan memiliki profile picture pada kolom <b>photo_path</b>.</p>
                </div>

                <div class="text-right text-slate-700">
                    <p>Denpasar, <?= date('d F Y') ?></p>
                    <p><?= e((string)($direktur['position_name'] ?? 'Direktur RS BaliMed')) ?></p>
                    <br><br><br>
                    <p class="font-bold"><?= e((string)($direktur['full_name'] ?? 'Belum dipilih')) ?></p>
                </div>
            </div>
        </div>
    </div>
</div>

<?php if ($isAdmin): ?>
<div id="strukturModal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50 p-4 no-print">
    <div class="bg-white rounded-[28px] shadow-2xl w-full max-w-2xl p-6">
        <div class="flex items-center justify-between mb-5">
            <div>
                <h3 class="text-xl font-bold text-slate-800">Pilih Pejabat Struktur</h3>
                <p id="strukturModalTitle" class="text-sm text-slate-500 mt-1">-</p>
            </div>
            <button type="button" onclick="closeStrukturModal()" class="w-10 h-10 rounded-full bg-slate-100 hover:bg-slate-200 text-slate-600">
                &times;
            </button>
        </div>

        <form method="POST" action="?module=struktur_organisasi" class="space-y-4">
            <input type="hidden" name="action" value="update_structure_slot">
            <input type="hidden" name="slot_key" id="strukturSlotKey" value="">

            <div>
                <label class="block text-sm font-semibold text-slate-700 mb-1">Title Jabatan</label>
                <input
                    type="text"
                    id="strukturTitleReadonly"
                    readonly
                    class="w-full rounded-2xl border border-slate-200 bg-slate-50 px-4 py-3 text-slate-700"
                >
            </div>

            <div>
                <label class="block text-sm font-semibold text-slate-700 mb-1">Pilih Nama Pegawai</label>
                <select name="employee_id" id="strukturEmployeeId" class="so-select">
                    <option value="0">-- Belum dipilih / kosongkan --</option>
                    <?php foreach ($employees as $emp): ?>
                        <?php
                            $label = trim((string)$emp['full_name']);
                            $meta = trim((string)($emp['position_name'] ?? ''));
                            $unit = trim((string)($emp['unit_name'] ?? ''));
                            $caption = $label;
                            if ($meta !== '' || $unit !== '') {
                                $caption .= ' — ' . trim($meta . ($unit !== '' ? ' / ' . $unit : ''));
                            }
                        ?>
                        <option value="<?= (int)$emp['id'] ?>"><?= e($caption) ?></option>
                    <?php endforeach; ?>
                </select>
                <p class="text-xs text-slate-500 mt-2">
                    Setelah disimpan, nama dan foto akan otomatis mengikuti data profile pegawai terpilih.
                </p>
            </div>

            <div class="flex justify-end gap-2 pt-2">
                <button type="button" onclick="closeStrukturModal()" class="px-4 py-2.5 rounded-2xl border border-slate-300 text-slate-700">
                    Batal
                </button>
                <button type="submit" class="px-4 py-2.5 rounded-2xl bg-blue-600 text-white hover:bg-blue-700">
                    Simpan Pilihan
                </button>
            </div>
        </form>
    </div>
</div>

<script>
function openStrukturModal(slotKey, title, employeeId) {
    const modal = document.getElementById('strukturModal');
    const slotInput = document.getElementById('strukturSlotKey');
    const titleInput = document.getElementById('strukturTitleReadonly');
    const titleText = document.getElementById('strukturModalTitle');
    const select = document.getElementById('strukturEmployeeId');

    slotInput.value = slotKey || '';
    titleInput.value = title || '';
    titleText.textContent = title || '-';
    select.value = String(employeeId || 0);

    modal.classList.remove('hidden');
    modal.classList.add('flex');
}

function closeStrukturModal() {
    const modal = document.getElementById('strukturModal');
    modal.classList.add('hidden');
    modal.classList.remove('flex');
}

document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        closeStrukturModal();
    }
});
</script>
<?php endif; ?>
