<?php
// modules/kegiatan_harian/index.php - UI Event/Card Version
ini_set('display_errors', '1');
error_reporting(E_ALL);

require_once __DIR__ . '/../../config/database.php';
if (file_exists(__DIR__ . '/../../config/app.php')) require_once __DIR__ . '/../../config/app.php';
if (file_exists(__DIR__ . '/../../config/master_auth.php')) require_once __DIR__ . '/../../config/master_auth.php';
if (file_exists(__DIR__ . '/../../includes/functions.php')) require_once __DIR__ . '/../../includes/functions.php';
if (function_exists('checkAuth')) { checkAuth(); }

$conn = getConnection();
if (!$conn instanceof mysqli) { echo '<div class="p-4 bg-red-50 text-red-700">Koneksi database gagal.</div>'; return; }

if (!function_exists('e')) { function e($v): string { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); } }
function kh_col_exists(mysqli $conn, string $table, string $col): bool {
    $stmt = $conn->prepare("SELECT COUNT(*) c FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?");
    if (!$stmt) return false;
    $stmt->bind_param('ss', $table, $col);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    return ((int)($row['c'] ?? 0)) > 0;
}
function kh_table_exists(mysqli $conn, string $table): bool {
    $stmt = $conn->prepare("SELECT COUNT(*) c FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?");
    if (!$stmt) return false;
    $stmt->bind_param('s', $table);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    return ((int)($row['c'] ?? 0)) > 0;
}
function kh_ensure_schema(mysqli $conn): void {
    if (!kh_table_exists($conn, 'daily_activities')) {
        $conn->query("CREATE TABLE daily_activities (
            id INT AUTO_INCREMENT PRIMARY KEY,
            activity_date DATE NOT NULL,
            job_title VARCHAR(180) NULL,
            unit_id INT NULL,
            unit_name VARCHAR(160) NULL,
            activity_type VARCHAR(120) NULL,
            activity_text TEXT NULL,
            start_time TIME NULL,
            end_time TIME NULL,
            result_note TEXT NULL,
            status VARCHAR(40) DEFAULT 'done',
            created_by INT NULL,
            created_by_name VARCHAR(180) NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_date (activity_date), INDEX idx_job (job_title), INDEX idx_unit (unit_id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
        return;
    }
    $adds = [
        'activity_date' => "ALTER TABLE daily_activities ADD COLUMN activity_date DATE NULL AFTER id",
        'job_title' => "ALTER TABLE daily_activities ADD COLUMN job_title VARCHAR(180) NULL AFTER activity_date",
        'unit_id' => "ALTER TABLE daily_activities ADD COLUMN unit_id INT NULL AFTER job_title",
        'unit_name' => "ALTER TABLE daily_activities ADD COLUMN unit_name VARCHAR(160) NULL AFTER unit_id",
        'activity_type' => "ALTER TABLE daily_activities ADD COLUMN activity_type VARCHAR(120) NULL AFTER unit_name",
        'activity_text' => "ALTER TABLE daily_activities ADD COLUMN activity_text TEXT NULL AFTER activity_type",
        'start_time' => "ALTER TABLE daily_activities ADD COLUMN start_time TIME NULL AFTER activity_text",
        'end_time' => "ALTER TABLE daily_activities ADD COLUMN end_time TIME NULL AFTER start_time",
        'result_note' => "ALTER TABLE daily_activities ADD COLUMN result_note TEXT NULL AFTER end_time",
        'status' => "ALTER TABLE daily_activities ADD COLUMN status VARCHAR(40) DEFAULT 'done' AFTER result_note",
        'created_by' => "ALTER TABLE daily_activities ADD COLUMN created_by INT NULL AFTER status",
        'created_by_name' => "ALTER TABLE daily_activities ADD COLUMN created_by_name VARCHAR(180) NULL AFTER created_by",
        'created_at' => "ALTER TABLE daily_activities ADD COLUMN created_at DATETIME DEFAULT CURRENT_TIMESTAMP AFTER created_by_name",
        'updated_at' => "ALTER TABLE daily_activities ADD COLUMN updated_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP AFTER created_at",
    ];
    foreach ($adds as $col => $sql) { if (!kh_col_exists($conn,'daily_activities',$col)) { try { $conn->query($sql); } catch (Throwable $e) {} } }
    $pairs = [
        'job_title' => ['level','jabatan','position_name'],
        'activity_type' => ['jenis_kegiatan','jenis','type'],
        'activity_text' => ['activity_name','kegiatan','nama_kegiatan'],
        'result_note' => ['description','hasil','keterangan'],
    ];
    foreach ($pairs as $target => $sources) foreach ($sources as $src) if (kh_col_exists($conn,'daily_activities',$src)) { try { $conn->query("UPDATE daily_activities SET {$target}=COALESCE(NULLIF({$target},''),NULLIF({$src},'')) WHERE {$target} IS NULL OR {$target}='' "); } catch(Throwable $e){} }
    if (kh_col_exists($conn,'daily_activities','tanggal')) { try { $conn->query("UPDATE daily_activities SET activity_date=COALESCE(activity_date,tanggal) WHERE activity_date IS NULL"); } catch(Throwable $e){} }
    try { $conn->query("UPDATE daily_activities da LEFT JOIN units u ON da.unit_id=u.id SET da.unit_name=COALESCE(NULLIF(da.unit_name,''),u.name) WHERE da.unit_name IS NULL OR da.unit_name='' "); } catch(Throwable $e){}
}
kh_ensure_schema($conn);

function kh_current_user_data(): array {
    $m = function_exists('current_user') ? (current_user() ?: []) : [];
    $s = $_SESSION['user'] ?? [];
    return [
        'id' => (int)($m['employee_id'] ?? $s['employee_id'] ?? $_SESSION['user_id'] ?? $s['id'] ?? 0),
        'name' => (string)($m['nama'] ?? $s['full_name'] ?? $s['name'] ?? $_SESSION['full_name'] ?? $_SESSION['username'] ?? 'User'),
        'role' => strtolower((string)($m['role'] ?? $s['role'] ?? $_SESSION['user_role'] ?? 'user')),
        'photo' => (string)($m['photo_path'] ?? $s['photo_path'] ?? ''),
    ];
}
$cu = kh_current_user_data();
$isAdmin = in_array($cu['role'], ['admin','superadmin'], true);

$jobs = [
    'Kepala Divisi Keperawatan',
    'Kepala Sub Divisi Keperawatan Rawat Inap',
    'Kepala Sub Divisi Keperawatan Rawat Jalan',
    'Kepala Unit IGD', 'Kepala Unit VK / Kamar Bersalin', 'Kepala Unit OK / Kamar Operasi',
    'Kepala Unit Poliklinik', 'Kepala Unit HD / Hemodialisa', 'Kepala Unit Pav. Canigara',
    'Kepala Unit Pav. Cempaka', 'Kepala Unit Pav. Cendana', 'Kepala Unit Cempaka Utara',
    'Kepala Unit Bayi Terpadu', 'Kepala Unit ICU',
];
$types = ['Koordinasi','Supervisi','Evaluasi','Briefing','Rapat','Audit','Edukasi','Monitoring','Administrasi','Lainnya'];


// Foto card jabatan: jangan memakai foto user login untuk semua card.
// Sistem mencari foto pegawai yang sesuai jabatan/unit. Jika tidak ada, pakai avatar default.
function kh_normalize_unit_label(string $s): string {
    $s = strtolower($s);
    $s = str_replace(['pav.', 'pav ', '/', '-', '.', '  '], ['pav', 'pav', ' ', ' ', ' ', ' '], $s);
    return trim(preg_replace('/\s+/', ' ', $s));
}
function kh_find_job_photo(mysqli $conn, string $job): string {
    $job = trim($job);
    if ($job === '') return '';

    // Kepala unit: cocokkan unit pada nama jabatan dengan unit pegawai.
    if (stripos($job, 'Kepala Unit ') === 0) {
        $unitNeedle = trim(substr($job, strlen('Kepala Unit ')));
        $unitNeedleNorm = kh_normalize_unit_label($unitNeedle);
        $isBayiTerpadu = ($unitNeedleNorm === 'bayi terpadu');
        $sql = "
            SELECT e.photo_path, COALESCE(u.name, COALESCE(u.name, ''), '') AS unit_label, COALESCE(e.position_name, '') AS pos
            FROM employees e
            LEFT JOIN units u ON e.unit_id = u.id
            WHERE e.photo_path IS NOT NULL AND e.photo_path <> ''
              AND (LOWER(COALESCE(e.position_name,'')) LIKE '%ka.unit%' OR LOWER(COALESCE(e.position_name,'')) LIKE '%kepala unit%' OR LOWER(COALESCE(e.position_name,'')) LIKE '%ka unit%')
            ORDER BY e.id ASC
            LIMIT 200
        ";
        $res = $conn->query($sql);
        if ($res) {
            while ($r = $res->fetch_assoc()) {
                $unitLabelNorm = kh_normalize_unit_label((string)($r['unit_label'] ?? ''));
                $matchUnit = $unitLabelNorm !== '' && (
                    strpos($unitLabelNorm, $unitNeedleNorm) !== false ||
                    strpos($unitNeedleNorm, $unitLabelNorm) !== false
                );
                if ($isBayiTerpadu && (
                    strpos($unitLabelNorm, 'ruang bayi') !== false ||
                    strpos($unitLabelNorm, 'nicu') !== false ||
                    strpos($unitLabelNorm, 'bayi terpadu') !== false
                )) {
                    $matchUnit = true;
                }
                if ($matchUnit) {
                    return (string)$r['photo_path'];
                }
            }
        }
        return '';
    }

    // Jabatan struktural non-unit: cocokkan posisi.
    $like = '%' . $job . '%';
    $stmt = $conn->prepare("SELECT photo_path FROM employees WHERE photo_path IS NOT NULL AND photo_path <> '' AND (position_name = ? OR position_name LIKE ?) ORDER BY id ASC LIMIT 1");
    if ($stmt) {
        $stmt->bind_param('ss', $job, $like);
        $stmt->execute();
        $row = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        return (string)($row['photo_path'] ?? '');
    }
    return '';
}
$jobPhotos = [];
foreach ($jobs as $jobPhotoName) {
    $jobPhotos[$jobPhotoName] = kh_find_job_photo($conn, $jobPhotoName);
}

// Units canonical + DB active.
$units = [];
$canonical = ['IGD','VK / Kamar Bersalin','OK / Kamar Operasi','Poliklinik','HD / Hemodialisa','Pav. Canigara','Pav. Cempaka','Pav. Cendana','Cempaka Utara','Bayi Terpadu','ICU'];
$resU = $conn->query("SELECT id,name FROM units WHERE is_active=1 ORDER BY name ASC");
$dbUnits = [];
if ($resU) while ($r=$resU->fetch_assoc()) $dbUnits[]=$r;
foreach ($canonical as $name) {
    $found = null;

    if ($name === 'Bayi Terpadu') {
        foreach ($dbUnits as $u) {
            if (strcasecmp(trim((string)$u['name']), 'Bayi Terpadu') === 0) {
                $found = $u;
                break;
            }
        }
        if (!$found) {
            foreach ($dbUnits as $u) {
                $dbName = strtolower(trim((string)$u['name']));
                if (in_array($dbName, ['ruang bayi','nicu','r. bayi dan nicu','bayi dan nicu'], true)) {
                    $found = $u;
                    break;
                }
            }
        }
    } else {
        foreach ($dbUnits as $u) {
            if (strcasecmp(trim((string)$u['name']), $name) === 0) {
                $found = $u;
                break;
            }
        }
    }

    $units[] = ['id' => (int)($found['id'] ?? 0), 'name' => $name];
}

function kh_merge_bayi_terpadu_row(array $row): array {
    $unitName = strtolower(trim((string)($row['unit_name'] ?? '')));
    if (in_array($unitName, ['ruang bayi','nicu','r. bayi dan nicu','bayi dan nicu','ruang bayi terpadu','nhcu'], true)) {
        $row['unit_name'] = 'Bayi Terpadu';
    }

    $jobTitle = trim((string)($row['job_title'] ?? ''));
    if (in_array($jobTitle, ['Kepala Unit Ruang Bayi','Kepala Unit NICU'], true)) {
        $row['job_title'] = 'Kepala Unit Bayi Terpadu';
    }

    return $row;
}

$selectedDate = $_GET['date'] ?? date('Y-m-d');
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $selectedDate)) $selectedDate = date('Y-m-d');
$month = (int)($_GET['month'] ?? date('n'));
$year = (int)($_GET['year'] ?? date('Y'));
$viewMode = $_GET['mode'] ?? 'day';
if (!in_array($viewMode, ['day','month'], true)) $viewMode = 'day';
$activeJob = $_GET['job'] ?? ($jobs[0] ?? 'Kepala Divisi Keperawatan');
if (!in_array($activeJob, $jobs, true)) $activeJob = $jobs[0];


