<?php
declare(strict_types=1);

if (!function_exists('getConnection')) {
    require_once __DIR__ . '/../../config/database.php';
}
if (!function_exists('current_user')) {
    require_once __DIR__ . '/../../config/master_auth.php';
}

$conn = getConnection();
$user = current_user() ?? [];
$currentRole = strtolower((string)($user['role'] ?? ($_SESSION['user_role'] ?? 'viewer')));
$currentEmployeeId = (int)($user['employee_id'] ?? 0);
$currentUserName = (string)($user['nama'] ?? $user['username'] ?? 'System');
$currentUserUnitId = (int)($user['unit_id'] ?? 0);

$fullAccessRoles = ['superadmin', 'admin', 'editor', 'kepala_unit', 'kasubdiv', 'kadiv'];
$canCreate = in_array($currentRole, $fullAccessRoles, true);
$canEdit   = in_array($currentRole, $fullAccessRoles, true);
$canDelete = in_array($currentRole, ['superadmin', 'admin'], true);

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

function ptl_table_has_column(mysqli $conn, string $table, string $column): bool
{
    $table = $conn->real_escape_string($table);
    $column = $conn->real_escape_string($column);
    $result = $conn->query("SHOW COLUMNS FROM `{$table}` LIKE '{$column}'");
    return $result instanceof mysqli_result && $result->num_rows > 0;
}

function ptl_redirect(array $params = []): void
{
    $query = array_merge(['module' => 'permasalahan_tindak_lanjut'], $params);
    $url = 'index.php?' . http_build_query($query);

    echo '<script>window.location.href=' . json_encode($url) . ';</script>';
    echo '<noscript><meta http-equiv="refresh" content="0;url=' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '"></noscript>';
    exit;
}

function ptl_fetch_units(mysqli $conn): array
{
    $rows = [];
    $sql = "SELECT id, name, report_type, category FROM units WHERE is_active = 1 ORDER BY name ASC";
    $res = $conn->query($sql);
    if ($res instanceof mysqli_result) {
        while ($row = $res->fetch_assoc()) {
            $rows[] = $row;
        }
    }
    return $rows;
}

function ptl_log_safe(string $action, int $recordId, string $desc): void
{
    if (function_exists('logActivity')) {
        @logActivity($action, 'permasalahan_tindak_lanjut', $recordId, $desc);
    }
}

$requiredColumns = [
    'detail_permasalahan',
    'unit_pelapor_id',
    'unit_terkait_id',
    'status',
    'tanggal_mulai',
    'tanggal_target',
    'penyelesaian',
    'masukan_kepala_divisi',
    'masukan_ptbdm',
];

$missingColumns = [];
foreach ($requiredColumns as $col) {
    if (!ptl_table_has_column($conn, 'permasalahan_unit', $col)) {
        $missingColumns[] = $col;
    }
}

if (!empty($missingColumns)) {
    echo '<div class="bg-red-50 border border-red-200 text-red-700 rounded-2xl p-6">';
    echo '<h2 class="text-xl font-bold mb-2">Struktur tabel belum siap</h2>';
    echo '<p class="mb-2">Kolom berikut belum ada di tabel <code>permasalahan_unit</code>:</p>';
    echo '<ul class="list-disc ml-6">';
    foreach ($missingColumns as $col) {
        echo '<li><code>' . e($col) . '</code></li>';
    }
    echo '</ul>';
    echo '<p class="mt-3">Jalankan patch SQL dulu, lalu refresh halaman ini.</p>';
    echo '</div>';
    return;
}

