<?php
declare(strict_types=1);

/**
 * modules/penugasan_manajemen_keperawatan/index.php
 * Modul Penugasan Manajemen Keperawatan
 * - Input penugasan oleh -> untuk siapa
 * - Jenis: urgent, biasa, rutin
 * - Laporan hasil oleh penerima penugasan
 * - Monitoring status dan rekap penerima tugas terbanyak
 */

if (!isset($conn) || !($conn instanceof mysqli)) {
    require_once __DIR__ . '/../../config/database.php';
    $conn = function_exists('getConnection') ? getConnection() : getAppConnection();
}
$conn->set_charset('utf8mb4');

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

if (!function_exists('pmk_date_id')) {
    function pmk_date_id(?string $date): string
    {
        if (!$date || $date === '0000-00-00') return '-';
        $ts = strtotime($date);
        return $ts ? date('d/m/Y', $ts) : '-';
    }
}

if (!function_exists('pmk_badge')) {
    function pmk_badge(string $status): string
    {
        $map = [
            'pending'  => 'bg-slate-100 text-slate-700 border-slate-200',
            'onproses' => 'bg-blue-100 text-blue-700 border-blue-200',
            'selesai'  => 'bg-emerald-100 text-emerald-700 border-emerald-200',
            'batal'    => 'bg-rose-100 text-rose-700 border-rose-200',
        ];
        return $map[$status] ?? 'bg-slate-100 text-slate-700 border-slate-200';
    }
}

if (!function_exists('pmk_type_badge')) {
    function pmk_type_badge(string $type): string
    {
        $map = [
            'urgent' => 'bg-red-100 text-red-700 border-red-200',
            'biasa'  => 'bg-amber-100 text-amber-700 border-amber-200',
            'rutin'  => 'bg-indigo-100 text-indigo-700 border-indigo-200',
        ];
        return $map[$type] ?? 'bg-slate-100 text-slate-700 border-slate-200';
    }
}

if (!function_exists('pmk_redirect')) {
    function pmk_redirect(string $url): void
    {
        echo '<script>window.location.href=' . json_encode($url) . ';</script>';
        echo '<noscript><meta http-equiv="refresh" content="0;url=' . pmk_h($url) . '"></noscript>';
        exit;
    }
}

$currentEmployeeId = (int)($_SESSION['user']['employee_id'] ?? $_SESSION['user_id'] ?? 0);
$currentRole = strtolower((string)($_SESSION['user_role'] ?? $_SESSION['user']['role'] ?? 'viewer'));
$isAdmin = in_array($currentRole, ['admin', 'superadmin'], true);
$isSuperAdmin = ($currentRole === 'superadmin');
$moduleUrl = 'index.php?module=penugasan_manajemen_keperawatan';
$flash = '';
$flashType = 'success';

// Ambil daftar pegawai aktif untuk dropdown.
$employees = [];
$empSql = "
    SELECT e.id, e.nik, e.full_name, e.position_name, COALESCE(u.name, '-') AS unit_name
    FROM employees e
    LEFT JOIN units u ON u.id = e.unit_id
    WHERE e.employment_status = 'aktif'
    ORDER BY e.full_name ASC
";
if ($res = $conn->query($empSql)) {
    while ($row = $res->fetch_assoc()) {
        $employees[] = $row;
    }
}

