<?php
// modules/data_perawat_per_unit.php
// Data Perawat per Unit + Mapping Unit Staf + Profesi/Tugas khusus Kamar Operasi
// Patch aman: mapping unit mengubah employees.unit_id; profesi/tugas tambahan disimpan pada tabel unit_staff_tasks.

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

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

if (!function_exists('dp_unit_conn')) {
    function dp_unit_conn() {
        if (function_exists('getConnection')) {
            return getConnection();
        }
        if (function_exists('db')) {
            return db();
        }
        if (class_exists('Database')) {
            $db = new Database();
            return $db->getConnection();
        }
        return null;
    }
}

$conn = dp_unit_conn();
if (!$conn) {
    echo "<div class='bg-red-50 border-l-4 border-red-500 p-4 rounded'>Koneksi database gagal.</div>";
    return;
}

if (!function_exists('dp_table_exists')) {
    function dp_table_exists(mysqli $conn, string $table): bool {
        $safe = $conn->real_escape_string($table);
        $res = $conn->query("SHOW TABLES LIKE '{$safe}'");
        return $res && $res->num_rows > 0;
    }
}

if (!function_exists('dp_column_exists')) {
    function dp_column_exists(mysqli $conn, string $table, string $column): bool {
        $safeTable = $conn->real_escape_string($table);
        $safeCol = $conn->real_escape_string($column);
        $res = $conn->query("SHOW COLUMNS FROM `{$safeTable}` LIKE '{$safeCol}'");
        return $res && $res->num_rows > 0;
    }
}

if (!function_exists('dp_first_column')) {
    function dp_first_column(mysqli $conn, string $table, array $candidates, string $fallback = ''): string {
        foreach ($candidates as $col) {
            if (dp_column_exists($conn, $table, $col)) return $col;
        }
        return $fallback;
    }
}

if (!function_exists('dp_normalize_unit_name')) {
    function dp_normalize_unit_name(string $name): string {
        $name = trim($name);
        $name = preg_replace('/\s+/', ' ', $name);
        return $name ?: 'Tanpa Unit';
    }
}

if (!function_exists('dp_is_ok_unit')) {
    function dp_is_ok_unit(string $unitName): bool {
        $name = strtolower($unitName);
        return str_contains($name, 'kamar operasi') || preg_match('/(^|\s|\/)ok(\s|\/|$)/i', $unitName);
    }
}

if (!function_exists('dp_norm_key')) {
    function dp_norm_key(string $name): string {
        $name = strtolower(trim($name));
        $name = str_replace(['.', '-', '_', '/', '&', '(', ')'], ' ', $name);
        $name = preg_replace('/\s+/', ' ', $name);
        return trim($name);
    }
}

if (!function_exists('dp_is_nursing_unit')) {
    function dp_is_nursing_unit(string $unitName): bool {
        $n = dp_norm_key($unitName);
        if ($n === '') return false;

        $patterns = [
            'igd',
            'vk', 'kamar bersalin', 'bersalin',
            'ok', 'kamar operasi', 'operasi',
            'poliklinik', 'poli',
            'hd', 'hemodialisa', 'hemodialisis',
            'pav canigara', 'canigara',
            'pav cempaka', 'cempaka',
            'pav cendana', 'cendana',
            'cempaka utara',
            'ruang bayi', 'bayi',
            'nicu',
            'icu'
        ];

        // Cempaka Utara harus dicek sebelum Cempaka biasa, tetapi keduanya tetap termasuk unit keperawatan.
        foreach ($patterns as $pattern) {
            if ($n === $pattern || str_contains($n, $pattern)) {
                // Jangan masukkan unit induk umum bernama hanya "keperawatan".
                if ($n === 'keperawatan' || $n === 'divisi keperawatan') return false;
                return true;
            }
        }
        return false;
    }
}

if (!function_exists('dp_nursing_unit_rank')) {
    function dp_nursing_unit_rank(string $unitName): int {
        $n = dp_norm_key($unitName);
        $order = [
            10 => ['igd'],
            20 => ['vk', 'kamar bersalin', 'bersalin'],
            30 => ['ok', 'kamar operasi', 'operasi'],
            40 => ['poliklinik', 'poli'],
            50 => ['hd', 'hemodialisa', 'hemodialisis'],
            60 => ['canigara'],
            70 => ['cempaka utara'],
            80 => ['cempaka'],
            90 => ['cendana'],
            100 => ['ruang bayi', 'bayi'],
            110 => ['nicu'],
            120 => ['icu'],
        ];
        foreach ($order as $rank => $keys) {
            foreach ($keys as $key) {
                if ($n === $key || str_contains($n, $key)) return $rank;
            }
        }
        return 999;
    }
}