function kh_redirect_url(array $extra = []): string {
    $params = [
        'module' => 'kegiatan_harian',
        'date'   => $_POST['return_date'] ?? $_GET['date'] ?? date('Y-m-d'),
        'month'  => (int)($_POST['return_month'] ?? $_GET['month'] ?? date('n')),
        'year'   => (int)($_POST['return_year'] ?? $_GET['year'] ?? date('Y')),
        'mode'   => $_POST['return_mode'] ?? $_GET['mode'] ?? 'day',
        'job'    => $_POST['return_job'] ?? $_GET['job'] ?? '',
    ];
    foreach ($extra as $k => $v) $params[$k] = $v;
    return '?' . http_build_query($params) . '#rekapKegiatan';
}

// Edit satu kegiatan dari tabel rekap.
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'edit_activity') {
    $id = (int)($_POST['activity_id'] ?? 0);
    $existing = null;
    if ($id > 0) {
        $st = $conn->prepare("SELECT * FROM daily_activities WHERE id=? LIMIT 1");
        if ($st) {
            $st->bind_param('i', $id);
            $st->execute();
            $existing = $st->get_result()->fetch_assoc();
            $st->close();
        }
    }

    if (!$existing) {
        echo '<script>alert("Data kegiatan tidak ditemukan.");window.location.href=' . json_encode(kh_redirect_url()) . ';</script>';
        exit;
    }

    $canEdit = $isAdmin || (int)($existing['created_by'] ?? 0) === (int)$cu['id'];
    if (!$canEdit) {
        echo '<script>alert("Anda tidak memiliki akses untuk mengubah kegiatan ini.");window.location.href=' . json_encode(kh_redirect_url()) . ';</script>';
        exit;
    }

    $activityDate = trim((string)($_POST['activity_date'] ?? ''));
    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $activityDate)) {
        $activityDate = (string)$existing['activity_date'];
    }

    $uid   = (int)($_POST['unit_id'] ?? 0);
    $uname = trim((string)($_POST['unit_manual'] ?? ''));
    if ($uid > 0) {
        foreach ($units as $u) {
            if ((int)$u['id'] === $uid) {
                $uname = (string)$u['name'];
                break;
            }
        }
        if ($uname === '') {
            $su = $conn->prepare("SELECT name FROM units WHERE id=? LIMIT 1");
            if ($su) {
                $su->bind_param('i', $uid);
                $su->execute();
                $ru = $su->get_result()->fetch_assoc();
                $su->close();
                $uname = (string)($ru['name'] ?? '');
            }
        }
    }
    if ($uname === '') $uname = 'Tidak disebutkan';

    $atype = trim((string)($_POST['activity_type'] ?? ''));
    $atext = trim((string)($_POST['activity_text'] ?? ''));
    $start = trim((string)($_POST['start_time'] ?? ''));
    $end   = trim((string)($_POST['end_time'] ?? ''));
    $note  = trim((string)($_POST['result_note'] ?? ''));

    $start = preg_match('/^\d{2}:\d{2}/', $start) ? substr($start, 0, 5) : null;
    $end   = preg_match('/^\d{2}:\d{2}/', $end) ? substr($end, 0, 5) : null;

    if ($atext === '' && $atype === '') {
        echo '<script>alert("Jenis atau isi kegiatan wajib diisi.");window.history.back();</script>';
        exit;
    }

    $up = $conn->prepare("UPDATE daily_activities
        SET activity_date=?, unit_id=?, unit_name=?, activity_type=?, activity_text=?,
            start_time=?, end_time=?, result_note=?, updated_at=NOW()
        WHERE id=?");
    if (!$up) die('Prepare edit gagal: ' . e($conn->error));
    $up->bind_param('sissssssi', $activityDate, $uid, $uname, $atype, $atext, $start, $end, $note, $id);
    $up->execute();
    $up->close();

    echo '<script>window.location.href=' . json_encode(kh_redirect_url(['updated' => 1])) . ';</script>';
    exit;
}