// Simpan penugasan baru.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = trim((string)($_POST['action'] ?? ''));

    if ($action === 'create_assignment') {
        $assignedBy = (int)($_POST['assigned_by_employee_id'] ?? 0);
        $assignedTo = (int)($_POST['assigned_to_employee_id'] ?? 0);
        $taskType = trim((string)($_POST['task_type'] ?? 'biasa'));
        $taskDescription = trim((string)($_POST['task_description'] ?? ''));
        $startDate = trim((string)($_POST['start_date'] ?? '')) ?: null;
        $endDate = trim((string)($_POST['end_date'] ?? '')) ?: null;

        if ($assignedBy <= 0 || $assignedTo <= 0 || $taskDescription === '' || !in_array($taskType, ['urgent', 'biasa', 'rutin'], true)) {
            $flash = 'Data belum lengkap. Pastikan pemberi tugas, penerima tugas, jenis, dan isi penugasan sudah diisi.';
            $flashType = 'error';
        } else {
            $stmt = $conn->prepare("INSERT INTO nursing_management_assignments
                (assigned_by_employee_id, assigned_to_employee_id, task_type, task_description, start_date, end_date, status, created_by_employee_id)
                VALUES (?, ?, ?, ?, ?, ?, 'pending', ?)");
            if (!$stmt) {
                $flash = 'Prepare gagal: ' . $conn->error;
                $flashType = 'error';
            } else {
                $stmt->bind_param('iissssi', $assignedBy, $assignedTo, $taskType, $taskDescription, $startDate, $endDate, $currentEmployeeId);
                if ($stmt->execute()) {
                    pmk_redirect($moduleUrl . '&saved=1');
                }
                $flash = 'Gagal menyimpan penugasan: ' . $stmt->error;
                $flashType = 'error';
                $stmt->close();
            }
        }
    }

    if ($action === 'update_report') {
        $id = (int)($_POST['id'] ?? 0);
        $status = trim((string)($_POST['status'] ?? 'pending'));
        $startDate = trim((string)($_POST['start_date'] ?? '')) ?: null;
        $endDate = trim((string)($_POST['end_date'] ?? '')) ?: null;
        $resultReport = trim((string)($_POST['result_report'] ?? ''));
        $responseNote = trim((string)($_POST['response_note'] ?? ''));

        if ($id <= 0 || !in_array($status, ['pending', 'onproses', 'selesai', 'batal'], true)) {
            $flash = 'Data laporan tidak valid.';
            $flashType = 'error';
        } else {
            $check = $conn->prepare("SELECT assigned_to_employee_id FROM nursing_management_assignments WHERE id = ? LIMIT 1");
            $check->bind_param('i', $id);
            $check->execute();
            $owner = $check->get_result()->fetch_assoc();
            $check->close();

            if (!$owner) {
                $flash = 'Data penugasan tidak ditemukan.';
                $flashType = 'error';
            } elseif (!$isAdmin && (int)$owner['assigned_to_employee_id'] !== $currentEmployeeId) {
                $flash = 'Akses ditolak. Laporan hanya bisa diisi oleh penerima tugas atau admin.';
                $flashType = 'error';
            } else {
                $completedAtSql = ($status === 'selesai') ? 'completed_at = IFNULL(completed_at, NOW()),' : 'completed_at = NULL,';
                $stmt = $conn->prepare("UPDATE nursing_management_assignments
                    SET start_date = ?, end_date = ?, status = ?, result_report = ?, response_note = ?, {$completedAtSql} updated_at = NOW()
                    WHERE id = ?");
                if (!$stmt) {
                    $flash = 'Prepare gagal: ' . $conn->error;
                    $flashType = 'error';
                } else {
                    $stmt->bind_param('sssssi', $startDate, $endDate, $status, $resultReport, $responseNote, $id);
                    if ($stmt->execute()) {
                        pmk_redirect($moduleUrl . '&updated=1');
                    }
                    $flash = 'Gagal update laporan: ' . $stmt->error;
                    $flashType = 'error';
                    $stmt->close();
                }
            }
        }
    }

    if ($action === 'delete_assignment') {
        $id = (int)($_POST['id'] ?? 0);
        if (!$isSuperAdmin) {
            $flash = 'Akses hapus hanya untuk superadmin.';
            $flashType = 'error';
        } elseif ($id > 0) {
            $stmt = $conn->prepare("DELETE FROM nursing_management_assignments WHERE id = ?");
            $stmt->bind_param('i', $id);
            if ($stmt->execute()) {
                pmk_redirect($moduleUrl . '&deleted=1');
            }
            $flash = 'Gagal menghapus data: ' . $stmt->error;
            $flashType = 'error';
            $stmt->close();
        }
    }
}

if (isset($_GET['saved'])) { $flash = 'Penugasan berhasil disimpan.'; }
if (isset($_GET['updated'])) { $flash = 'Laporan hasil penugasan berhasil diperbarui.'; }
if (isset($_GET['deleted'])) { $flash = 'Data penugasan berhasil dihapus.'; }

// Filter.
$q = trim((string)($_GET['q'] ?? ''));
$statusFilter = trim((string)($_GET['status'] ?? ''));
$typeFilter = trim((string)($_GET['type'] ?? ''));
$mine = trim((string)($_GET['mine'] ?? ''));
$where = [];
$params = [];
$types = '';

if ($q !== '') {
    $where[] = "(by_emp.full_name LIKE CONCAT('%', ?, '%') OR to_emp.full_name LIKE CONCAT('%', ?, '%') OR a.task_description LIKE CONCAT('%', ?, '%') OR a.result_report LIKE CONCAT('%', ?, '%'))";
    $params = array_merge($params, [$q, $q, $q, $q]);
    $types .= 'ssss';
}
if (in_array($statusFilter, ['pending', 'onproses', 'selesai', 'batal'], true)) {
    $where[] = 'a.status = ?';
    $params[] = $statusFilter;
    $types .= 's';
}
if (in_array($typeFilter, ['urgent', 'biasa', 'rutin'], true)) {
    $where[] = 'a.task_type = ?';
    $params[] = $typeFilter;
    $types .= 's';
}
if ($mine === '1' && $currentEmployeeId > 0) {
    $where[] = '(a.assigned_to_employee_id = ? OR a.assigned_by_employee_id = ?)';
    $params[] = $currentEmployeeId;
    $params[] = $currentEmployeeId;
    $types .= 'ii';
}
$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

// Statistik ringkas.
$stats = ['total' => 0, 'pending' => 0, 'onproses' => 0, 'selesai' => 0, 'batal' => 0, 'urgent' => 0];
$statSql = "SELECT status, COUNT(*) total FROM nursing_management_assignments GROUP BY status";
if ($res = $conn->query($statSql)) {
    while ($row = $res->fetch_assoc()) {
        $stats[$row['status']] = (int)$row['total'];
        $stats['total'] += (int)$row['total'];
    }
}
if ($res = $conn->query("SELECT COUNT(*) total FROM nursing_management_assignments WHERE task_type = 'urgent' AND status NOT IN ('selesai','batal')")) {
    $stats['urgent'] = (int)($res->fetch_assoc()['total'] ?? 0);
}

// Daftar penugasan.
$listSql = "
    SELECT a.*,
           by_emp.full_name AS assigned_by_name, by_emp.nik AS assigned_by_nik,
           to_emp.full_name AS assigned_to_name, to_emp.nik AS assigned_to_nik,
           u.name AS assigned_to_unit,
           CASE
               WHEN a.status = 'selesai' AND a.end_date IS NOT NULL AND DATE(a.completed_at) <= a.end_date THEN 'Tepat waktu'
               WHEN a.status = 'selesai' AND a.end_date IS NOT NULL AND DATE(a.completed_at) > a.end_date THEN 'Terlambat'
               WHEN a.status IN ('pending','onproses') AND a.end_date IS NOT NULL AND CURDATE() > a.end_date THEN 'Melewati target'
               WHEN a.status IN ('pending','onproses') THEN 'Dalam proses'
               WHEN a.status = 'batal' THEN 'Dibatalkan'
               ELSE '-'
           END AS response_status
    FROM nursing_management_assignments a
    LEFT JOIN employees by_emp ON by_emp.id = a.assigned_by_employee_id
    LEFT JOIN employees to_emp ON to_emp.id = a.assigned_to_employee_id
    LEFT JOIN units u ON u.id = to_emp.unit_id
    {$whereSql}
    ORDER BY FIELD(a.task_type,'urgent','biasa','rutin'), FIELD(a.status,'pending','onproses','selesai','batal'), a.created_at DESC
    LIMIT 300
";
$stmt = $conn->prepare($listSql);
$assignments = [];
if ($stmt) {
    if ($params) {
        $stmt->bind_param($types, ...$params);
    }
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $assignments[] = $row;
    }
    $stmt->close();
} else {
    $flash = 'Query daftar gagal: ' . $conn->error;
    $flashType = 'error';
}