if (!function_exists('dp_months_worked')) {
    function dp_months_worked(?string $joinDate): ?int {
        $joinDate = trim((string)$joinDate);
        if ($joinDate === '' || $joinDate === '0000-00-00') return null;
        try {
            $start = new DateTime($joinDate);
            $today = new DateTime(date('Y-m-d'));
            if ($start > $today) return 0;
            $diff = $start->diff($today);
            return ($diff->y * 12) + $diff->m;
        } catch (Throwable $e) {
            return null;
        }
    }
}

if (!function_exists('dp_format_masa_kerja')) {
    function dp_format_masa_kerja(?string $joinDate): string {
        $months = dp_months_worked($joinDate);
        if ($months === null) return 'Belum diisi';
        $years = intdiv($months, 12);
        $remMonths = $months % 12;
        if ($years <= 0) {
            return $remMonths . ' bln';
        }
        if ($remMonths <= 0) {
            return $years . ' th';
        }
        return $years . ' th ' . $remMonths . ' bln';
    }
}

if (!function_exists('dp_tenure_bucket')) {
    function dp_tenure_bucket(?string $joinDate): string {
        $months = dp_months_worked($joinDate);
        if ($months === null) return 'unknown';
        return $months < 12 ? 'baru' : 'lama';
    }
}

if (!function_exists('dp_tenure_badge')) {
    function dp_tenure_badge(?string $joinDate): string {
        $bucket = dp_tenure_bucket($joinDate);
        if ($bucket === 'baru') {
            return '<span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-bold bg-blue-100 text-blue-700">Staf Baru</span>';
        }
        if ($bucket === 'lama') {
            return '<span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-bold bg-emerald-100 text-emerald-700">Staf Lama</span>';
        }
        return '<span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-bold bg-amber-100 text-amber-700">Tanggal Masuk Kosong</span>';
    }
}

if (!function_exists('dp_pct')) {
    function dp_pct(int $part, int $total): string {
        if ($total <= 0) return '0%';
        return number_format(($part / $total) * 100, 1, ',', '.') . '%';
    }
}