if (isset($_GET['mark_notif']) && $_GET['mark_notif'] === '1') {
    $conn->query("UPDATE permasalahan_unit SET is_read_admin = 1 WHERE is_read_admin = 0");
    ptl_redirect(['msg' => 'Notifikasi sudah ditandai dibaca.', 'type' => 'success']);
}

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

    if ($action === 'create' && $canCreate) {
        $permasalahan = trim((string)($_POST['permasalahan'] ?? ''));
        $detail = trim((string)($_POST['detail_permasalahan'] ?? ''));
        $unitPelaporId = (int)($_POST['unit_pelapor_id'] ?? 0);
        $unitTerkaitId = (int)($_POST['unit_terkait_id'] ?? 0);
        $status = trim((string)($_POST['status'] ?? 'Belum Selesai'));
        $tindakLanjut = trim((string)($_POST['tindak_lanjut'] ?? ''));
        $penyelesaian = trim((string)($_POST['penyelesaian'] ?? ''));
        $masukanKepalaDivisi = trim((string)($_POST['masukan_kepala_divisi'] ?? ''));
        $masukanPtbdm = trim((string)($_POST['masukan_ptbdm'] ?? ''));
        $tanggalMulai = trim((string)($_POST['tanggal_mulai'] ?? ''));
        $tanggalTarget = trim((string)($_POST['tanggal_target'] ?? ''));

        if ($permasalahan === '' || $unitPelaporId <= 0) {
            ptl_redirect(['msg' => 'Permasalahan dan unit pelapor wajib diisi.', 'type' => 'error']);
        }

        if (!in_array($status, ['Belum Selesai', 'Proses', 'Selesai'], true)) {
            $status = 'Belum Selesai';
        }

        $stmt = $conn->prepare("
            INSERT INTO permasalahan_unit
            (
                laporan_id,
                permasalahan,
                detail_permasalahan,
                unit_pelapor_id,
                unit_terkait_id,
                status,
                tindak_lanjut,
                penyelesaian,
                masukan_kepala_divisi,
                masukan_ptbdm,
                tanggal_mulai,
                tanggal_target,
                created_by_employee_id,
                created_by_name,
                is_read_admin,
                notif_created_at
            )
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, NOW())
        ");

        if (!$stmt) {
            ptl_redirect(['msg' => 'Gagal menyiapkan query insert.', 'type' => 'error']);
        }

        $laporanId = null;
        $tanggalMulai = $tanggalMulai !== '' ? $tanggalMulai : null;
        $tanggalTarget = $tanggalTarget !== '' ? $tanggalTarget : null;
        $unitTerkaitParam = $unitTerkaitId > 0 ? $unitTerkaitId : null;
        $createdByEmployeeId = $currentEmployeeId > 0 ? $currentEmployeeId : null;

        $stmt->bind_param(
            "issiisssssssis",
            $laporanId,
            $permasalahan,
            $detail,
            $unitPelaporId,
            $unitTerkaitParam,
            $status,
            $tindakLanjut,
            $penyelesaian,
            $masukanKepalaDivisi,
            $masukanPtbdm,
            $tanggalMulai,
            $tanggalTarget,
            $createdByEmployeeId,
            $currentUserName
        );

        if ($stmt->execute()) {
            $newId = (int)$stmt->insert_id;
            ptl_log_safe('create', $newId, 'Menambah permasalahan baru: ' . $permasalahan);
            ptl_redirect([
                'msg' => 'Data permasalahan berhasil disimpan.',
                'type' => 'success',
                'play_sound' => 1
            ]);
        }

        ptl_redirect(['msg' => 'Gagal menyimpan data: ' . $stmt->error, 'type' => 'error']);
    }

    if ($action === 'update' && $canEdit) {
        $id = (int)($_POST['id'] ?? 0);
        $status = trim((string)($_POST['status'] ?? 'Belum Selesai'));
        $tindakLanjut = trim((string)($_POST['tindak_lanjut'] ?? ''));
        $penyelesaian = trim((string)($_POST['penyelesaian'] ?? ''));
        $masukanKepalaDivisi = trim((string)($_POST['masukan_kepala_divisi'] ?? ''));
        $masukanPtbdm = trim((string)($_POST['masukan_ptbdm'] ?? ''));
        $tanggalMulai = trim((string)($_POST['tanggal_mulai'] ?? ''));
        $tanggalTarget = trim((string)($_POST['tanggal_target'] ?? ''));

        if ($id <= 0) {
            ptl_redirect(['msg' => 'ID data tidak valid.', 'type' => 'error']);
        }

        if (!in_array($status, ['Belum Selesai', 'Proses', 'Selesai'], true)) {
            $status = 'Belum Selesai';
        }

        $tanggalMulai = $tanggalMulai !== '' ? $tanggalMulai : null;
        $tanggalTarget = $tanggalTarget !== '' ? $tanggalTarget : null;

        $stmt = $conn->prepare("
            UPDATE permasalahan_unit
            SET
                status = ?,
                tindak_lanjut = ?,
                penyelesaian = ?,
                masukan_kepala_divisi = ?,
                masukan_ptbdm = ?,
                tanggal_mulai = ?,
                tanggal_target = ?
            WHERE id = ?
            LIMIT 1
        ");

        if (!$stmt) {
            ptl_redirect(['msg' => 'Gagal menyiapkan query update.', 'type' => 'error']);
        }

        $stmt->bind_param(
            "sssssssi",
            $status,
            $tindakLanjut,
            $penyelesaian,
            $masukanKepalaDivisi,
            $masukanPtbdm,
            $tanggalMulai,
            $tanggalTarget,
            $id
        );

        if ($stmt->execute()) {
            ptl_log_safe('update', $id, 'Mengubah permasalahan / tindak lanjut ID: ' . $id);
            ptl_redirect(['msg' => 'Data berhasil diupdate.', 'type' => 'success']);
        }

        ptl_redirect(['msg' => 'Gagal update data: ' . $stmt->error, 'type' => 'error']);
    }

    if ($action === 'delete' && $canDelete) {
        $id = (int)($_POST['id'] ?? 0);
        if ($id > 0) {
            $stmt = $conn->prepare("DELETE FROM permasalahan_unit WHERE id = ? LIMIT 1");
            if ($stmt) {
                $stmt->bind_param("i", $id);
                if ($stmt->execute()) {
                    ptl_log_safe('delete', $id, 'Menghapus permasalahan ID: ' . $id);
                    ptl_redirect(['msg' => 'Data berhasil dihapus.', 'type' => 'success']);
                }
                ptl_redirect(['msg' => 'Gagal menghapus data: ' . $stmt->error, 'type' => 'error']);
            }
        }
        ptl_redirect(['msg' => 'ID hapus tidak valid.', 'type' => 'error']);
    }
}