// Rekap nama yang sering mendapat penugasan.
$topAssigned = [];
$topSql = "
    SELECT e.full_name, e.nik, COALESCE(u.name, '-') AS unit_name,
           COUNT(a.id) AS total_task,
           SUM(a.status = 'selesai') AS total_done,
           SUM(a.status IN ('pending','onproses')) AS total_open,
           SUM(a.task_type = 'urgent') AS total_urgent,
           ROUND(AVG(CASE WHEN a.status='selesai' AND a.start_date IS NOT NULL AND a.completed_at IS NOT NULL THEN DATEDIFF(DATE(a.completed_at), a.start_date) END), 1) AS avg_days
    FROM nursing_management_assignments a
    JOIN employees e ON e.id = a.assigned_to_employee_id
    LEFT JOIN units u ON u.id = e.unit_id
    GROUP BY e.id, e.full_name, e.nik, u.name
    ORDER BY total_task DESC, total_done DESC
    LIMIT 10
";
if ($res = $conn->query($topSql)) {
    while ($row = $res->fetch_assoc()) {
        $topAssigned[] = $row;
    }
}
?>

<style>
.pmk-card{background:#fff;border:1px solid #e2e8f0;border-radius:22px;box-shadow:0 14px 35px rgba(15,23,42,.06)}
.pmk-input{width:100%;border:1px solid #cbd5e1;border-radius:14px;padding:.72rem .9rem;font-size:.9rem;background:#fff;outline:none;transition:.18s}
.pmk-input:focus{border-color:#2563eb;box-shadow:0 0 0 4px rgba(37,99,235,.10)}
.pmk-label{display:block;font-size:.78rem;font-weight:800;color:#334155;margin-bottom:.4rem;text-transform:uppercase;letter-spacing:.035em}
.pmk-btn{display:inline-flex;align-items:center;justify-content:center;gap:.5rem;border-radius:14px;padding:.72rem 1rem;font-weight:800;font-size:.87rem;transition:.18s;text-decoration:none;border:0;cursor:pointer}
.pmk-btn-primary{background:linear-gradient(135deg,#2563eb,#4f46e5);color:#fff;box-shadow:0 12px 24px rgba(37,99,235,.22)}
.pmk-btn-primary:hover{transform:translateY(-1px);box-shadow:0 16px 30px rgba(37,99,235,.28)}
.pmk-btn-soft{background:#f8fafc;color:#334155;border:1px solid #e2e8f0}
.pmk-btn-danger{background:#fee2e2;color:#b91c1c;border:1px solid #fecaca}
.pmk-badge{display:inline-flex;align-items:center;gap:.35rem;border:1px solid;border-radius:999px;padding:.25rem .62rem;font-size:.73rem;font-weight:800;white-space:nowrap}
.pmk-table th{font-size:.72rem;text-transform:uppercase;letter-spacing:.04em;color:#64748b;background:#f8fafc;border-bottom:1px solid #e2e8f0;padding:.8rem;text-align:left}
.pmk-table td{border-bottom:1px solid #eef2f7;padding:.82rem;vertical-align:top;font-size:.86rem;color:#334155}
.pmk-modal{display:none;position:fixed;inset:0;z-index:9999;background:rgba(15,23,42,.52);align-items:center;justify-content:center;padding:1.25rem}
.pmk-modal:target{display:flex}
.pmk-modal-box{width:min(1120px,98vw);max-height:94vh;overflow:auto;background:#fff;border-radius:28px;box-shadow:0 30px 80px rgba(15,23,42,.28)}
.pmk-report-form{padding:1.35rem 1.55rem 1.55rem}
.pmk-report-textarea{min-height:210px;resize:vertical}
.pmk-response-textarea{min-height:125px;resize:vertical}
@media (max-width:768px){.pmk-modal{padding:.65rem}.pmk-modal-box{width:99vw;max-height:96vh;border-radius:20px}.pmk-report-form{padding:1rem}}
.pmk-search-select{position:relative}
.pmk-search-dropdown{display:none;position:absolute;z-index:80;top:calc(100% + 6px);left:0;right:0;max-height:260px;overflow:auto;background:#fff;border:1px solid #cbd5e1;border-radius:16px;box-shadow:0 20px 45px rgba(15,23,42,.16);padding:.45rem}
.pmk-search-select.open .pmk-search-dropdown{display:block}
.pmk-search-option{width:100%;display:block;text-align:left;border:0;background:#fff;border-radius:12px;padding:.72rem .85rem;cursor:pointer;transition:.15s}
.pmk-search-option:hover{background:#eff6ff}
.pmk-search-option .name{font-weight:800;color:#0f172a;font-size:.88rem}
.pmk-search-option .meta{font-size:.74rem;color:#64748b;margin-top:.12rem}
.pmk-empty-search{display:none;padding:.85rem;color:#94a3b8;font-size:.85rem;text-align:center}
.pmk-quick-search{position:relative}
.pmk-quick-search i{position:absolute;left:14px;top:50%;transform:translateY(-50%);color:#64748b}
.pmk-quick-search input{padding-left:2.4rem}
</style>

<div class="space-y-6">
    <div class="pmk-card overflow-hidden">
        <div class="p-6 bg-gradient-to-br from-blue-600 via-indigo-600 to-violet-600 text-white">
            <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
                <div>
                    <div class="text-sm font-bold uppercase tracking-wider text-blue-100">Modul Manajemen Keperawatan</div>
                    <h2 class="text-2xl md:text-3xl font-extrabold mt-1">Penugasan Manajemen Keperawatan</h2>
                    <p class="text-blue-50 mt-2 max-w-3xl">Input penugasan, laporan hasil, status penyelesaian, dan rekap staf yang paling sering mendapat penugasan.</p>
                </div>
                <a href="<?= pmk_h($moduleUrl) ?>" class="pmk-btn bg-white text-blue-700">
                    <i class="fas fa-rotate"></i> Refresh
                </a>
            </div>
        </div>

        <?php if ($flash !== ''): ?>
            <div class="mx-6 mt-5 rounded-2xl border p-4 <?= $flashType === 'error' ? 'bg-rose-50 border-rose-200 text-rose-700' : 'bg-emerald-50 border-emerald-200 text-emerald-700' ?>">
                <i class="fas <?= $flashType === 'error' ? 'fa-triangle-exclamation' : 'fa-check-circle' ?> mr-2"></i><?= pmk_h($flash) ?>
            </div>
        <?php endif; ?>

        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-6 gap-4 p-6">
            <div class="rounded-2xl bg-slate-50 border border-slate-200 p-4"><div class="text-xs font-bold text-slate-500 uppercase">Total</div><div class="text-3xl font-extrabold text-slate-800 mt-1"><?= (int)$stats['total'] ?></div></div>
            <div class="rounded-2xl bg-red-50 border border-red-100 p-4"><div class="text-xs font-bold text-red-500 uppercase">Urgent Aktif</div><div class="text-3xl font-extrabold text-red-700 mt-1"><?= (int)$stats['urgent'] ?></div></div>
            <div class="rounded-2xl bg-slate-50 border border-slate-200 p-4"><div class="text-xs font-bold text-slate-500 uppercase">Pending</div><div class="text-3xl font-extrabold text-slate-700 mt-1"><?= (int)$stats['pending'] ?></div></div>
            <div class="rounded-2xl bg-blue-50 border border-blue-100 p-4"><div class="text-xs font-bold text-blue-500 uppercase">On Proses</div><div class="text-3xl font-extrabold text-blue-700 mt-1"><?= (int)$stats['onproses'] ?></div></div>
            <div class="rounded-2xl bg-emerald-50 border border-emerald-100 p-4"><div class="text-xs font-bold text-emerald-500 uppercase">Selesai</div><div class="text-3xl font-extrabold text-emerald-700 mt-1"><?= (int)$stats['selesai'] ?></div></div>
            <div class="rounded-2xl bg-rose-50 border border-rose-100 p-4"><div class="text-xs font-bold text-rose-500 uppercase">Batal</div><div class="text-3xl font-extrabold text-rose-700 mt-1"><?= (int)$stats['batal'] ?></div></div>
        </div>
    </div>

    <div class="grid grid-cols-1 xl:grid-cols-3 gap-6">
        <div class="xl:col-span-1 pmk-card p-6">
            <h3 class="text-lg font-extrabold text-slate-800 mb-1"><i class="fas fa-plus-circle text-blue-600 mr-2"></i>Input Penugasan</h3>
            <p class="text-sm text-slate-500 mb-5">Pilih pemberi tugas, penerima tugas, jenis, dan isi penugasan.</p>

            <form method="post" class="space-y-4">
                <input type="hidden" name="action" value="create_assignment">
                <div>
                    <label class="pmk-label">Penugasan Oleh</label>
                    <div class="pmk-search-select" data-search-select>
                        <input type="hidden" name="assigned_by_employee_id" value="<?= (int)$currentEmployeeId ?>" required>
                        <input type="text" class="pmk-input" data-search-input placeholder="Ketik nama / NIK / unit pemberi tugas..." autocomplete="off"
                               value="<?php foreach ($employees as $emp) { if ((int)$emp['id'] === $currentEmployeeId) { echo pmk_h($emp['full_name'] . ' — ' . $emp['unit_name']); break; } } ?>">
                        <div class="pmk-search-dropdown">
                            <?php foreach ($employees as $emp): ?>
                                <button type="button" class="pmk-search-option"
                                        data-value="<?= (int)$emp['id'] ?>"
                                        data-label="<?= pmk_h($emp['full_name'] . ' — ' . $emp['unit_name']) ?>"
                                        data-keywords="<?= pmk_h(strtolower($emp['full_name'] . ' ' . $emp['nik'] . ' ' . $emp['unit_name'] . ' ' . $emp['position_name'])) ?>">
                                    <div class="name"><?= pmk_h($emp['full_name']) ?></div>
                                    <div class="meta">NIK: <?= pmk_h($emp['nik']) ?> • <?= pmk_h($emp['unit_name']) ?> • <?= pmk_h($emp['position_name']) ?></div>
                                </button>
                            <?php endforeach; ?>
                            <div class="pmk-empty-search">Nama tidak ditemukan</div>
                        </div>
                    </div>
                </div>
                <div>
                    <label class="pmk-label">Untuk Siapa</label>
                    <div class="pmk-search-select" data-search-select>
                        <input type="hidden" name="assigned_to_employee_id" value="" required>
                        <input type="text" class="pmk-input" data-search-input placeholder="Ketik nama / NIK / unit penerima tugas..." autocomplete="off">
                        <div class="pmk-search-dropdown">
                            <?php foreach ($employees as $emp): ?>
                                <button type="button" class="pmk-search-option"
                                        data-value="<?= (int)$emp['id'] ?>"
                                        data-label="<?= pmk_h($emp['full_name'] . ' — ' . $emp['unit_name']) ?>"
                                        data-keywords="<?= pmk_h(strtolower($emp['full_name'] . ' ' . $emp['nik'] . ' ' . $emp['unit_name'] . ' ' . $emp['position_name'])) ?>">
                                    <div class="name"><?= pmk_h($emp['full_name']) ?></div>
                                    <div class="meta">NIK: <?= pmk_h($emp['nik']) ?> • <?= pmk_h($emp['unit_name']) ?> • <?= pmk_h($emp['position_name']) ?></div>
                                </button>
                            <?php endforeach; ?>
                            <div class="pmk-empty-search">Nama tidak ditemukan</div>
                        </div>
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                    <div>
                        <label class="pmk-label">Jenis Penugasan</label>
                        <select name="task_type" class="pmk-input" required>
                            <option value="urgent">Urgent</option>
                            <option value="biasa" selected>Biasa</option>
                            <option value="rutin">Rutin</option>
                        </select>
                    </div>
                    <div>
                        <label class="pmk-label">Target Selesai</label>
                        <input type="date" name="end_date" class="pmk-input">
                    </div>
                </div>
                <div>
                    <label class="pmk-label">Tanggal Mulai Penugasan</label>
                    <input type="date" name="start_date" class="pmk-input" value="<?= date('Y-m-d') ?>">
                </div>
                <div>
                    <label class="pmk-label">Isi Penugasan</label>
                    <textarea name="task_description" rows="5" class="pmk-input" placeholder="Tuliskan detail penugasan..." required></textarea>
                </div>
                <button class="pmk-btn pmk-btn-primary w-full" type="submit"><i class="fas fa-save"></i> Simpan Penugasan</button>
            </form>
        </div>

        <div class="xl:col-span-2 pmk-card p-6">
            <div class="flex items-center justify-between gap-3 flex-wrap mb-5">
                <div>
                    <h3 class="text-lg font-extrabold text-slate-800"><i class="fas fa-ranking-star text-amber-500 mr-2"></i>Nama yang Sering Mendapat Penugasan</h3>
                    <p class="text-sm text-slate-500">Top 10 berdasarkan jumlah penugasan.</p>
                </div>
            </div>
            <div class="overflow-x-auto rounded-2xl border border-slate-200">
                <table class="min-w-full pmk-table">
                    <thead><tr><th>Nama</th><th>Unit</th><th>Total</th><th>Selesai</th><th>Aktif</th><th>Urgent</th><th>Rata-rata Respon</th></tr></thead>
                    <tbody>
                    <?php if (!$topAssigned): ?>
                        <tr><td colspan="7" class="text-center text-slate-500 py-8">Belum ada data rekap.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($topAssigned as $top): ?>
                        <tr>
                            <td><div class="font-bold text-slate-800"><?= pmk_h($top['full_name']) ?></div><div class="text-xs text-slate-400">NIK: <?= pmk_h($top['nik']) ?></div></td>
                            <td><?= pmk_h($top['unit_name']) ?></td>
                            <td class="font-extrabold text-slate-800"><?= (int)$top['total_task'] ?></td>
                            <td class="text-emerald-700 font-bold"><?= (int)$top['total_done'] ?></td>
                            <td class="text-blue-700 font-bold"><?= (int)$top['total_open'] ?></td>
                            <td class="text-red-700 font-bold"><?= (int)$top['total_urgent'] ?></td>
                            <td><?= $top['avg_days'] !== null ? pmk_h($top['avg_days']) . ' hari' : '-' ?></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="pmk-card p-6">
        <div class="flex flex-col lg:flex-row lg:items-end lg:justify-between gap-4 mb-5">
            <div>
                <h3 class="text-xl font-extrabold text-slate-800"><i class="fas fa-table-list text-indigo-600 mr-2"></i>Daftar Penugasan</h3>
                <p class="text-sm text-slate-500">Penerima tugas dapat mengisi laporan hasil, tanggal mulai, tanggal selesai, dan status.</p>
            </div>
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-3 w-full lg:w-auto">
                <div class="pmk-quick-search">
                    <i class="fas fa-search"></i>
                    <input type="text" id="pmkQuickSearch" class="pmk-input" placeholder="Cari cepat di tabel tanpa reload...">
                </div>
                <form method="get" class="grid grid-cols-1 md:grid-cols-5 gap-3">
                    <input type="hidden" name="module" value="penugasan_manajemen_keperawatan">
                    <input type="text" name="q" class="pmk-input" placeholder="Cari database..." value="<?= pmk_h($q) ?>">
                <select name="status" class="pmk-input">
                    <option value="">Semua Status</option>
                    <?php foreach (['pending'=>'Pending','onproses'=>'On Proses','selesai'=>'Selesai','batal'=>'Batal'] as $k=>$v): ?>
                        <option value="<?= $k ?>" <?= $statusFilter===$k?'selected':'' ?>><?= $v ?></option>
                    <?php endforeach; ?>
                </select>
                <select name="type" class="pmk-input">
                    <option value="">Semua Jenis</option>
                    <?php foreach (['urgent'=>'Urgent','biasa'=>'Biasa','rutin'=>'Rutin'] as $k=>$v): ?>
                        <option value="<?= $k ?>" <?= $typeFilter===$k?'selected':'' ?>><?= $v ?></option>
                    <?php endforeach; ?>
                </select>
                <select name="mine" class="pmk-input">
                    <option value="">Semua Data</option>
                    <option value="1" <?= $mine==='1'?'selected':'' ?>>Terkait Saya</option>
                </select>
                    <button class="pmk-btn pmk-btn-soft" type="submit"><i class="fas fa-filter"></i> Filter</button>
                </form>
            </div>
        </div>

        <div class="overflow-x-auto rounded-2xl border border-slate-200">
            <table class="min-w-full pmk-table">
                <thead>
                    <tr>
                        <th style="width:70px">No</th>
                        <th>Penugasan</th>
                        <th>Oleh</th>
                        <th>Untuk</th>
                        <th>Tanggal</th>
                        <th>Status</th>
                        <th>Respon</th>
                        <th style="width:170px">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (!$assignments): ?>
                    <tr><td colspan="8" class="text-center text-slate-500 py-10">Belum ada data penugasan.</td></tr>
                <?php endif; ?>
                <?php foreach ($assignments as $i => $row): ?>
                    <?php $canReport = $isAdmin || (int)$row['assigned_to_employee_id'] === $currentEmployeeId; ?>
                    <tr class="pmk-assignment-row" data-search="<?= pmk_h(strtolower(($row['task_description'] ?? '') . ' ' . ($row['assigned_by_name'] ?? '') . ' ' . ($row['assigned_to_name'] ?? '') . ' ' . ($row['assigned_to_unit'] ?? '') . ' ' . ($row['status'] ?? '') . ' ' . ($row['task_type'] ?? '') . ' ' . ($row['result_report'] ?? '') . ' ' . ($row['response_note'] ?? ''))) ?>">
                        <td class="font-bold text-slate-500"><?= $i + 1 ?></td>
                        <td>
                            <div class="flex items-center gap-2 flex-wrap mb-2">
                                <span class="pmk-badge <?= pmk_type_badge((string)$row['task_type']) ?>"><?= strtoupper(pmk_h((string)$row['task_type'])) ?></span>
                            </div>
                            <div class="font-semibold text-slate-800 whitespace-pre-line"><?= pmk_h($row['task_description']) ?></div>
                            <?php if (!empty($row['result_report'])): ?>
                                <div class="mt-3 rounded-xl bg-slate-50 border border-slate-200 p-3">
                                    <div class="text-xs font-extrabold text-slate-500 uppercase mb-1">Laporan Hasil</div>
                                    <div class="whitespace-pre-line"><?= pmk_h($row['result_report']) ?></div>
                                </div>
                            <?php endif; ?>
                        </td>
                        <td><div class="font-bold text-slate-800"><?= pmk_h($row['assigned_by_name'] ?? '-') ?></div><div class="text-xs text-slate-400"><?= pmk_h($row['assigned_by_nik'] ?? '-') ?></div></td>
                        <td><div class="font-bold text-slate-800"><?= pmk_h($row['assigned_to_name'] ?? '-') ?></div><div class="text-xs text-slate-400"><?= pmk_h($row['assigned_to_unit'] ?? '-') ?></div></td>
                        <td><div>Mulai: <b><?= pmk_date_id($row['start_date'] ?? null) ?></b></div><div>Selesai/Target: <b><?= pmk_date_id($row['end_date'] ?? null) ?></b></div><div class="text-xs text-slate-400 mt-1">Input: <?= pmk_date_id(substr((string)$row['created_at'],0,10)) ?></div></td>
                        <td><span class="pmk-badge <?= pmk_badge((string)$row['status']) ?>"><?= strtoupper(pmk_h((string)$row['status'])) ?></span></td>
                        <td>
                            <div class="font-bold <?= in_array($row['response_status'], ['Terlambat','Melewati target'], true) ? 'text-rose-700' : 'text-slate-700' ?>"><?= pmk_h($row['response_status']) ?></div>
                            <?php if (!empty($row['response_note'])): ?><div class="text-xs text-slate-500 mt-1 whitespace-pre-line"><?= pmk_h($row['response_note']) ?></div><?php endif; ?>
                        </td>
                        <td>
                            <div class="flex flex-col gap-2">
                                <?php if ($canReport): ?>
                                    <a href="#report-<?= (int)$row['id'] ?>" class="pmk-btn pmk-btn-primary"><i class="fas fa-pen-to-square"></i> Isi Laporan</a>
                                <?php else: ?>
                                    <button type="button" class="pmk-btn pmk-btn-soft" disabled><i class="fas fa-lock"></i> Laporan</button>
                                <?php endif; ?>
                                <?php if ($isSuperAdmin): ?>
                                    <form method="post" onsubmit="return confirm('Hapus data penugasan ini?')">
                                        <input type="hidden" name="action" value="delete_assignment">
                                        <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                                        <button class="pmk-btn pmk-btn-danger w-full" type="submit"><i class="fas fa-trash"></i> Hapus</button>
                                    </form>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>

                    <div id="report-<?= (int)$row['id'] ?>" class="pmk-modal">
                        <div class="pmk-modal-box">
                            <div class="p-5 border-b border-slate-200 flex items-center justify-between gap-3">
                                <div>
                                    <h3 class="text-lg font-extrabold text-slate-800">Laporan Hasil Penugasan</h3>
                                    <p class="text-sm text-slate-500"><?= pmk_h($row['assigned_to_name'] ?? '-') ?></p>
                                </div>
                                <a href="#" class="pmk-btn pmk-btn-soft"><i class="fas fa-xmark"></i> Tutup</a>
                            </div>
                            <form method="post" class="pmk-report-form space-y-5">
                                <input type="hidden" name="action" value="update_report">
                                <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                                <div class="rounded-2xl bg-slate-50 border border-slate-200 p-4 text-sm text-slate-700 whitespace-pre-line"><?= pmk_h($row['task_description']) ?></div>
                                <div class="grid grid-cols-1 md:grid-cols-3 gap-3">
                                    <div><label class="pmk-label">Tanggal Mulai</label><input type="date" name="start_date" class="pmk-input" value="<?= pmk_h($row['start_date'] ?? '') ?>"></div>
                                    <div><label class="pmk-label">Tanggal Selesai</label><input type="date" name="end_date" class="pmk-input" value="<?= pmk_h($row['end_date'] ?? '') ?>"></div>
                                    <div><label class="pmk-label">Status</label><select name="status" class="pmk-input" required><?php foreach (['pending'=>'Pending','onproses'=>'On Proses','selesai'=>'Selesai','batal'=>'Batal'] as $k=>$v): ?><option value="<?= $k ?>" <?= $row['status']===$k?'selected':'' ?>><?= $v ?></option><?php endforeach; ?></select></div>
                                </div>
                                <div><label class="pmk-label">Laporan Hasil Penugasan</label><textarea name="result_report" rows="9" class="pmk-input pmk-report-textarea" placeholder="Isi hasil penugasan yang sudah dilakukan..."><?= pmk_h($row['result_report'] ?? '') ?></textarea></div>
                                <div><label class="pmk-label">Respon Penyelesaian / Keterangan</label><textarea name="response_note" rows="5" class="pmk-input pmk-response-textarea" placeholder="Contoh: selesai tepat waktu, hambatan, tindak lanjut berikutnya..."><?= pmk_h($row['response_note'] ?? '') ?></textarea></div>
                                <div class="flex justify-end gap-3 flex-wrap">
                                    <a href="#" class="pmk-btn pmk-btn-soft">Batal</a>
                                    <button class="pmk-btn pmk-btn-primary" type="submit"><i class="fas fa-save"></i> Simpan Laporan</button>
                                </div>
                            </form>
                        </div>
                    </div>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>


<script>
(function(){
    function normalizeText(value){
        return (value || '').toString().toLowerCase().replace(/\s+/g, ' ').trim();
    }

    document.querySelectorAll('[data-search-select]').forEach(function(box){
        const visibleInput = box.querySelector('[data-search-input]');
        const hiddenInput = box.querySelector('input[type="hidden"]');
        const options = Array.from(box.querySelectorAll('.pmk-search-option'));
        const empty = box.querySelector('.pmk-empty-search');

        function filterOptions(){
            const term = normalizeText(visibleInput.value);
            let shown = 0;
            options.forEach(function(option){
                const keywords = normalizeText((option.dataset.keywords || '') + ' ' + (option.dataset.label || ''));
                const match = term === '' || keywords.includes(term);
                option.style.display = match ? 'block' : 'none';
                if (match) shown++;
            });
            if (empty) empty.style.display = shown === 0 ? 'block' : 'none';
        }

        visibleInput.addEventListener('focus', function(){
            box.classList.add('open');
            filterOptions();
        });

        visibleInput.addEventListener('input', function(){
            hiddenInput.value = '';
            box.classList.add('open');
            filterOptions();
        });

        options.forEach(function(option){
            option.addEventListener('click', function(){
                hiddenInput.value = option.dataset.value || '';
                visibleInput.value = option.dataset.label || '';
                box.classList.remove('open');
            });
        });

        document.addEventListener('click', function(event){
            if (!box.contains(event.target)) {
                box.classList.remove('open');
            }
        });
    });

    const quickSearch = document.getElementById('pmkQuickSearch');
    if (quickSearch) {
        quickSearch.addEventListener('input', function(){
            const term = normalizeText(this.value);
            document.querySelectorAll('.pmk-assignment-row').forEach(function(row){
                const source = normalizeText(row.dataset.search || row.innerText);
                row.style.display = term === '' || source.includes(term) ? '' : 'none';
            });
        });
    }
})();
</script>