// Hapus satu kegiatan dari tabel rekap.
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete_activity') {
    $id = (int)($_POST['activity_id'] ?? 0);
    $existing = null;
    if ($id > 0) {
        $st = $conn->prepare("SELECT id,created_by FROM daily_activities WHERE id=? LIMIT 1");
        if ($st) {
            $st->bind_param('i', $id);
            $st->execute();
            $existing = $st->get_result()->fetch_assoc();
            $st->close();
        }
    }

    if ($existing && ($isAdmin || (int)($existing['created_by'] ?? 0) === (int)$cu['id'])) {
        $del = $conn->prepare("DELETE FROM daily_activities WHERE id=?");
        if ($del) {
            $del->bind_param('i', $id);
            $del->execute();
            $del->close();
        }
        echo '<script>window.location.href=' . json_encode(kh_redirect_url(['deleted' => 1])) . ';</script>';
    } else {
        echo '<script>alert("Anda tidak memiliki akses untuk menghapus kegiatan ini.");window.location.href=' . json_encode(kh_redirect_url()) . ';</script>';
    }
    exit;
}

// Save multi rows.
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'save_activities') {
    $activityDate = $_POST['activity_date'] ?? date('Y-m-d');
    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $activityDate)) $activityDate = date('Y-m-d');
    $jobTitle = trim($_POST['job_title'] ?? '');
    if ($jobTitle === '') $jobTitle = 'Tidak disebutkan';
    $unitIds = $_POST['unit_id'] ?? [];
    $unitManuals = $_POST['unit_manual'] ?? [];
    $activityTypes = $_POST['activity_type'] ?? [];
    $activityTexts = $_POST['activity_text'] ?? [];
    $startTimes = $_POST['start_time'] ?? [];
    $endTimes = $_POST['end_time'] ?? [];
    $resultNotes = $_POST['result_note'] ?? [];

    $stmt = $conn->prepare("INSERT INTO daily_activities
        (activity_date, job_title, unit_id, unit_name, activity_type, activity_text, start_time, end_time, result_note, status, created_by, created_by_name, created_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'done', ?, ?, NOW())");
    if (!$stmt) { die('Prepare simpan gagal: ' . e($conn->error)); }
    $saved = 0;
    $n = max(count($activityTexts), count($activityTypes), count($unitIds), count($unitManuals));
    for ($i=0; $i<$n; $i++) {
        $text = trim((string)($activityTexts[$i] ?? ''));
        $atype = trim((string)($activityTypes[$i] ?? ''));
        if ($text === '' && $atype === '') continue;
        $uid = (int)($unitIds[$i] ?? 0);
        $uname = trim((string)($unitManuals[$i] ?? ''));
        if ($uid > 0) {
            foreach ($units as $u) { if ((int)$u['id'] === $uid) { $uname = $u['name']; break; } }
            if ($uname === '') {
                $su = $conn->prepare("SELECT name FROM units WHERE id=? LIMIT 1");
                if ($su) { $su->bind_param('i',$uid); $su->execute(); $ru=$su->get_result()->fetch_assoc(); $su->close(); $uname = (string)($ru['name'] ?? ''); }
            }
        }
        if ($uname === '') $uname = 'Tidak disebutkan';
        $st = trim((string)($startTimes[$i] ?? ''));
        $et = trim((string)($endTimes[$i] ?? ''));
        $st = preg_match('/^\d{2}:\d{2}/', $st) ? substr($st,0,5) : null;
        $et = preg_match('/^\d{2}:\d{2}/', $et) ? substr($et,0,5) : null;
        $note = trim((string)($resultNotes[$i] ?? ''));
        $createdBy = $cu['id'];
        $createdByName = $cu['name'];
        $stmt->bind_param('ssissssssis', $activityDate, $jobTitle, $uid, $uname, $atype, $text, $st, $et, $note, $createdBy, $createdByName);
        if ($stmt->execute()) $saved++;
    }
    $stmt->close();
    echo '<script>window.location.href="?module=kegiatan_harian&date=' . e($activityDate) . '&job=' . rawurlencode($jobTitle) . '&saved=' . $saved . '";</script>';
    exit;
}