// Buat tabel tambahan bila belum ada.
$conn->query("
    CREATE TABLE IF NOT EXISTS unit_staff_tasks (
        id INT AUTO_INCREMENT PRIMARY KEY,
        employee_id INT NOT NULL,
        unit_id INT NOT NULL,
        task_name VARCHAR(150) NOT NULL DEFAULT '',
        notes TEXT NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uniq_employee_unit (employee_id, unit_id),
        KEY idx_unit_id (unit_id),
        KEY idx_employee_id (employee_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
");

$flash = '';
$flashType = 'success';

$unitNameCol = dp_first_column($conn, 'units', ['name', 'unit_name', 'nama_unit', 'nama'], 'name');
$unitActiveCol = dp_first_column($conn, 'units', ['is_active', 'active', 'status'], '');

$empNameCol = dp_first_column($conn, 'employees', ['full_name', 'nama_lengkap', 'name', 'nama'], 'full_name');
$empCodeCol = dp_first_column($conn, 'employees', ['employee_code', 'nik', 'nip', 'kode'], '');
$empProfessionCol = dp_first_column($conn, 'employees', ['profession', 'profesi'], '');
$empPositionCol = dp_first_column($conn, 'employees', ['position_name', 'jabatan', 'position'], '');
$empUnitCol = dp_first_column($conn, 'employees', ['unit_id'], '');
$empJoinDateCol = dp_first_column($conn, 'employees', ['join_date', 'tanggal_masuk', 'tgl_masuk', 'start_date', 'hire_date'], '');
$empStatusCol = dp_first_column($conn, 'employees', ['employment_status', 'status'], '');

$units = [];
$whereUnit = '';
if ($unitActiveCol === 'is_active' || $unitActiveCol === 'active') {
    $whereUnit = "WHERE COALESCE(u.`{$unitActiveCol}`, 1) = 1";
}
$sqlUnits = "SELECT u.id, u.`{$unitNameCol}` AS unit_name FROM units u {$whereUnit} ORDER BY u.`{$unitNameCol}` ASC";
$resUnits = $conn->query($sqlUnits);
if ($resUnits) {
    while ($row = $resUnits->fetch_assoc()) {
        $unitNameTmp = dp_normalize_unit_name((string)$row['unit_name']);
        if (dp_is_nursing_unit($unitNameTmp)) {
            $units[(int)$row['id']] = $unitNameTmp;
        }
    }
}

uasort($units, static function ($a, $b) {
    $ra = dp_nursing_unit_rank((string)$a);
    $rb = dp_nursing_unit_rank((string)$b);
    if ($ra === $rb) return strcasecmp((string)$a, (string)$b);
    return $ra <=> $rb;
});
$nursingUnitIds = array_keys($units);
$nursingUnitIdSql = !empty($nursingUnitIds) ? implode(',', array_map('intval', $nursingUnitIds)) : '0';

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

    if ($actionPost === 'save_task') {
        $employeeId = (int)($_POST['employee_id'] ?? 0);
        $unitId = (int)($_POST['unit_id'] ?? 0);
        $taskName = trim((string)($_POST['task_name'] ?? ''));
        $notes = trim((string)($_POST['notes'] ?? ''));

        if ($employeeId > 0 && $unitId > 0) {
            $stmt = $conn->prepare("
                INSERT INTO unit_staff_tasks (employee_id, unit_id, task_name, notes)
                VALUES (?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE
                    task_name = VALUES(task_name),
                    notes = VALUES(notes),
                    updated_at = CURRENT_TIMESTAMP
            ");
            if ($stmt) {
                $stmt->bind_param('iiss', $employeeId, $unitId, $taskName, $notes);
                if ($stmt->execute()) {
                    $flash = 'Profesi/tugas berhasil disimpan.';
                } else {
                    $flash = 'Gagal menyimpan profesi/tugas: ' . $stmt->error;
                    $flashType = 'danger';
                }
                $stmt->close();
            } else {
                $flash = 'Prepare simpan profesi/tugas gagal: ' . $conn->error;
                $flashType = 'danger';
            }
        } else {
            $flash = 'Data pegawai/unit tidak valid untuk simpan profesi/tugas.';
            $flashType = 'danger';
        }
    }

    if ($actionPost === 'update_unit' || $actionPost === 'update_mapping_details') {
        $employeeId = (int)($_POST['employee_id'] ?? 0);
        $targetUnitId = (int)($_POST['target_unit_id'] ?? 0);
        $joinDateInput = trim((string)($_POST['join_date'] ?? ''));
        $joinDateValue = null;

        if ($joinDateInput !== '') {
            $ts = strtotime($joinDateInput);
            if ($ts !== false) {
                $joinDateValue = date('Y-m-d', $ts);
            }
        }

        if (!$empUnitCol) {
            $flash = 'Kolom unit_id pada tabel employees tidak ditemukan.';
            $flashType = 'danger';
        } elseif ($employeeId <= 0 || $targetUnitId <= 0 || !isset($units[$targetUnitId])) {
            $flash = 'Data pegawai atau target unit tidak valid.';
            $flashType = 'danger';
        } else {
            $setParts = ["`{$empUnitCol}` = ?"];
            $types = 'i';
            $params = [$targetUnitId];

            if ($empJoinDateCol) {
                $setParts[] = "`{$empJoinDateCol}` = ?";
                $types .= 's';
                $params[] = $joinDateValue;
            }

            if (dp_column_exists($conn, 'employees', 'updated_at')) {
                $setParts[] = "updated_at = CURRENT_TIMESTAMP";
            }

            $types .= 'i';
            $params[] = $employeeId;

            $sqlUpdate = "UPDATE employees SET " . implode(', ', $setParts) . " WHERE id = ? LIMIT 1";
            $stmt = $conn->prepare($sqlUpdate);
            if ($stmt) {
                $stmt->bind_param($types, ...$params);
                if ($stmt->execute()) {
                    $flash = 'Mapping unit dan tanggal masuk staf berhasil diperbarui.';
                } else {
                    $flash = 'Gagal update mapping/masa kerja: ' . $stmt->error;
                    $flashType = 'danger';
                }
                $stmt->close();
            } else {
                $flash = 'Prepare update mapping/masa kerja gagal: ' . $conn->error;
                $flashType = 'danger';
            }
        }
    }
}

$selectedUnit = isset($_GET['unit_id']) ? (int)$_GET['unit_id'] : 0;
$showUnmappedOnly = (int)($_GET['unmapped'] ?? 0) === 1;
$search = trim((string)($_GET['q'] ?? ''));
$tab = trim((string)($_GET['tab'] ?? 'data'));
if (!in_array($tab, ['data', 'mapping'], true)) {
    $tab = 'data';
}

$employeeSelectParts = [
    "e.id",
    "e.`{$empNameCol}` AS employee_name",
];
if ($empCodeCol) $employeeSelectParts[] = "e.`{$empCodeCol}` AS employee_code"; else $employeeSelectParts[] = "'' AS employee_code";
if ($empProfessionCol) $employeeSelectParts[] = "e.`{$empProfessionCol}` AS profession"; else $employeeSelectParts[] = "'' AS profession";
if ($empPositionCol) $employeeSelectParts[] = "e.`{$empPositionCol}` AS position_name"; else $employeeSelectParts[] = "'' AS position_name";
if ($empUnitCol) $employeeSelectParts[] = "e.`{$empUnitCol}` AS unit_id"; else $employeeSelectParts[] = "0 AS unit_id";
if ($empJoinDateCol) $employeeSelectParts[] = "e.`{$empJoinDateCol}` AS join_date"; else $employeeSelectParts[] = "NULL AS join_date";

$whereEmp = [];
if ($empStatusCol) {
    $whereEmp[] = "(e.`{$empStatusCol}` IS NULL OR e.`{$empStatusCol}` = '' OR LOWER(e.`{$empStatusCol}`) IN ('aktif','active'))";
}
if ($empProfessionCol) {
    $whereEmp[] = "(LOWER(e.`{$empProfessionCol}`) LIKE '%perawat%' OR LOWER(e.`{$empProfessionCol}`) LIKE '%bidan%' OR LOWER(e.`{$empProfessionCol}`) LIKE '%anastesi%' OR LOWER(e.`{$empProfessionCol}`) LIKE '%anestesi%' OR LOWER(e.`{$empProfessionCol}`) LIKE '%lainnya%')";
}

// Unit yang ditampilkan/dipilih hanya 12 unit pelayanan keperawatan.
// Tab Data: hanya staf yang sudah berada di unit keperawatan.
// Tab Mapping: tampilkan staf unit keperawatan + yang belum mapping + yang masih nyasar di unit non-keperawatan agar bisa dipindahkan.
if ($empUnitCol && !$showUnmappedOnly) {
    if ($tab === 'data') {
        $whereEmp[] = "e.`{$empUnitCol}` IN ({$nursingUnitIdSql})";
    }
}
if ($selectedUnit > 0 && $empUnitCol) {
    $whereEmp[] = "e.`{$empUnitCol}` = " . (int)$selectedUnit;
}
if ($showUnmappedOnly && $empUnitCol) {
    $whereEmp[] = "(e.`{$empUnitCol}` IS NULL OR e.`{$empUnitCol}` = 0 OR e.`{$empUnitCol}` NOT IN ({$nursingUnitIdSql}))";
}
if ($search !== '') {
    $safeSearch = '%' . $conn->real_escape_string($search) . '%';
    $searchParts = ["e.`{$empNameCol}` LIKE '{$safeSearch}'"];
    if ($empCodeCol) $searchParts[] = "e.`{$empCodeCol}` LIKE '{$safeSearch}'";
    if (dp_column_exists($conn, 'employees', 'nik')) $searchParts[] = "e.`nik` LIKE '{$safeSearch}'";
    $whereEmp[] = '(' . implode(' OR ', $searchParts) . ')';
}
$whereEmpSql = $whereEmp ? ('WHERE ' . implode(' AND ', $whereEmp)) : '';

$unitJoin = $empUnitCol ? "u.id = e.`{$empUnitCol}`" : "1=0";
$taskJoinUnit = $empUnitCol ? "COALESCE(e.`{$empUnitCol}`, 0)" : "0";

$sqlEmployees = "
    SELECT " . implode(",\n           ", $employeeSelectParts) . ",
           u.`{$unitNameCol}` AS unit_name,
           ust.task_name,
           ust.notes
    FROM employees e
    LEFT JOIN units u ON {$unitJoin}
    LEFT JOIN unit_staff_tasks ust ON ust.employee_id = e.id AND ust.unit_id = {$taskJoinUnit}
    {$whereEmpSql}
    ORDER BY
        CASE WHEN e.`" . ($empUnitCol ?: 'id') . "` IS NULL OR e.`" . ($empUnitCol ?: 'id') . "` = 0 THEN 0 ELSE 1 END ASC,
        u.`{$unitNameCol}` ASC,
        e.`{$empNameCol}` ASC
";

$employeesByUnit = [];
$resEmp = $conn->query($sqlEmployees);
if ($resEmp) {
    while ($row = $resEmp->fetch_assoc()) {
        $uid = (int)($row['unit_id'] ?? 0);
        if ($uid > 0 && isset($units[$uid])) {
            $uname = $row['unit_name'] ?: ($units[$uid] ?? 'Unit Tidak Terbaca');
        } elseif ($uid > 0) {
            $uname = 'Unit Non-Keperawatan / Perlu Mapping';
            $uid = -1;
        } else {
            $uname = 'Belum Ada Unit / Perlu Mapping';
        }
        if (!isset($employeesByUnit[$uid])) {
            $employeesByUnit[$uid] = [
                'unit_name' => dp_normalize_unit_name((string)$uname),
                'rows' => [],
            ];
        }
        $employeesByUnit[$uid]['rows'][] = $row;
    }
}


$tenureStats = [
    'total' => 0,
    'baru' => 0,
    'lama' => 0,
    'unknown' => 0,
];
$tenureStatsByUnit = [];

foreach ($employeesByUnit as $gUnitId => $group) {
    $unitStats = ['total' => 0, 'baru' => 0, 'lama' => 0, 'unknown' => 0];
    foreach ($group['rows'] as $row) {
        $bucket = dp_tenure_bucket($row['join_date'] ?? null);
        $unitStats['total']++;
        $unitStats[$bucket]++;

        $tenureStats['total']++;
        $tenureStats[$bucket]++;
    }
    $tenureStatsByUnit[$gUnitId] = $unitStats;
}

$unmappedCount = 0;
if ($empUnitCol) {
    $resUnmapped = $conn->query("SELECT COUNT(*) AS total FROM employees e WHERE (e.`{$empUnitCol}` IS NULL OR e.`{$empUnitCol}` = 0 OR e.`{$empUnitCol}` NOT IN ({$nursingUnitIdSql}))" . ($empStatusCol ? " AND (e.`{$empStatusCol}` IS NULL OR e.`{$empStatusCol}` = '' OR LOWER(e.`{$empStatusCol}`) IN ('aktif','active'))" : ""));
    if ($resUnmapped) {
        $unmappedCount = (int)($resUnmapped->fetch_assoc()['total'] ?? 0);
    }
}

$okRoles = [
    '',
    'Penata Anastesi',
    'Perawat Bedah',
    'Perawat Anastesi',
    'Instrumentator',
    'Sirkuler',
    'Recovery Room',
    'CSSD OK',
    'Koordinator OK',
];
?>

<div class="w-full max-w-none space-y-6">
    <div class="bg-gradient-to-r from-blue-700 to-indigo-700 text-white rounded-2xl p-6 shadow-lg">
        <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
            <div>
                <h2 class="text-2xl font-bold">Data Perawat per Unit</h2>
                <p class="text-blue-100 mt-1">Distribusi staf khusus 12 unit keperawatan, mapping database unit staf, dan komposisi masa kerja staf baru/lama.</p>
            </div>
            <div class="flex flex-wrap gap-2">
                <a href="index.php?module=data_perawat_per_unit&unmapped=1" class="inline-flex items-center gap-2 bg-red-500 hover:bg-red-600 px-4 py-2 rounded-xl font-semibold">
                    <i class="fas fa-user-tag"></i> Belum Mapping: <?= (int)$unmappedCount ?>
                </a>
                <a href="index.php?module=dashboard" class="inline-flex items-center gap-2 bg-white/15 hover:bg-white/25 px-4 py-2 rounded-xl">
                    <i class="fas fa-home"></i> Dashboard
                </a>
            </div>
        </div>
    </div>

    <?php if ($flash !== ''): ?>
        <div class="rounded-xl p-4 <?= $flashType === 'danger' ? 'bg-red-50 text-red-700 border border-red-200' : 'bg-green-50 text-green-700 border border-green-200' ?>">
            <?= e($flash) ?>
        </div>
    <?php endif; ?>

    <div class="bg-white rounded-2xl shadow p-2 flex flex-wrap gap-2">
        <a href="index.php?module=data_perawat_per_unit&tab=data" class="inline-flex items-center gap-2 px-5 py-3 rounded-xl font-bold <?= $tab === 'data' ? 'bg-blue-600 text-white shadow' : 'bg-slate-100 text-slate-700 hover:bg-slate-200' ?>">
            <i class="fas fa-users"></i> Data Staf per Unit
        </a>
        <a href="index.php?module=data_perawat_per_unit&tab=mapping" class="inline-flex items-center gap-2 px-5 py-3 rounded-xl font-bold <?= $tab === 'mapping' ? 'bg-emerald-600 text-white shadow' : 'bg-slate-100 text-slate-700 hover:bg-slate-200' ?>">
            <i class="fas fa-database"></i> Mapping Database
            <?php if ($unmappedCount > 0): ?>
                <span class="ml-1 bg-red-500 text-white text-xs px-2 py-1 rounded-full"><?= (int)$unmappedCount ?></span>
            <?php endif; ?>
        </a>
    </div>

    <?php if ($tab === 'mapping'): ?>
    <div class="bg-amber-50 border border-amber-200 rounded-2xl p-5 text-amber-900">
        <div class="flex gap-3">
            <div class="text-xl"><i class="fas fa-info-circle"></i></div>
            <div>
                <div class="font-bold">Mapping Database Unit Staf</div>
                <div class="text-sm mt-1">
                    Tab ini khusus untuk merapikan unit staf di database. Dropdown <b>Mapping Unit</b> hanya berisi unit keperawatan. Gunakan untuk memindahkan staf yang nyasar ke unit umum seperti <b>KEPERAWATAN</b>, unit dobel, atau belum punya unit. Isi juga <b>Tanggal Masuk</b> agar komposisi staf baru/lama dapat dihitung otomatis.
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div class="bg-white rounded-2xl shadow border border-slate-100 p-5">
            <div class="text-sm text-slate-500 font-semibold">Total Staf Ditampilkan</div>
            <div class="text-3xl font-extrabold text-slate-800 mt-1"><?= (int)$tenureStats['total'] ?></div>
            <div class="text-xs text-slate-400 mt-1">Sesuai filter halaman ini</div>
        </div>
        <div class="bg-blue-50 rounded-2xl shadow border border-blue-100 p-5">
            <div class="text-sm text-blue-700 font-semibold">Staf Baru (&lt; 1 tahun)</div>
            <div class="text-3xl font-extrabold text-blue-800 mt-1"><?= (int)$tenureStats['baru'] ?></div>
            <div class="text-xs text-blue-600 mt-1"><?= e(dp_pct((int)$tenureStats['baru'], (int)$tenureStats['total'])) ?> dari total</div>
        </div>
        <div class="bg-emerald-50 rounded-2xl shadow border border-emerald-100 p-5">
            <div class="text-sm text-emerald-700 font-semibold">Staf Lama (≥ 1 tahun)</div>
            <div class="text-3xl font-extrabold text-emerald-800 mt-1"><?= (int)$tenureStats['lama'] ?></div>
            <div class="text-xs text-emerald-600 mt-1"><?= e(dp_pct((int)$tenureStats['lama'], (int)$tenureStats['total'])) ?> dari total</div>
        </div>
        <div class="bg-amber-50 rounded-2xl shadow border border-amber-100 p-5">
            <div class="text-sm text-amber-700 font-semibold">Tanggal Masuk Kosong</div>
            <div class="text-3xl font-extrabold text-amber-800 mt-1"><?= (int)$tenureStats['unknown'] ?></div>
            <div class="text-xs text-amber-600 mt-1">Perlu dilengkapi di tab Mapping Database</div>
        </div>
    </div>

    <div class="bg-white rounded-2xl shadow p-5">
        <form method="GET"" class="grid grid-cols-1 md:grid-cols-4 gap-3 md:items-end">
            <input type="hidden" name="module" value="data_perawat_per_unit">
            <input type="hidden" name="tab" value="<?= e($tab) ?>">
            <div>
                <label class="block text-sm font-semibold text-slate-700 mb-1">Cari Nama/NIK</label>
                <input type="text" name="q" value="<?= e($search) ?>" placeholder="Ketik nama atau NIK" class="w-full border rounded-xl px-4 py-2">
            </div>
            <div>
                <label class="block text-sm font-semibold text-slate-700 mb-1">Filter Unit</label>
                <select name="unit_id" class="w-full border rounded-xl px-4 py-2">
                    <option value="0">Semua Unit</option>
                    <?php foreach ($units as $id => $name): ?>
                        <option value="<?= (int)$id ?>" <?= $selectedUnit === (int)$id ? 'selected' : '' ?>>
                            <?= e($name) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <?php if ($tab === 'mapping'): ?>
                <label class="flex items-center gap-2 border rounded-xl px-4 py-2 h-[42px] bg-slate-50">
                    <input type="checkbox" name="unmapped" value="1" <?= $showUnmappedOnly ? 'checked' : '' ?>>
                    <span class="text-sm font-semibold text-slate-700">Hanya belum mapping</span>
                </label>
            <?php else: ?>
                <div class="border rounded-xl px-4 py-2 h-[42px] bg-slate-50 text-sm text-slate-600 flex items-center">
                    Menampilkan rekap staf unit keperawatan
                </div>
            <?php endif; ?>
            <div class="flex gap-2">
                <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white rounded-xl px-5 py-2 font-semibold">
                    <i class="fas fa-filter mr-1"></i> Tampilkan
                </button>
                <a href="index.php?module=data_perawat_per_unit&tab=<?= e($tab) ?>" class="bg-slate-100 hover:bg-slate-200 rounded-xl px-5 py-2 font-semibold text-slate-700">
                    Reset
                </a>
            </div>
        </form>
    </div>

    <?php if (empty($employeesByUnit)): ?>
        <div class="bg-yellow-50 border border-yellow-200 text-yellow-800 rounded-2xl p-6">
            Belum ada data perawat/bidan yang cocok untuk ditampilkan.
        </div>
    <?php else: ?>
        <?php foreach ($employeesByUnit as $unitId => $group): ?>
            <?php
                $unitName = (string)$group['unit_name'];
                $isOk = dp_is_ok_unit($unitName);
                $isUnmappedGroup = (int)$unitId <= 0;
            ?>
            <div class="bg-white rounded-2xl shadow overflow-hidden border border-slate-100">
                <div class="px-5 py-4 <?= $isUnmappedGroup ? 'bg-red-700 text-white' : ($isOk ? 'bg-purple-700 text-white' : 'bg-slate-50 text-slate-800') ?>">
                    <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-2">
                        <div>
                            <h3 class="text-lg font-bold">
                                <?= e($unitName) ?>
                                <?php if ($isOk): ?>
                                    <span class="ml-2 text-xs bg-white/20 px-2 py-1 rounded-full">Profesi/Tugas OK aktif</span>
                                <?php endif; ?>
                                <?php if ($isUnmappedGroup): ?>
                                    <span class="ml-2 text-xs bg-white/20 px-2 py-1 rounded-full">Wajib mapping</span>
                                <?php endif; ?>
                            </h3>
                            <?php $uStats = $tenureStatsByUnit[$unitId] ?? ['total' => 0, 'baru' => 0, 'lama' => 0, 'unknown' => 0]; ?>
                            <p class="<?= ($isOk || $isUnmappedGroup) ? 'text-white/80' : 'text-slate-500' ?> text-sm">
                                Total staf: <?= count($group['rows']) ?> orang · Baru: <?= (int)$uStats['baru'] ?> (<?= e(dp_pct((int)$uStats['baru'], (int)$uStats['total'])) ?>) · Lama: <?= (int)$uStats['lama'] ?> (<?= e(dp_pct((int)$uStats['lama'], (int)$uStats['total'])) ?>) · Tgl masuk kosong: <?= (int)$uStats['unknown'] ?>
                            </p>
                        </div>
                    </div>
                </div>

                <div class="overflow-x-auto">
                    <table class="w-full text-sm">
                        <thead class="bg-slate-100 text-slate-700">
                            <tr>
                                <th class="px-4 py-3 text-left w-16">No</th>
                                <th class="px-4 py-3 text-left min-w-[260px]">Nama</th>
                                <th class="px-4 py-3 text-left">NIK/Kode</th>
                                <th class="px-4 py-3 text-left">Profesi DB</th>
                                <th class="px-4 py-3 text-left min-w-[190px]">Jabatan</th>
                                <th class="px-4 py-3 text-left min-w-[150px]">Tgl Masuk</th>
                                <th class="px-4 py-3 text-left min-w-[170px]">Masa Kerja</th>
                                <?php if ($tab === 'mapping'): ?>
                                    <th class="px-4 py-3 text-left min-w-[280px]">Mapping Unit</th>
                                <?php endif; ?>
                                <th class="px-4 py-3 text-left min-w-[260px]">Profesi/Tugas di Unit</th>
                                <th class="px-4 py-3 text-left min-w-[220px]">Catatan</th>
                                <?php if ($tab === 'data'): ?>
                                    <th class="px-4 py-3 text-center">Simpan Tugas</th>
                                <?php endif; ?>
                            </tr>
                        </thead>
                        <tbody class="divide-y">
                            <?php foreach ($group['rows'] as $i => $row): ?>
                                <?php
                                    $taskName = (string)($row['task_name'] ?? '');
                                    $notes = (string)($row['notes'] ?? '');
                                    $rowUnitId = (int)($row['unit_id'] ?? 0);
                                    $joinDate = (string)($row['join_date'] ?? '');
                                    $employeeId = (int)$row['id'];
                                ?>
                                <tr class="hover:bg-slate-50 <?= $isUnmappedGroup ? 'bg-red-50/40' : '' ?>">
                                    <td class="px-4 py-3 align-top"><?= $i + 1 ?></td>
                                    <td class="px-4 py-3 align-top font-semibold text-slate-800"><?= e($row['employee_name'] ?? '-') ?></td>
                                    <td class="px-4 py-3 align-top text-slate-600"><?= e($row['employee_code'] ?? '-') ?></td>
                                    <td class="px-4 py-3 align-top"><?= e($row['profession'] ?? '-') ?></td>
                                    <td class="px-4 py-3 align-top"><?= e($row['position_name'] ?? '-') ?></td>
                                    <td class="px-4 py-3 align-top"><?= $joinDate !== '' && $joinDate !== '0000-00-00' ? e(date('d/m/Y', strtotime($joinDate))) : '<span class="text-amber-600 font-semibold">Belum diisi</span>' ?></td>
                                    <td class="px-4 py-3 align-top">
                                        <div class="font-semibold text-slate-800"><?= e(dp_format_masa_kerja($joinDate)) ?></div>
                                        <div class="mt-1"><?= dp_tenure_badge($joinDate) ?></div>
                                    </td>
                                    <?php if ($tab === 'mapping'): ?>
                                    <td class="px-4 py-3 align-top">
                                        <form method="POST" class="flex flex-col gap-2">
                                            <input type="hidden" name="action" value="update_mapping_details">
                                            <input type="hidden" name="employee_id" value="<?= $employeeId ?>">
                                            <div class="flex flex-col sm:flex-row gap-2">
                                                <select name="target_unit_id" class="border rounded-lg px-3 py-2 w-full min-w-[190px] <?= $isUnmappedGroup ? 'border-red-400 bg-red-50' : '' ?>">
                                                    <option value="0">-- pilih unit --</option>
                                                    <?php foreach ($units as $id => $name): ?>
                                                        <option value="<?= (int)$id ?>" <?= $rowUnitId === (int)$id ? 'selected' : '' ?>>
                                                            <?= e($name) ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                                <input type="date" name="join_date" value="<?= ($joinDate !== '' && $joinDate !== '0000-00-00') ? e($joinDate) : '' ?>" class="border rounded-lg px-3 py-2 w-full sm:w-[165px]" title="Tanggal mulai bekerja">
                                                <button type="submit" class="bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg px-3 py-2 font-semibold whitespace-nowrap" title="Simpan mapping unit dan tanggal masuk">
                                                    <i class="fas fa-save"></i>
                                                </button>
                                            </div>
                                            <div class="text-xs text-slate-500">Tanggal masuk dipakai menghitung masa kerja.</div>
                                        </form>
                                    </td>
                                    <?php endif; ?>
                                    <?php if ($tab === 'data'): ?>
                                        <td class="px-4 py-3 align-top">
                                            <form method="POST" class="flex flex-col gap-2">
                                                <input type="hidden" name="action" value="save_task">
                                                <input type="hidden" name="employee_id" value="<?= $employeeId ?>">
                                                <input type="hidden" name="unit_id" value="<?= (int)$rowUnitId ?>">

                                                <?php if ($isOk): ?>
                                                    <select name="task_name" class="border rounded-lg px-3 py-2 w-full" <?= $rowUnitId <= 0 ? 'disabled' : '' ?>>
                                                        <?php foreach ($okRoles as $roleOption): ?>
                                                            <option value="<?= e($roleOption) ?>" <?= $taskName === $roleOption ? 'selected' : '' ?>>
                                                                <?= $roleOption === '' ? '-- pilih profesi/tugas OK --' : e($roleOption) ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                <?php else: ?>
                                                    <input
                                                        type="text"
                                                        name="task_name"
                                                        value="<?= e($taskName) ?>"
                                                        placeholder="Isi tugas/profesi di unit"
                                                        class="border rounded-lg px-3 py-2 w-full"
                                                        <?= $rowUnitId <= 0 ? 'disabled' : '' ?>
                                                    >
                                                <?php endif; ?>
                                        </td>
                                        <td class="px-4 py-3 align-top">
                                                <textarea name="notes" rows="2" class="border rounded-lg px-3 py-2 w-full resize-y" placeholder="Catatan opsional" <?= $rowUnitId <= 0 ? 'disabled' : '' ?>><?= e($notes) ?></textarea>
                                        </td>
                                        <td class="px-4 py-3 align-top text-center">
                                                <?php if ($rowUnitId > 0): ?>
                                                    <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white rounded-lg px-4 py-2 font-semibold" title="Simpan profesi/tugas">
                                                        <i class="fas fa-save"></i>
                                                    </button>
                                                <?php else: ?>
                                                    <span class="inline-flex items-center text-xs text-red-600 font-semibold">Mapping unit dulu</span>
                                                <?php endif; ?>
                                            </form>
                                        </td>
                                    <?php else: ?>
                                        <td class="px-4 py-3 align-top text-slate-700"><?= e($taskName !== '' ? $taskName : '-') ?></td>
                                        <td class="px-4 py-3 align-top text-slate-600"><?= e($notes !== '' ? $notes : '-') ?></td>
                                    <?php endif; ?>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>