$units = ptl_fetch_units($conn);

$q = trim((string)($_GET['q'] ?? ''));
$status = trim((string)($_GET['status'] ?? ''));
$unitPelaporId = (int)($_GET['unit_pelapor_id'] ?? 0);
$unitTerkaitId = (int)($_GET['unit_terkait_id'] ?? 0);
$msg = trim((string)($_GET['msg'] ?? ''));
$type = trim((string)($_GET['type'] ?? 'success'));
$playSound = (int)($_GET['play_sound'] ?? 0) === 1;

$sql = "
    SELECT
        pu.*,
        up.name AS unit_pelapor,
        ut.name AS unit_terkait,
        DATE_FORMAT(pu.created_at, '%d-%m-%Y %H:%i') AS created_at_formatted,
        CASE
            WHEN pu.tanggal_mulai IS NOT NULL AND pu.tanggal_target IS NOT NULL
            THEN DATEDIFF(pu.tanggal_target, pu.tanggal_mulai)
            ELSE NULL
        END AS lama_penyelesaian_hari
    FROM permasalahan_unit pu
    LEFT JOIN units up ON up.id = pu.unit_pelapor_id
    LEFT JOIN units ut ON ut.id = pu.unit_terkait_id
    WHERE 1 = 1
";

$types = '';
$params = [];

if ($q !== '') {
    $sql .= " AND (
        pu.permasalahan LIKE ?
        OR pu.detail_permasalahan LIKE ?
        OR pu.tindak_lanjut LIKE ?
        OR pu.penyelesaian LIKE ?
        OR pu.masukan_kepala_divisi LIKE ?
        OR pu.masukan_ptbdm LIKE ?
    )";
    $like = '%' . $q . '%';
    $types .= 'ssssss';
    array_push($params, $like, $like, $like, $like, $like, $like);
}

if ($status !== '') {
    $sql .= " AND pu.status = ?";
    $types .= 's';
    $params[] = $status;
}

if ($unitPelaporId > 0) {
    $sql .= " AND pu.unit_pelapor_id = ?";
    $types .= 'i';
    $params[] = $unitPelaporId;
}

if ($unitTerkaitId > 0) {
    $sql .= " AND pu.unit_terkait_id = ?";
    $types .= 'i';
    $params[] = $unitTerkaitId;
}

$sql .= " ORDER BY
            FIELD(pu.status, 'Belum Selesai', 'Proses', 'Selesai'),
            pu.created_at DESC,
            pu.id DESC";

$rows = [];
$stmt = $conn->prepare($sql);
if ($stmt) {
    if ($types !== '' && !empty($params)) {
        $stmt->bind_param($types, ...$params);
    }
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result instanceof mysqli_result) {
        while ($row = $result->fetch_assoc()) {
            $rows[] = $row;
        }
    }
}

$stats = [
    'total' => 0,
    'belum' => 0,
    'proses' => 0,
    'selesai' => 0,
];