// Query data for selected date/month
$whereSql = '';
$typesBind = '';
$params = [];
if ($viewMode === 'month') {
    $whereSql = "MONTH(activity_date)=? AND YEAR(activity_date)=?";
    $typesBind = 'ii'; $params = [$month, $year];
} else {
    $whereSql = "activity_date=?";
    $typesBind = 's'; $params = [$selectedDate];
}
$sqlList = "SELECT * FROM daily_activities WHERE {$whereSql} ORDER BY activity_date DESC, COALESCE(start_time,'99:99') ASC, id DESC";
$stmtList = $conn->prepare($sqlList);
$stmtList->bind_param($typesBind, ...$params);
$stmtList->execute();
$resList = $stmtList->get_result();
$activities = [];
while ($r=$resList->fetch_assoc()) $activities[] = kh_merge_bayi_terpadu_row($r);
$stmtList->close();

$byJob = [];
foreach ($activities as $a) {
    $j = trim((string)($a['job_title'] ?? 'Tidak disebutkan')) ?: 'Tidak disebutkan';
    if (!isset($byJob[$j])) $byJob[$j] = [];
    $byJob[$j][] = $a;
}

// Date summary for current month
$dateCards = [];
$stmtDates = $conn->prepare("
    SELECT activity_date,
           COUNT(*) total,
           COUNT(DISTINCT CASE
               WHEN job_title IN ('Kepala Unit Ruang Bayi','Kepala Unit NICU')
                   THEN 'Kepala Unit Bayi Terpadu'
               ELSE job_title
           END) jobs
    FROM daily_activities
    WHERE MONTH(activity_date)=? AND YEAR(activity_date)=?
    GROUP BY activity_date
    ORDER BY activity_date DESC
    LIMIT 31
");
$stmtDates->bind_param('ii', $month, $year);
$stmtDates->execute();
$rDates = $stmtDates->get_result();
while ($r=$rDates->fetch_assoc()) $dateCards[]=$r;
$stmtDates->close();

// Admin monthly summary
$adminUnitSummary = [];
if ($isAdmin) {
    $sm = $conn->prepare("
        SELECT CASE
                 WHEN LOWER(TRIM(COALESCE(unit_name,''))) IN
                      ('ruang bayi','nicu','r. bayi dan nicu','bayi dan nicu','ruang bayi terpadu','nhcu')
                   THEN 'Bayi Terpadu'
                 ELSE COALESCE(NULLIF(unit_name,''),'Tidak disebutkan')
               END AS unit_name,
               COUNT(*) total
        FROM daily_activities
        WHERE MONTH(activity_date)=? AND YEAR(activity_date)=?
        GROUP BY CASE
                 WHEN LOWER(TRIM(COALESCE(unit_name,''))) IN
                      ('ruang bayi','nicu','r. bayi dan nicu','bayi dan nicu','ruang bayi terpadu','nhcu')
                   THEN 'Bayi Terpadu'
                 ELSE COALESCE(NULLIF(unit_name,''),'Tidak disebutkan')
               END
        ORDER BY total DESC
    ");
    $sm->bind_param('ii', $month, $year);
    $sm->execute();
    $rs = $sm->get_result();
    while ($r=$rs->fetch_assoc()) $adminUnitSummary[]=$r;
    $sm->close();
}

$profilePhoto = $cu['photo'];
if (!$profilePhoto && $cu['id'] > 0) {
    $sp = $conn->prepare("SELECT photo_path FROM employees WHERE id=? LIMIT 1");
    if ($sp) { $sp->bind_param('i',$cu['id']); $sp->execute(); $rp=$sp->get_result()->fetch_assoc(); $sp->close(); $profilePhoto=(string)($rp['photo_path'] ?? ''); }
}
?>
<style>
.kh-wrap{font-family:Poppins,system-ui,sans-serif;color:#0f172a}.kh-hero{background:linear-gradient(135deg,#312e81,#2563eb 55%,#06b6d4);border-radius:30px;padding:28px;color:white;box-shadow:0 24px 55px rgba(37,99,235,.24);position:relative;overflow:hidden}.kh-hero:after{content:"";position:absolute;right:-70px;top:-70px;width:220px;height:220px;background:rgba(255,255,255,.13);border-radius:50%}.kh-card{background:rgba(255,255,255,.94);border:1px solid #e2e8f0;border-radius:24px;box-shadow:0 16px 38px rgba(15,23,42,.07)}.kh-job{border-radius:22px;padding:18px;border:1px solid #e2e8f0;background:#fff;transition:.2s;cursor:pointer}.kh-job:hover{transform:translateY(-3px);box-shadow:0 18px 34px rgba(15,23,42,.10)}.kh-job.active{border-color:#2563eb;background:linear-gradient(135deg,#eff6ff,#eef2ff)}.kh-avatar{width:54px;height:54px;border-radius:18px;object-fit:cover;background:#e2e8f0}.kh-pill{border-radius:999px;background:#eef2ff;color:#3730a3;padding:6px 10px;font-size:12px;font-weight:700}.kh-date{display:flex;align-items:center;gap:15px;padding:13px;border-radius:20px;border:1px solid #e2e8f0;background:#fff;transition:.2s}.kh-date:hover{transform:translateY(-2px);box-shadow:0 12px 28px rgba(15,23,42,.08)}.kh-date.active{border-color:#10b981;background:#ecfdf5}.kh-datebox{width:72px;border-radius:16px;background:#f1f5f9;text-align:center;padding:9px}.kh-row-input{background:#f8fafc;border:1px solid #e2e8f0;border-radius:20px;padding:14px;margin-bottom:12px}.kh-accordion summary{list-style:none;cursor:pointer}.kh-accordion summary::-webkit-details-marker{display:none}.kh-table{width:100%;border-collapse:collapse}.kh-table th{background:#f1f5f9;text-align:left;font-size:13px;padding:13px}.kh-table td{border-top:1px solid #e2e8f0;padding:13px;vertical-align:top}.kh-input,.kh-select,.kh-textarea{width:100%;border:1px solid #cbd5e1;border-radius:14px;padding:11px 13px;background:#fff}.kh-textarea{resize:vertical;min-height:58px}.kh-btn{border-radius:16px;padding:12px 18px;font-weight:800}.kh-btn-primary{background:#2563eb;color:#fff}.kh-btn-soft{background:#eef2ff;color:#3730a3}.kh-btn-dark{background:#0f172a;color:#fff}.kh-activity-grid{
    display:grid;
    grid-template-columns:minmax(220px,1.25fr) minmax(150px,.85fr) minmax(250px,1.4fr) minmax(145px,.72fr) minmax(145px,.72fr) minmax(250px,1.35fr);
    gap:12px;
    align-items:start
}
.kh-time-input{min-width:145px;font-size:16px;font-weight:700;padding-left:14px;padding-right:10px}
.kh-action-btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;border-radius:11px;padding:8px 11px;font-size:12px;font-weight:800;white-space:nowrap}
.kh-edit-btn{background:#dbeafe;color:#1d4ed8}.kh-delete-btn{background:#ffe4e6;color:#be123c}
.kh-modal{position:fixed;inset:0;display:none;align-items:center;justify-content:center;padding:20px;background:rgba(15,23,42,.60);backdrop-filter:blur(5px);z-index:99999}
.kh-modal.open{display:flex}
.kh-modal-panel{width:min(920px,96vw);max-height:92vh;overflow:auto;background:#fff;border-radius:26px;padding:22px;box-shadow:0 30px 80px rgba(15,23,42,.30)}
.kh-unit-section{border:1px solid #e2e8f0;border-radius:18px;overflow:hidden;margin-top:14px}
.kh-unit-section-title{display:flex;align-items:center;justify-content:space-between;gap:12px;background:#f8fafc;padding:12px 14px;font-weight:800}
.kh-table .kh-col-time{min-width:160px;width:160px}
.kh-table .kh-col-action{min-width:145px;width:145px}
@media(max-width:1100px){.kh-activity-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}
@media(max-width:900px){.kh-grid,.kh-activity-grid{grid-template-columns:1fr!important}.kh-table{font-size:12px}.kh-time-input{min-width:100%}}
</style>
<div class="kh-wrap space-y-6">
    <?php if (isset($_GET['saved'])): ?><div class="kh-card p-4 border-l-4 border-green-500 text-green-700">Berhasil menyimpan <?= (int)$_GET['saved'] ?> kegiatan.</div><?php endif; ?>
    <?php if (isset($_GET['updated'])): ?><div class="kh-card p-4 border-l-4 border-blue-500 text-blue-700">Kegiatan berhasil diperbarui.</div><?php endif; ?>
    <?php if (isset($_GET['deleted'])): ?><div class="kh-card p-4 border-l-4 border-rose-500 text-rose-700">Kegiatan berhasil dihapus.</div><?php endif; ?>
    <section class="kh-hero">
        <div class="relative z-10 flex flex-col md:flex-row md:items-center md:justify-between gap-5">
            <div>
                <div class="inline-flex items-center gap-2 px-3 py-2 rounded-full bg-white/15 text-sm font-bold mb-3"><i class="fas fa-calendar-check"></i> Kegiatan Harian Keperawatan</div>
                <h2 class="text-3xl md:text-4xl font-extrabold">Rencana & Realisasi Kegiatan</h2>
                <p class="mt-2 text-blue-50">Klik card jabatan untuk membuka input, lalu klik tanggal untuk melihat kegiatan harian/bulanan.</p>
            </div>
            <div class="bg-white/15 border border-white/20 rounded-3xl p-4 min-w-[260px]">
                <div class="flex items-center gap-3">
                    <?php if ($profilePhoto && file_exists(__DIR__ . '/../../' . $profilePhoto)): ?><img src="<?= e($profilePhoto) ?>" class="kh-avatar" alt="profile"><?php else: ?><div class="kh-avatar flex items-center justify-center text-slate-500 bg-white/30"><i class="fas fa-user"></i></div><?php endif; ?>
                    <div><div class="text-xs uppercase text-blue-100 font-bold">Login sebagai</div><div class="font-extrabold leading-tight"><?= e($cu['name']) ?></div><div class="text-xs text-blue-100"><?= e($cu['role']) ?></div></div>
                </div>
            </div>
        </div>
    </section>

    <section class="kh-card p-5">
        <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-3 mb-4">
            <div><h3 class="text-xl font-extrabold">Pilih Jabatan</h3><p class="text-sm text-slate-500">Pilih salah satu card. Form input akan mengikuti jabatan yang dipilih.</p></div>
            <form method="GET" class="flex gap-2 items-center">
                <input type="hidden" name="module" value="kegiatan_harian"><input type="hidden" name="job" value="<?= e($activeJob) ?>">
                <select name="month" class="kh-select" style="width:90px"><?php for($i=1;$i<=12;$i++): ?><option value="<?= $i ?>" <?= $i===$month?'selected':'' ?>><?= $i ?></option><?php endfor; ?></select>
                <input type="number" name="year" value="<?= $year ?>" class="kh-input" style="width:110px">
                <button class="kh-btn kh-btn-dark">Bulan</button>
            </form>
        </div>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 kh-grid">
            <?php foreach ($jobs as $j): $countJ = 0; foreach ($activities as $a) if (($a['job_title'] ?? '') === $j) $countJ++; ?>
                <a class="kh-job <?= $j===$activeJob?'active':'' ?>" href="?module=kegiatan_harian&date=<?= e($selectedDate) ?>&month=<?= $month ?>&year=<?= $year ?>&job=<?= rawurlencode($j) ?>#inputKegiatan">
                    <div class="flex items-start gap-3">
                        <?php $jobPhoto = (string)($jobPhotos[$j] ?? ''); ?><?php if ($jobPhoto && file_exists(__DIR__ . '/../../' . $jobPhoto)): ?><img src="<?= e($jobPhoto) ?>" class="kh-avatar" alt="foto jabatan"><?php else: ?><div class="kh-avatar flex items-center justify-center"><i class="fas fa-user-tie"></i></div><?php endif; ?>
                        <div class="flex-1"><div class="font-extrabold leading-tight"><?= e($j) ?></div><div class="text-sm text-slate-500 mt-1">Klik untuk input kegiatan</div><div class="mt-3"><span class="kh-pill"><?= $countJ ?> kegiatan filter aktif</span></div></div>
                    </div>
                </a>
            <?php endforeach; ?>
        </div>
    </section>

    <section class="grid grid-cols-1 lg:grid-cols-3 gap-6 kh-grid">
        <div class="kh-card p-5 lg:col-span-1">
            <h3 class="text-xl font-extrabold mb-1">Tanggal Kegiatan</h3><p class="text-sm text-slate-500 mb-4">Klik tanggal untuk melihat rincian kegiatan.</p>
            <div class="space-y-3 max-h-[520px] overflow-y-auto pr-1">
                <?php if (empty($dateCards)): ?><div class="text-slate-500 text-sm border border-dashed rounded-2xl p-4">Belum ada kegiatan bulan ini.</div><?php endif; ?>
                <?php foreach($dateCards as $d): $isA = $d['activity_date']===$selectedDate; ?>
                    <a class="kh-date <?= $isA?'active':'' ?>" href="?module=kegiatan_harian&date=<?= e($d['activity_date']) ?>&month=<?= $month ?>&year=<?= $year ?>&job=<?= rawurlencode($activeJob) ?>#rekapKegiatan">
                        <div class="kh-datebox"><div class="text-xs font-bold text-slate-500"><?= strtoupper(date('M', strtotime($d['activity_date']))) ?></div><div class="text-2xl font-extrabold"><?= date('d', strtotime($d['activity_date'])) ?></div></div>
                        <div class="flex-1"><div class="font-extrabold"><?= date('d/m/Y', strtotime($d['activity_date'])) ?></div><div class="text-sm text-slate-500"><?= (int)$d['total'] ?> kegiatan · <?= (int)$d['jobs'] ?> jabatan</div></div>
                        <i class="fas fa-chevron-right text-slate-400"></i>
                    </a>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="kh-card p-5 lg:col-span-2" id="inputKegiatan">
            <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-3 mb-4">
                <div><h3 class="text-xl font-extrabold">Input Kegiatan</h3><p class="text-sm text-slate-500">Jabatan aktif: <b><?= e($activeJob) ?></b></p></div>
                <button type="button" onclick="khAddRow()" class="kh-btn kh-btn-soft"><i class="fas fa-plus mr-1"></i> Tambah Baris</button>
            </div>
            <form method="POST" id="khForm">
                <input type="hidden" name="action" value="save_activities"><input type="hidden" name="job_title" value="<?= e($activeJob) ?>">
                <div class="mb-4"><label class="font-bold text-sm">Tanggal</label><input type="date" name="activity_date" value="<?= e($selectedDate) ?>" class="kh-input mt-1 max-w-[240px]"></div>
                <div id="khRows"></div>
                <div class="flex justify-end mt-4"><button class="kh-btn kh-btn-primary"><i class="fas fa-save mr-2"></i>Simpan Semua Baris</button></div>
            </form>
        </div>
    </section>

    <section class="kh-card p-5" id="rekapKegiatan">
        <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-3 mb-4">
            <div><h3 class="text-xl font-extrabold">Rekap Kegiatan</h3><p class="text-sm text-slate-500">Mode <?= $viewMode==='day'?'harian':'bulanan' ?>. Klik jabatan untuk membuka detail.</p></div>
            <form method="GET" class="flex flex-wrap gap-2"><input type="hidden" name="module" value="kegiatan_harian"><input type="hidden" name="job" value="<?= e($activeJob) ?>"><select name="mode" class="kh-select" style="width:140px"><option value="day" <?= $viewMode==='day'?'selected':'' ?>>Per Hari</option><option value="month" <?= $viewMode==='month'?'selected':'' ?>>Per Bulan</option></select><input type="date" name="date" value="<?= e($selectedDate) ?>" class="kh-input" style="width:170px"><select name="month" class="kh-select" style="width:80px"><?php for($i=1;$i<=12;$i++): ?><option value="<?= $i ?>" <?= $i===$month?'selected':'' ?>><?= $i ?></option><?php endfor; ?></select><input type="number" name="year" value="<?= $year ?>" class="kh-input" style="width:110px"><button class="kh-btn kh-btn-dark">Tampilkan</button></form>
        </div>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-3 mb-4"><div class="rounded-2xl bg-slate-50 border p-4"><div class="text-sm text-slate-500">Total Kegiatan</div><div class="text-3xl font-extrabold"><?= count($activities) ?></div></div><div class="rounded-2xl bg-slate-50 border p-4"><div class="text-sm text-slate-500">Jumlah Jabatan</div><div class="text-3xl font-extrabold"><?= count($byJob) ?></div></div><div class="rounded-2xl bg-slate-50 border p-4"><div class="text-sm text-slate-500">Filter</div><div class="text-lg font-extrabold"><?= $viewMode==='day' ? e(date('d/m/Y', strtotime($selectedDate))) : e($month.'/'.$year) ?></div></div></div>
        <?php if (empty($byJob)): ?><div class="border border-dashed rounded-3xl p-10 text-center text-slate-500">Belum ada kegiatan pada filter ini.</div><?php endif; ?>
        <div class="space-y-4">
            <?php foreach($byJob as $job => $rows):
                $unitGroups = [];
                foreach ($rows as $r) {
                    $un = trim((string)($r['unit_name'] ?? '')) ?: 'Tidak disebutkan';
                    if (!isset($unitGroups[$un])) $unitGroups[$un] = [];
                    $unitGroups[$un][] = $r;
                }
            ?>
            <details class="kh-accordion kh-card p-4" open>
                <summary>
                    <div class="flex items-center justify-between gap-3">
                        <div>
                            <h4 class="font-extrabold text-lg"><?= e($job) ?></h4>
                            <p class="text-sm text-slate-500"><?= count($rows) ?> kegiatan · <?= count($unitGroups) ?> unit terkait</p>
                            <div class="flex flex-wrap gap-2 mt-2">
                                <?php foreach($unitGroups as $un=>$unitRows): ?>
                                    <span class="kh-pill"><?= e($un) ?>: <?= count($unitRows) ?></span>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <div class="text-right">
                            <span class="inline-flex items-center justify-center w-9 h-9 rounded-full bg-emerald-100 text-emerald-700 font-extrabold"><?= count($rows) ?></span>
                            <i class="fas fa-chevron-down ml-3"></i>
                        </div>
                    </div>
                </summary>

                <?php foreach ($unitGroups as $unitNameGroup => $unitRows): ?>
                    <div class="kh-unit-section">
                        <div class="kh-unit-section-title">
                            <div><i class="fas fa-hospital mr-2 text-blue-600"></i><?= e($unitNameGroup) ?></div>
                            <span class="kh-pill"><?= count($unitRows) ?> kegiatan</span>
                        </div>
                        <div class="overflow-x-auto">
                            <table class="kh-table">
                                <thead>
                                    <tr>
                                        <th>No</th>
                                        <th>Tanggal</th>
                                        <th>Jenis</th>
                                        <th>Kegiatan</th>
                                        <th class="kh-col-time">Jam</th>
                                        <th>Hasil/Keterangan</th>
                                        <th>Pengisi</th>
                                        <th class="kh-col-action">Aksi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                <?php foreach($unitRows as $i=>$r):
                                    $canEditRow = $isAdmin || (int)($r['created_by'] ?? 0) === (int)$cu['id'];
                                    $rowPayload = [
                                        'id' => (int)$r['id'],
                                        'activity_date' => (string)$r['activity_date'],
                                        'unit_id' => (int)($r['unit_id'] ?? 0),
                                        'unit_name' => (string)($r['unit_name'] ?? ''),
                                        'activity_type' => (string)($r['activity_type'] ?? ''),
                                        'activity_text' => (string)($r['activity_text'] ?? ''),
                                        'start_time' => $r['start_time'] ? substr((string)$r['start_time'],0,5) : '',
                                        'end_time' => $r['end_time'] ? substr((string)$r['end_time'],0,5) : '',
                                        'result_note' => (string)($r['result_note'] ?? ''),
                                    ];
                                ?>
                                    <tr>
                                        <td><?= $i+1 ?></td>
                                        <td><?= e(date('d/m/Y', strtotime($r['activity_date']))) ?></td>
                                        <td><?= e($r['activity_type'] ?: '-') ?></td>
                                        <td><?= nl2br(e($r['activity_text'] ?: '-')) ?></td>
                                        <td class="kh-col-time font-semibold"><?= e(($r['start_time'] ? substr($r['start_time'],0,5) : '-') . ' – ' . ($r['end_time'] ? substr($r['end_time'],0,5) : '-')) ?></td>
                                        <td><?= nl2br(e($r['result_note'] ?: '-')) ?></td>
                                        <td><?= e($r['created_by_name'] ?: '-') ?></td>
                                        <td class="kh-col-action">
                                            <?php if ($canEditRow): ?>
                                                <div class="flex flex-wrap gap-2">
                                                    <button type="button"
                                                            class="kh-action-btn kh-edit-btn"
                                                            data-row="<?= e(json_encode($rowPayload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)) ?>"
                                                            onclick="khOpenEdit(this)">
                                                        <i class="fas fa-pen"></i>Edit
                                                    </button>
                                                    <form method="POST" onsubmit="return confirm('Hapus kegiatan ini?')">
                                                        <input type="hidden" name="action" value="delete_activity">
                                                        <input type="hidden" name="activity_id" value="<?= (int)$r['id'] ?>">
                                                        <input type="hidden" name="return_date" value="<?= e($selectedDate) ?>">
                                                        <input type="hidden" name="return_month" value="<?= (int)$month ?>">
                                                        <input type="hidden" name="return_year" value="<?= (int)$year ?>">
                                                        <input type="hidden" name="return_mode" value="<?= e($viewMode) ?>">
                                                        <input type="hidden" name="return_job" value="<?= e($activeJob) ?>">
                                                        <button class="kh-action-btn kh-delete-btn"><i class="fas fa-trash"></i></button>
                                                    </form>
                                                </div>
                                            <?php else: ?>
                                                <span class="text-xs text-slate-400">Tidak tersedia</span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                <?php endforeach; ?>
            </details>
            <?php endforeach; ?>
        </div>
        </div>
    </section>

    <?php if($isAdmin): ?>
    <section class="kh-card p-5">
        <h3 class="text-xl font-extrabold mb-1">Ringkasan Admin Bulanan</h3><p class="text-sm text-slate-500 mb-4">Komposisi total kegiatan per unit pada bulan yang dipilih.</p>
        <div class="overflow-x-auto"><table class="kh-table"><thead><tr><th>Unit</th><th>Total Kegiatan</th></tr></thead><tbody><?php if(empty($adminUnitSummary)): ?><tr><td colspan="2" class="text-center text-slate-500">Belum ada data bulan ini.</td></tr><?php endif; ?><?php foreach($adminUnitSummary as $r): ?><tr><td><?= e($r['unit_name']) ?></td><td class="font-extrabold"><?= (int)$r['total'] ?></td></tr><?php endforeach; ?></tbody></table></div>
    </section>
    <?php endif; ?>
</div>

<div id="khEditModal" class="kh-modal" aria-hidden="true">
    <div class="kh-modal-panel">
        <div class="flex items-center justify-between gap-3 mb-5">
            <div>
                <h3 class="text-2xl font-extrabold">Edit Kegiatan</h3>
                <p class="text-sm text-slate-500">Perbarui data kegiatan pada unit terkait.</p>
            </div>
            <button type="button" onclick="khCloseEdit()" class="w-11 h-11 rounded-full bg-slate-100 text-slate-700 font-bold text-xl">&times;</button>
        </div>

        <form method="POST" id="khEditForm">
            <input type="hidden" name="action" value="edit_activity">
            <input type="hidden" name="activity_id" id="edit_activity_id">
            <input type="hidden" name="return_date" value="<?= e($selectedDate) ?>">
            <input type="hidden" name="return_month" value="<?= (int)$month ?>">
            <input type="hidden" name="return_year" value="<?= (int)$year ?>">
            <input type="hidden" name="return_mode" value="<?= e($viewMode) ?>">
            <input type="hidden" name="return_job" value="<?= e($activeJob) ?>">

            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label class="text-xs font-bold text-slate-500">Tanggal</label>
                    <input type="date" name="activity_date" id="edit_activity_date" class="kh-input mt-1" required>
                </div>
                <div>
                    <label class="text-xs font-bold text-slate-500">Jenis</label>
                    <select name="activity_type" id="edit_activity_type" class="kh-select mt-1">
                        <?php foreach($types as $tp): ?><option value="<?= e($tp) ?>"><?= e($tp) ?></option><?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="text-xs font-bold text-slate-500">Unit</label>
                    <select name="unit_id" id="edit_unit_id" class="kh-select mt-1">
                        <option value="0">-- Pilih Unit --</option>
                        <?php foreach($units as $u): ?><option value="<?= (int)$u['id'] ?>"><?= e($u['name']) ?></option><?php endforeach; ?>
                    </select>
                    <input name="unit_manual" id="edit_unit_manual" class="kh-input mt-2" placeholder="atau ketik unit manual">
                </div>
                <div>
                    <label class="text-xs font-bold text-slate-500">Jam</label>
                    <div class="grid grid-cols-2 gap-3 mt-1">
                        <input type="time" name="start_time" id="edit_start_time" class="kh-input kh-time-input">
                        <input type="time" name="end_time" id="edit_end_time" class="kh-input kh-time-input">
                    </div>
                </div>
                <div class="md:col-span-2">
                    <label class="text-xs font-bold text-slate-500">Kegiatan</label>
                    <textarea name="activity_text" id="edit_activity_text" class="kh-textarea mt-1 min-h-[100px]" required></textarea>
                </div>
                <div class="md:col-span-2">
                    <label class="text-xs font-bold text-slate-500">Hasil/Keterangan</label>
                    <textarea name="result_note" id="edit_result_note" class="kh-textarea mt-1 min-h-[90px]"></textarea>
                </div>
            </div>

            <div class="flex justify-end gap-3 mt-6">
                <button type="button" onclick="khCloseEdit()" class="kh-btn bg-slate-100 text-slate-700">Batal</button>
                <button class="kh-btn kh-btn-primary"><i class="fas fa-save mr-2"></i>Simpan Perubahan</button>
            </div>
        </form>
    </div>
</div>

<script>
const khUnits = <?= json_encode($units, JSON_UNESCAPED_UNICODE) ?>;
const khTypes = <?= json_encode($types, JSON_UNESCAPED_UNICODE) ?>;
function khRowTemplate(idx){
    const unitOpts = ['<option value="0">-- Pilih Unit --</option>'].concat(khUnits.map(u=>`<option value="${u.id}">${u.name}</option>`)).join('');
    const typeOpts = ['<option value="">-- Jenis --</option>'].concat(khTypes.map(t=>`<option value="${t}">${t}</option>`)).join('');
    return `<div class="kh-row-input" data-row="${idx}">
        <div class="kh-activity-grid">
            <div>
                <label class="text-xs font-bold text-slate-500">Unit</label>
                <select name="unit_id[]" class="kh-select mt-1">${unitOpts}</select>
                <input name="unit_manual[]" class="kh-input mt-2" placeholder="atau ketik unit manual">
            </div>
            <div>
                <label class="text-xs font-bold text-slate-500">Jenis</label>
                <select name="activity_type[]" class="kh-select mt-1">${typeOpts}</select>
            </div>
            <div>
                <label class="text-xs font-bold text-slate-500">Kegiatan</label>
                <textarea name="activity_text[]" class="kh-textarea mt-1" placeholder="Kegiatan yang dikerjakan"></textarea>
            </div>
            <div>
                <label class="text-xs font-bold text-slate-500">Mulai</label>
                <input type="time" name="start_time[]" class="kh-input kh-time-input mt-1">
            </div>
            <div>
                <label class="text-xs font-bold text-slate-500">Selesai</label>
                <input type="time" name="end_time[]" class="kh-input kh-time-input mt-1">
            </div>
            <div>
                <label class="text-xs font-bold text-slate-500">Hasil/Keterangan</label>
                <textarea name="result_note[]" class="kh-textarea mt-1" placeholder="Hasil/keterangan"></textarea>
            </div>
        </div>
        <div class="flex justify-end mt-3">
            <button type="button" onclick="this.closest('.kh-row-input').remove()" class="px-4 py-2 rounded-xl bg-rose-100 text-rose-700 font-bold">Hapus</button>
        </div>
    </div>`;
}
function khAddRow(){ const wrap=document.getElementById('khRows'); wrap.insertAdjacentHTML('beforeend', khRowTemplate(wrap.children.length+1)); }
document.addEventListener('DOMContentLoaded',()=>{ if(document.getElementById('khRows').children.length===0) khAddRow(); });

function khOpenEdit(button){
    let row = {};
    try { row = JSON.parse(button.dataset.row || '{}'); } catch(e) { return; }
    document.getElementById('edit_activity_id').value = row.id || '';
    document.getElementById('edit_activity_date').value = row.activity_date || '';
    document.getElementById('edit_unit_id').value = String(row.unit_id || 0);
    document.getElementById('edit_unit_manual').value = row.unit_name || '';
    document.getElementById('edit_activity_type').value = row.activity_type || '';
    document.getElementById('edit_activity_text').value = row.activity_text || '';
    document.getElementById('edit_start_time').value = row.start_time || '';
    document.getElementById('edit_end_time').value = row.end_time || '';
    document.getElementById('edit_result_note').value = row.result_note || '';
    const modal = document.getElementById('khEditModal');
    modal.classList.add('open');
    modal.setAttribute('aria-hidden','false');
    document.body.style.overflow='hidden';
}
function khCloseEdit(){
    const modal = document.getElementById('khEditModal');
    modal.classList.remove('open');
    modal.setAttribute('aria-hidden','true');
    document.body.style.overflow='';
}
document.getElementById('khEditModal')?.addEventListener('click', function(e){
    if(e.target === this) khCloseEdit();
});
document.addEventListener('keydown', function(e){
    if(e.key === 'Escape') khCloseEdit();
});

</script>