$statRes = $conn->query("
    SELECT
        COUNT(*) AS total,
        SUM(CASE WHEN status = 'Belum Selesai' THEN 1 ELSE 0 END) AS belum,
        SUM(CASE WHEN status = 'Proses' THEN 1 ELSE 0 END) AS proses,
        SUM(CASE WHEN status = 'Selesai' THEN 1 ELSE 0 END) AS selesai
    FROM permasalahan_unit
");
if ($statRes instanceof mysqli_result) {
    $statRow = $statRes->fetch_assoc();
    if ($statRow) {
        $stats['total'] = (int)($statRow['total'] ?? 0);
        $stats['belum'] = (int)($statRow['belum'] ?? 0);
        $stats['proses'] = (int)($statRow['proses'] ?? 0);
        $stats['selesai'] = (int)($statRow['selesai'] ?? 0);
    }
}

$notifCount = 0;
$notifRes = $conn->query("SELECT COUNT(*) AS total FROM permasalahan_unit WHERE is_read_admin = 0");
if ($notifRes instanceof mysqli_result) {
    $notifRow = $notifRes->fetch_assoc();
    $notifCount = (int)($notifRow['total'] ?? 0);
}

$exportUrl = 'modules/permasalahan_tindak_lanjut_export.php?' . http_build_query([
    'q' => $q,
    'status' => $status,
    'unit_pelapor_id' => $unitPelaporId,
    'unit_terkait_id' => $unitTerkaitId,
]);
?>

<div class="space-y-6">
    <div class="bg-gradient-to-r from-indigo-600 via-blue-600 to-cyan-500 rounded-3xl p-6 text-white shadow-xl">
        <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
            <div>
                <h1 class="text-2xl lg:text-3xl font-bold">Permasalahan & Tindak Lanjut</h1>
                <p class="text-blue-100 mt-1">
                    Monitoring permasalahan unit, progres tindak lanjut, masukan kepala divisi, dan dokumentasi penyelesaian.
                </p>
            </div>
            <div class="flex flex-wrap gap-3">
                <a href="index.php?module=permasalahan_tindak_lanjut&mark_notif=1"
                   class="relative inline-flex items-center gap-2 px-4 py-3 rounded-xl bg-white text-slate-700 hover:bg-slate-100 font-semibold shadow">
                    <i class="fas fa-bell"></i>
                    Notif
                    <?php if ($notifCount > 0): ?>
                        <span class="absolute -top-2 -right-2 min-w-[24px] h-6 px-2 rounded-full bg-red-500 text-white text-xs flex items-center justify-center font-bold">
                            <?= $notifCount ?>
                        </span>
                    <?php endif; ?>
                </a>

                <?php if ($canCreate): ?>
                    <button type="button" id="openCreateModal" class="inline-flex items-center gap-2 px-4 py-3 rounded-xl bg-white text-blue-700 hover:bg-blue-50 font-semibold shadow">
                        <i class="fas fa-plus-circle"></i>
                        Tambah Permasalahan
                    </button>
                <?php endif; ?>

                <a href="<?= e($exportUrl) ?>" class="inline-flex items-center gap-2 px-4 py-3 rounded-xl bg-white/15 hover:bg-white/20 text-white font-medium border border-white/20">
                    <i class="fas fa-file-excel"></i>
                    Export Excel
                </a>
            </div>
        </div>
    </div>

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

    <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div class="bg-white rounded-2xl border border-slate-200 p-5 shadow-sm">
            <div class="text-sm text-slate-500">Total Data</div>
            <div class="text-3xl font-bold text-slate-800 mt-1"><?= $stats['total'] ?></div>
        </div>
        <div class="bg-red-50 rounded-2xl border border-red-100 p-5 shadow-sm">
            <div class="text-sm text-red-500">Belum Selesai</div>
            <div class="text-3xl font-bold text-red-700 mt-1"><?= $stats['belum'] ?></div>
        </div>
        <div class="bg-amber-50 rounded-2xl border border-amber-100 p-5 shadow-sm">
            <div class="text-sm text-amber-600">Proses</div>
            <div class="text-3xl font-bold text-amber-700 mt-1"><?= $stats['proses'] ?></div>
        </div>
        <div class="bg-green-50 rounded-2xl border border-green-100 p-5 shadow-sm">
            <div class="text-sm text-green-600">Selesai</div>
            <div class="text-3xl font-bold text-green-700 mt-1"><?= $stats['selesai'] ?></div>
        </div>
    </div>

    <div class="bg-white rounded-3xl shadow-sm border border-slate-200 overflow-hidden">
        <div class="px-6 py-5 border-b border-slate-200 bg-slate-50">
            <h2 class="text-lg font-bold text-slate-800">Filter & Daftar Permasalahan</h2>
        </div>

        <form method="GET" class="p-6 grid grid-cols-1 md:grid-cols-2 xl:grid-cols-5 gap-4 border-b border-slate-200">
            <input type="hidden" name="module" value="permasalahan_tindak_lanjut">

            <div class="xl:col-span-2">
                <label class="block text-sm font-medium text-slate-700 mb-2">Cari</label>
                <input
                    type="text"
                    name="q"
                    value="<?= e($q) ?>"
                    class="w-full rounded-2xl border border-slate-300 px-4 py-3"
                    placeholder="Cari permasalahan, tindak lanjut, penyelesaian..."
                >
            </div>

            <div>
                <label class="block text-sm font-medium text-slate-700 mb-2">Status</label>
                <select name="status" class="w-full rounded-2xl border border-slate-300 px-4 py-3">
                    <option value="">Semua Status</option>
                    <option value="Belum Selesai" <?= $status === 'Belum Selesai' ? 'selected' : '' ?>>Belum Selesai</option>
                    <option value="Proses" <?= $status === 'Proses' ? 'selected' : '' ?>>Proses</option>
                    <option value="Selesai" <?= $status === 'Selesai' ? 'selected' : '' ?>>Selesai</option>
                </select>
            </div>

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

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

            <div class="md:col-span-2 xl:col-span-5 flex flex-wrap gap-3">
                <button type="submit" class="px-5 py-3 rounded-2xl bg-slate-900 hover:bg-black text-white font-medium">
                    Filter
                </button>
                <a href="index.php?module=permasalahan_tindak_lanjut" class="px-5 py-3 rounded-2xl bg-slate-200 hover:bg-slate-300 text-slate-800 font-medium">
                    Reset
                </a>
            </div>
        </form>

        <div class="p-6 space-y-4">
            <?php if (empty($rows)): ?>
                <div class="rounded-2xl border border-dashed border-slate-300 p-10 text-center text-slate-500">
                    Belum ada data permasalahan.
                </div>
            <?php endif; ?>

            <?php foreach ($rows as $i => $row): ?>
                <?php
                    $statusClass = 'bg-red-100 text-red-700';
                    if (($row['status'] ?? '') === 'Proses') $statusClass = 'bg-amber-100 text-amber-700';
                    if (($row['status'] ?? '') === 'Selesai') $statusClass = 'bg-green-100 text-green-700';
                ?>
                <div class="rounded-3xl border border-slate-200 bg-slate-50 p-5 shadow-sm">
                    <div class="flex flex-col xl:flex-row xl:items-start xl:justify-between gap-4">
                        <div class="flex-1">
                            <div class="text-xs text-slate-500 mb-2">
                                #<?= $i + 1 ?> • Dibuat: <?= e($row['created_at_formatted'] ?? '-') ?> • Oleh: <?= e($row['created_by_name'] ?? '-') ?>
                            </div>

                            <h3 class="text-xl font-bold text-slate-800"><?= e($row['permasalahan'] ?? '') ?></h3>

                            <div class="mt-2 flex flex-wrap gap-2 text-sm">
                                <span class="inline-flex items-center px-3 py-1 rounded-full bg-blue-100 text-blue-700">
                                    Pelapor: <?= e($row['unit_pelapor'] ?? '-') ?>
                                </span>
                                <span class="inline-flex items-center px-3 py-1 rounded-full bg-purple-100 text-purple-700">
                                    Terkait: <?= e($row['unit_terkait'] ?? '-') ?>
                                </span>
                                <span class="inline-flex items-center px-3 py-1 rounded-full <?= $statusClass ?>">
                                    <?= e($row['status'] ?? '-') ?>
                                </span>
                            </div>
                        </div>

                        <div class="flex flex-wrap gap-2">
                            <?php if ($canEdit): ?>
                                <button
                                    type="button"
                                    class="btn-edit inline-flex items-center px-4 py-2 rounded-xl bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium"
                                    data-id="<?= (int)$row['id'] ?>"
                                    data-permasalahan="<?= e($row['permasalahan'] ?? '') ?>"
                                    data-detail_permasalahan="<?= e($row['detail_permasalahan'] ?? '') ?>"
                                    data-unit_pelapor="<?= e($row['unit_pelapor'] ?? '-') ?>"
                                    data-unit_terkait="<?= e($row['unit_terkait'] ?? '-') ?>"
                                    data-status="<?= e($row['status'] ?? '') ?>"
                                    data-tindak_lanjut="<?= e($row['tindak_lanjut'] ?? '') ?>"
                                    data-penyelesaian="<?= e($row['penyelesaian'] ?? '') ?>"
                                    data-masukan_kepala_divisi="<?= e($row['masukan_kepala_divisi'] ?? '') ?>"
                                    data-masukan_ptbdm="<?= e($row['masukan_ptbdm'] ?? '') ?>"
                                    data-tanggal_mulai="<?= e($row['tanggal_mulai'] ?? '') ?>"
                                    data-tanggal_target="<?= e($row['tanggal_target'] ?? '') ?>"
                                >
                                    Edit
                                </button>
                            <?php endif; ?>

                            <?php if ($canDelete): ?>
                                <form method="POST" onsubmit="return confirm('Yakin hapus data ini?');">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                                    <button type="submit" class="inline-flex items-center px-4 py-2 rounded-xl bg-red-600 hover:bg-red-700 text-white text-sm font-medium">
                                        Hapus
                                    </button>
                                </form>
                            <?php endif; ?>
                        </div>
                    </div>

                    <?php if (!empty($row['detail_permasalahan'])): ?>
                        <div class="mt-4 rounded-2xl bg-white border border-slate-200 p-4">
                            <div class="text-xs font-semibold text-slate-500 mb-2">Detail Permasalahan</div>
                            <div class="text-slate-700 whitespace-pre-line"><?= e($row['detail_permasalahan']) ?></div>
                        </div>
                    <?php endif; ?>

                    <div class="mt-4 grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div class="rounded-2xl bg-white border border-slate-200 p-4">
                            <div class="text-xs font-semibold text-slate-500 mb-2">Tanggal Mulai</div>
                            <div class="text-slate-800 font-medium"><?= e($row['tanggal_mulai'] ?? '-') ?></div>
                        </div>
                        <div class="rounded-2xl bg-white border border-slate-200 p-4">
                            <div class="text-xs font-semibold text-slate-500 mb-2">Tanggal Target</div>
                            <div class="text-slate-800 font-medium"><?= e($row['tanggal_target'] ?? '-') ?></div>
                        </div>
                        <div class="rounded-2xl bg-white border border-slate-200 p-4">
                            <div class="text-xs font-semibold text-slate-500 mb-2">Lama Penyelesaian</div>
                            <div class="text-slate-800 font-medium">
                                <?= $row['lama_penyelesaian_hari'] !== null ? ((int)$row['lama_penyelesaian_hari'] . ' hari') : '-' ?>
                            </div>
                        </div>
                    </div>

                    <?php if (!empty($row['tindak_lanjut'])): ?>
                        <div class="mt-4 rounded-2xl bg-white border border-slate-200 p-4">
                            <div class="text-xs font-semibold text-slate-500 mb-2">Tindak Lanjut</div>
                            <div class="text-slate-700 whitespace-pre-line"><?= e($row['tindak_lanjut']) ?></div>
                        </div>
                    <?php endif; ?>

                    <?php if (!empty($row['penyelesaian'])): ?>
                        <div class="mt-4 rounded-2xl bg-white border border-slate-200 p-4">
                            <div class="text-xs font-semibold text-slate-500 mb-2">Penyelesaian</div>
                            <div class="text-slate-700 whitespace-pre-line"><?= e($row['penyelesaian']) ?></div>
                        </div>
                    <?php endif; ?>

                    <div class="mt-4 grid grid-cols-1 lg:grid-cols-2 gap-4">
                        <div class="rounded-2xl bg-blue-50 border border-blue-100 p-4">
                            <div class="text-xs font-semibold text-blue-600 mb-2">Masukan Kepala Divisi</div>
                            <div class="text-slate-700 whitespace-pre-line"><?= e($row['masukan_kepala_divisi'] ?? '-') ?></div>
                        </div>
                        <div class="rounded-2xl bg-purple-50 border border-purple-100 p-4">
                            <div class="text-xs font-semibold text-purple-600 mb-2">Masukan PT BDM</div>
                            <div class="text-slate-700 whitespace-pre-line"><?= e($row['masukan_ptbdm'] ?? '-') ?></div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<?php if ($canCreate): ?>
<div id="createModal" class="fixed inset-0 bg-slate-900/60 hidden items-center justify-center z-50 p-4">
    <div class="bg-white w-full max-w-5xl rounded-3xl shadow-2xl max-h-[90vh] overflow-y-auto">
        <div class="sticky top-0 bg-white border-b border-slate-200 px-6 py-4 flex items-center justify-between rounded-t-3xl">
            <h3 class="text-xl font-bold text-slate-800">Tambah Permasalahan</h3>
            <button type="button" id="closeCreateModal" class="w-10 h-10 rounded-full bg-slate-100 hover:bg-slate-200 text-slate-700 text-xl">&times;</button>
        </div>

        <form method="POST" class="p-6 space-y-5">
            <input type="hidden" name="action" value="create">

            <div class="grid grid-cols-1 xl:grid-cols-2 gap-5">
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-2">Permasalahan <span class="text-red-500">*</span></label>
                    <input type="text" name="permasalahan" required class="w-full rounded-2xl border border-slate-300 px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Contoh: Keterlambatan pengiriman berkas rekam medis">
                </div>

                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-2">Status Awal</label>
                    <select name="status" class="w-full rounded-2xl border border-slate-300 px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <option value="Belum Selesai">Belum Selesai</option>
                        <option value="Proses">Proses</option>
                        <option value="Selesai">Selesai</option>
                    </select>
                </div>
            </div>

            <div>
                <label class="block text-sm font-medium text-slate-700 mb-2">Detail Permasalahan</label>
                <textarea name="detail_permasalahan" rows="4" class="w-full rounded-2xl border border-slate-300 px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Uraikan masalah secara ringkas namun jelas..."></textarea>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-2 gap-5">
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-2">Unit Pelapor <span class="text-red-500">*</span></label>
                    <select name="unit_pelapor_id" required class="w-full rounded-2xl border border-slate-300 px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <option value="">-- Pilih Unit Pelapor --</option>
                        <?php foreach ($units as $unit): ?>
                            <option value="<?= (int)$unit['id'] ?>" <?= $currentUserUnitId === (int)$unit['id'] ? 'selected' : '' ?>>
                                <?= e($unit['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-2">Unit Terkait</label>
                    <select name="unit_terkait_id" class="w-full rounded-2xl border border-slate-300 px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <option value="">-- Pilih Unit Terkait --</option>
                        <?php foreach ($units as $unit): ?>
                            <option value="<?= (int)$unit['id'] ?>"><?= e($unit['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-2 gap-5">
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-2">Tanggal Mulai</label>
                    <input type="date" name="tanggal_mulai" class="w-full rounded-2xl border border-slate-300 px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-2">Tanggal Target</label>
                    <input type="date" name="tanggal_target" class="w-full rounded-2xl border border-slate-300 px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>
            </div>

            <div>
                <label class="block text-sm font-medium text-slate-700 mb-2">Tindak Lanjut</label>
                <textarea name="tindak_lanjut" rows="3" class="w-full rounded-2xl border border-slate-300 px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Rencana tindak lanjut awal..."></textarea>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-2 gap-5">
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-2">Masukan Kepala Divisi</label>
                    <textarea name="masukan_kepala_divisi" rows="3" class="w-full rounded-2xl border border-slate-300 px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Masukan atau arahan kepala divisi..."></textarea>
                </div>
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-2">Masukan PT BDM</label>
                    <textarea name="masukan_ptbdm" rows="3" class="w-full rounded-2xl border border-slate-300 px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Masukan atau tindak lanjut dari PT BDM..."></textarea>
                </div>
            </div>

            <div>
                <label class="block text-sm font-medium text-slate-700 mb-2">Penyelesaian</label>
                <textarea name="penyelesaian" rows="3" class="w-full rounded-2xl border border-slate-300 px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Isi bila kasus langsung selesai pada saat input..."></textarea>
            </div>

            <div class="flex justify-end gap-3 pt-2">
                <button type="button" id="cancelCreateModal" class="px-5 py-3 rounded-2xl bg-slate-200 hover:bg-slate-300 text-slate-800 font-medium">Batal</button>
                <button type="submit" class="px-5 py-3 rounded-2xl bg-blue-600 hover:bg-blue-700 text-white font-semibold">Simpan Permasalahan</button>
            </div>
        </form>
    </div>
</div>
<?php endif; ?>

<?php if ($canEdit): ?>
<div id="editModal" class="fixed inset-0 bg-slate-900/60 hidden items-center justify-center z-50 p-4">
    <div class="bg-white w-full max-w-4xl rounded-3xl shadow-2xl max-h-[90vh] overflow-y-auto">
        <div class="sticky top-0 bg-white border-b border-slate-200 px-6 py-4 flex items-center justify-between rounded-t-3xl">
            <h3 class="text-xl font-bold text-slate-800">Edit Permasalahan</h3>
            <button type="button" id="closeModal" class="w-10 h-10 rounded-full bg-slate-100 hover:bg-slate-200 text-slate-700 text-xl">&times;</button>
        </div>

        <form method="POST" class="p-6 space-y-5">
            <input type="hidden" name="action" value="update">
            <input type="hidden" name="id" id="edit_id">

            <div>
                <label class="block text-sm font-medium text-slate-700 mb-2">Permasalahan</label>
                <input type="text" id="edit_permasalahan" class="w-full rounded-2xl border border-slate-300 px-4 py-3 bg-slate-100" readonly>
            </div>

            <div>
                <label class="block text-sm font-medium text-slate-700 mb-2">Detail Permasalahan</label>
                <textarea id="edit_detail_permasalahan" rows="4" class="w-full rounded-2xl border border-slate-300 px-4 py-3 bg-slate-100" readonly></textarea>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-2 gap-5">
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-2">Unit Pelapor</label>
                    <input type="text" id="edit_unit_pelapor" class="w-full rounded-2xl border border-slate-300 px-4 py-3 bg-slate-100" readonly>
                </div>
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-2">Unit Terkait</label>
                    <input type="text" id="edit_unit_terkait" class="w-full rounded-2xl border border-slate-300 px-4 py-3 bg-slate-100" readonly>
                </div>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-3 gap-5">
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-2">Status</label>
                    <select name="status" id="edit_status" class="w-full rounded-2xl border border-slate-300 px-4 py-3">
                        <option value="Belum Selesai">Belum Selesai</option>
                        <option value="Proses">Proses</option>
                        <option value="Selesai">Selesai</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-2">Tanggal Mulai</label>
                    <input type="date" name="tanggal_mulai" id="edit_tanggal_mulai" class="w-full rounded-2xl border border-slate-300 px-4 py-3">
                </div>
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-2">Tanggal Target</label>
                    <input type="date" name="tanggal_target" id="edit_tanggal_target" class="w-full rounded-2xl border border-slate-300 px-4 py-3">
                </div>
            </div>

            <div>
                <label class="block text-sm font-medium text-slate-700 mb-2">Tindak Lanjut</label>
                <textarea name="tindak_lanjut" id="edit_tindak_lanjut" rows="3" class="w-full rounded-2xl border border-slate-300 px-4 py-3"></textarea>
            </div>

            <div>
                <label class="block text-sm font-medium text-slate-700 mb-2">Penyelesaian</label>
                <textarea name="penyelesaian" id="edit_penyelesaian" rows="3" class="w-full rounded-2xl border border-slate-300 px-4 py-3"></textarea>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-2 gap-5">
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-2">Masukan Kepala Divisi</label>
                    <textarea name="masukan_kepala_divisi" id="edit_masukan_kepala_divisi" rows="3" class="w-full rounded-2xl border border-slate-300 px-4 py-3"></textarea>
                </div>
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-2">Masukan PT BDM</label>
                    <textarea name="masukan_ptbdm" id="edit_masukan_ptbdm" rows="3" class="w-full rounded-2xl border border-slate-300 px-4 py-3"></textarea>
                </div>
            </div>

            <div class="flex justify-end gap-3 pt-2">
                <button type="button" id="cancelModal" class="px-5 py-3 rounded-2xl bg-slate-200 hover:bg-slate-300 text-slate-800 font-medium">Batal</button>
                <button type="submit" class="px-5 py-3 rounded-2xl bg-blue-600 hover:bg-blue-700 text-white font-semibold">Simpan Update</button>
            </div>
        </form>
    </div>
</div>
<?php endif; ?>

<?php if ($playSound): ?>
<audio id="notifSound" preload="auto">
    <source src="https://actions.google.com/sounds/v1/alarms/alarm_clock.ogg" type="audio/ogg">
</audio>
<?php endif; ?>

<script>
(function () {
    const createModal = document.getElementById('createModal');
    const openCreateBtn = document.getElementById('openCreateModal');
    const closeCreateBtn = document.getElementById('closeCreateModal');
    const cancelCreateBtn = document.getElementById('cancelCreateModal');

    function openCreateModal() {
        if (!createModal) return;
        createModal.classList.remove('hidden');
        createModal.classList.add('flex');
        document.body.classList.add('overflow-hidden');
    }

    function closeCreateModal() {
        if (!createModal) return;
        createModal.classList.add('hidden');
        createModal.classList.remove('flex');
        document.body.classList.remove('overflow-hidden');
    }

    openCreateBtn?.addEventListener('click', openCreateModal);
    closeCreateBtn?.addEventListener('click', closeCreateModal);
    cancelCreateBtn?.addEventListener('click', closeCreateModal);

    createModal?.addEventListener('click', function (e) {
        if (e.target === createModal) {
            closeCreateModal();
        }
    });

    const modal = document.getElementById('editModal');
    const closeBtn = document.getElementById('closeModal');
    const cancelBtn = document.getElementById('cancelModal');

    function openModal() {
        if (!modal) return;
        modal.classList.remove('hidden');
        modal.classList.add('flex');
        document.body.classList.add('overflow-hidden');
    }

    function closeModal() {
        if (!modal) return;
        modal.classList.add('hidden');
        modal.classList.remove('flex');
        document.body.classList.remove('overflow-hidden');
    }

    document.querySelectorAll('.btn-edit').forEach(btn => {
        btn.addEventListener('click', function () {
            document.getElementById('edit_id').value = this.dataset.id || '';
            document.getElementById('edit_permasalahan').value = this.dataset.permasalahan || '';
            document.getElementById('edit_detail_permasalahan').value = this.dataset.detail_permasalahan || '';
            document.getElementById('edit_unit_pelapor').value = this.dataset.unit_pelapor || '';
            document.getElementById('edit_unit_terkait').value = this.dataset.unit_terkait || '';
            document.getElementById('edit_status').value = this.dataset.status || 'Belum Selesai';
            document.getElementById('edit_tindak_lanjut').value = this.dataset.tindak_lanjut || '';
            document.getElementById('edit_penyelesaian').value = this.dataset.penyelesaian || '';
            document.getElementById('edit_masukan_kepala_divisi').value = this.dataset.masukan_kepala_divisi || '';
            document.getElementById('edit_masukan_ptbdm').value = this.dataset.masukan_ptbdm || '';
            document.getElementById('edit_tanggal_mulai').value = this.dataset.tanggal_mulai || '';
            document.getElementById('edit_tanggal_target').value = this.dataset.tanggal_target || '';
            openModal();
        });
    });

    closeBtn?.addEventListener('click', closeModal);
    cancelBtn?.addEventListener('click', closeModal);

    modal?.addEventListener('click', function (e) {
        if (e.target === modal) {
            closeModal();
        }
    });

    const notifSound = document.getElementById('notifSound');
    if (notifSound) {
        notifSound.volume = 1.0;
        notifSound.play().catch(() => {});
        setTimeout(() => {
            notifSound.play().catch(() => {});
        }, 700);
    }
})();
</script>