<?php
include "../config/koneksi.php";
include "../middleware/auth.php";
include "../fuzzy/fuzzy_logic.php";
include "../config/komplain_workflow.php";

sikompro_require_role('admin');
$profileUser = komplain_user_profile($conn, (int) $_SESSION['user_id']);
$notifCount = komplain_notification_count($conn, 'admin');

$error = "";
$editId = isset($_GET['id']) ? (int) $_GET['id'] : 0;
$isEdit = $editId > 0;
$wilayahOptions = komplain_wilayah_options($conn);
$clusterMap = komplain_cluster_map($conn);
$pelaksanaOptions = mysqli_query($conn, "SELECT id, username FROM users WHERE role='pelaksana' ORDER BY username ASC");
$formData = [
    'wilayah_id'        => '',
    'wilayah_nama'      => '',
    'cluster_id'        => '',
    'cluster_nama'      => '',
    'lokasi_detail'     => '',
    'deskripsi_komplain'=> '',
    'kerusakan'         => '',
    'waktu'             => '',
    'foto_before'       => '',
    'pelaksana_id'      => '',
];
$oldPelaksanaId = 0;

if ($isEdit) {
    $editQuery = mysqli_query($conn, "SELECT * FROM komplain WHERE id = '{$editId}' LIMIT 1");
    $editData  = $editQuery ? mysqli_fetch_assoc($editQuery) : null;

    if (!$editData) {
        die("Data komplain tidak ditemukan.");
    }

    $formData = [
        'wilayah_id'        => komplain_row_value($editData, 'wilayah_id', ''),
        'wilayah_nama'      => '',
        'cluster_id'        => komplain_row_value($editData, 'cluster_id', ''),
        'cluster_nama'      => '',
        'lokasi_detail'     => komplain_row_value($editData, 'lokasi_detail', ''),
        'deskripsi_komplain'=> komplain_row_value($editData, 'deskripsi_komplain', ''),
        'kerusakan'         => komplain_row_value($editData, 'kerusakan', ''),
        'waktu'             => komplain_row_value($editData, 'waktu', ''),
        'foto_before'       => komplain_row_value($editData, 'foto_before', ''),
        'pelaksana_id'      => komplain_row_value($editData, 'pelaksana_id', ''),
    ];
    $oldPelaksanaId = (int) komplain_row_value($editData, 'pelaksana_id', 0);

    foreach ($wilayahOptions as $wilayah) {
        if ((string) $wilayah['id'] === (string) $formData['wilayah_id']) {
            $formData['wilayah_nama'] = $wilayah['nama'];
            break;
        }
    }

    foreach ($clusterMap[(int) $formData['wilayah_id']] ?? [] as $cluster) {
        if ((string) $cluster['id'] === (string) $formData['cluster_id']) {
            $formData['cluster_nama'] = $cluster['nama'];
            break;
        }
    }
}

// ── Hapus satu foto before (AJAX / GET request) ─────────────────────────────
if (isset($_GET['hapus_before']) && $isEdit) {
    $namaFile   = basename($_GET['hapus_before']);
    $currentQuery = mysqli_query($conn,
        "SELECT foto_before FROM komplain WHERE id = '{$editId}' LIMIT 1"
    );
    $currentRow = $currentQuery ? mysqli_fetch_assoc($currentQuery) : null;

    if (!$currentRow) {
        header("Location: input_komplain_admin.php?id={$editId}&msg=foto_tidak_ditemukan");
        exit;
    }

    $newJson    = komplain_remove_image($currentRow['foto_before'] ?? '', $namaFile);
    $newJsonSql = komplain_escape($conn, $newJson);

    mysqli_query($conn,
        "UPDATE komplain SET foto_before='{$newJsonSql}', tanggal_update=NOW() WHERE id='{$editId}'"
    );

    // Hapus file fisik
    $filePath = "../uploads/before/" . $namaFile;
    if (file_exists($filePath)) {
        unlink($filePath);
    }

    header("Location: input_komplain_admin.php?id={$editId}&msg=foto_dihapus");
    exit;
}

// ── Proses simpan/update ─────────────────────────────────────────────────────
if (isset($_POST['simpan'])) {
    $wilayahId       = (int) $_POST['wilayah_id'];
    $wilayahNamaInput= trim((string) $_POST['wilayah_nama']);
    $clusterId       = (int) $_POST['cluster_id'];
    $clusterNamaInput= trim((string) $_POST['cluster_nama']);
    $lokasiDetail    = trim($_POST['lokasi_detail']);
    $deskripsiKomplain = trim($_POST['deskripsi_komplain']);
    $kerusakan       = (int) $_POST['kerusakan'];
    $waktu           = (int) $_POST['waktu'];
    $tanggal         = date('Y-m-d');
    $prioritas       = fuzzy_prioritas($kerusakan, $waktu);
    $kategoriKerusakan = fuzzy_kategori_kerusakan($kerusakan);
    $adminId         = (int) $_SESSION['user_id'];
    $pelaksanaId     = (int) ($_POST['pelaksana_id'] ?? 0);
    $selectedWilayah = null;
    $selectedCluster = null;

    // Resolve wilayah
    if ($wilayahId > 0) {
        foreach ($wilayahOptions as $wilayah) {
            if ((int) $wilayah['id'] === $wilayahId) {
                $selectedWilayah = $wilayah;
                break;
            }
        }
    }
    if (!$selectedWilayah && $wilayahNamaInput !== '') {
        $selectedWilayah = komplain_find_or_create_wilayah($conn, $wilayahNamaInput);
        $wilayahId       = (int) $selectedWilayah['id'];
    }

    // Resolve cluster
    if ($clusterId > 0) {
        foreach ($clusterMap[$wilayahId] ?? [] as $cluster) {
            if ((int) $cluster['id'] === $clusterId) {
                $selectedCluster = $cluster;
                break;
            }
        }
    }
    if (!$selectedCluster && $clusterNamaInput !== '' && $wilayahId > 0) {
        $selectedCluster = komplain_find_or_create_cluster($conn, $wilayahId, $clusterNamaInput);
        $clusterId       = (int) $selectedCluster['id'];
    }

    // Cek apakah ada upload baru
    $folder    = "../uploads/before/";
    $hasUpload = !empty($_FILES['foto']['name']) && (
        is_array($_FILES['foto']['name'])
            ? count(array_filter($_FILES['foto']['name'])) > 0
            : $_FILES['foto']['name'] !== ''
    );

    // Validasi
    if (!$selectedWilayah) {
        $error = "Wilayah wajib dipilih.";
    } elseif (!$selectedCluster) {
        $error = "Cluster wajib dipilih.";
    } elseif ($deskripsiKomplain === "") {
        $error = "Keterangan komplain wajib diisi.";
    } elseif ($kerusakan < 1 || $kerusakan > 100) {
        $error = "Nilai kerusakan harus antara 1 – 100.";
    } elseif ($waktu < 1) {
        $error = "Tenggat waktu minimal 1 hari.";
    } elseif ($pelaksanaId <= 0) {
        $error = "Pelaksana wajib dipilih sebelum simpan komplain.";
    } elseif (!$isEdit && !$hasUpload) {
        $error = "Foto before wajib diupload minimal 1 foto.";
    } else {
        $lokasi        = komplain_format_lokasi($selectedWilayah['nama'], $selectedCluster['nama'], $lokasiDetail);
        $lokasiSql     = komplain_escape($conn, $lokasi);
        $lokasiDetailSql = komplain_escape($conn, $lokasiDetail);
        $deskripsiSql  = komplain_escape($conn, $deskripsiKomplain);
        $kategoriSql   = komplain_escape($conn, $kategoriKerusakan);
        $fotoToSave    = $formData['foto_before'];

        if ($hasUpload) {
            if (!is_dir($folder)) {
                mkdir($folder, 0755, true);
            }
            $uploadedBefore = komplain_upload_multiple_images('foto', $folder, 'before');

            if (empty($uploadedBefore)) {
                $error = "Upload foto before gagal. Pastikan format JPG/PNG/WEBP, maks 10MB/foto.";
            } else {
                $fotoToSave = $isEdit
                    ? komplain_merge_images($formData['foto_before'], $uploadedBefore)
                    : komplain_images_to_json($uploadedBefore);
            }
        }

        if ($error === "") {
            $fotoSql = komplain_escape($conn, $fotoToSave);

            if ($isEdit) {
                $query = "UPDATE komplain SET
                    wilayah_id        = '{$wilayahId}',
                    cluster_id        = '{$clusterId}',
                    lokasi            = '{$lokasiSql}',
                    lokasi_detail     = '{$lokasiDetailSql}',
                    deskripsi_komplain= '{$deskripsiSql}',
                    kerusakan         = '{$kerusakan}',
                    kategori_kerusakan= '{$kategoriSql}',
                    waktu             = '{$waktu}',
                    prioritas         = '{$prioritas}',
                    foto_before       = '{$fotoSql}',
                    pelaksana_id      = '{$pelaksanaId}',
                    tanggal_update    = NOW()
                    WHERE id = '{$editId}'";
            } else {
                $query = "INSERT INTO komplain
                    (admin_id, pelaksana_id, wilayah_id, cluster_id, lokasi, lokasi_detail,
                     deskripsi_komplain, kerusakan, kategori_kerusakan, waktu,
                     prioritas, status, foto_before, tanggal, tanggal_update)
                    VALUES
                    ('{$adminId}','{$pelaksanaId}','{$wilayahId}','{$clusterId}','{$lokasiSql}','{$lokasiDetailSql}',
                     '{$deskripsiSql}','{$kerusakan}','{$kategoriSql}','{$waktu}',
                     '{$prioritas}','pending_pelaksana','{$fotoSql}','{$tanggal}',NOW())";
            }

            if (mysqli_query($conn, $query)) {
                if (!$isEdit && $pelaksanaId > 0) {
                    $notifLokasi = $lokasi !== '' ? $lokasi : 'komplain baru';
                    komplain_notify(
                        $conn,
                        'pelaksana',
                        'Komplain baru masuk',
                        "Ada komplain baru untuk Anda di lokasi {$notifLokasi}.",
                        $isEdit ? $editId : mysqli_insert_id($conn)
                    );
                } elseif ($isEdit && $pelaksanaId > 0 && $pelaksanaId !== $oldPelaksanaId) {
                    komplain_notify(
                        $conn,
                        'pelaksana',
                        'Komplain diperbarui',
                        "Ada pembaruan komplain yang ditugaskan ke Anda. Silakan buka daftar komplain.",
                        $editId
                    );
                }

                $target = $isEdit ? 'total' : 'pending';
                echo "<script>alert('Komplain berhasil disimpan!');window.location='data_komplain.php?filter={$target}';</script>";
                exit;
            }

            $error = "Gagal menyimpan data komplain: " . mysqli_error($conn);
        }
    }

    // Kembalikan formData setelah error
    $formData = [
        'wilayah_id'        => $wilayahId,
        'wilayah_nama'      => $selectedWilayah['nama'] ?? $wilayahNamaInput,
        'cluster_id'        => $clusterId,
        'cluster_nama'      => $selectedCluster['nama'] ?? $clusterNamaInput,
        'lokasi_detail'     => $lokasiDetail,
        'deskripsi_komplain'=> $deskripsiKomplain,
        'kerusakan'         => $kerusakan,
        'waktu'             => $waktu,
        'foto_before'       => $formData['foto_before'],
        'pelaksana_id'      => $pelaksanaId,
    ];
}

// Foto before yang sudah tersimpan (untuk mode edit)
$existingPhotos = komplain_image_files($formData['foto_before']);
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= $isEdit ? 'Edit Komplain' : 'Input Komplain' ?> | PT. ALVINDO</title>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/css/adminlte.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" integrity="sha384-sRIl4kxILFvY47J16cr9ZwB07vP4J8+LH7qKQnuqkuIAvNWLzeN8tE5YBujZqJLB" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="../assets/sikompro-ux.css?v=20260722.11">

<style>
/* ── Base ──────────────────────────────────────────── */
body {
    background: linear-gradient(160deg, #eef5ff 0%, #f5f8ff 60%, #eaf3f0 100%);
    min-height: 100vh;
    font-family: 'Segoe UI', sans-serif;
}

/* ── Sidebar ───────────────────────────────────────── */
.main-sidebar {
    background: linear-gradient(180deg, #1a2c45 0%, #162236 100%);
}
.brand-link {
    border-bottom: 1px solid rgba(255,255,255,.08) !important;
    background: rgba(0,0,0,.15) !important;
    letter-spacing: 2px;
    font-weight: 800;
    font-size: 1rem;
    color: #fff !important;
}
.sidebar-profile {
    text-align: center;
    padding: 18px 10px 14px;
    border-bottom: 1px solid rgba(255,255,255,.1);
}
.sidebar-profile img {
    width: 74px; height: 74px;
    object-fit: cover;
    border-radius: 50%;
    border: 3px solid rgba(255,255,255,.4);
    box-shadow: 0 4px 14px rgba(0,0,0,.3);
}
.sidebar-profile .sp-name {
    color: #fff;
    font-weight: 700;
    font-size: .9rem;
    margin-top: 8px;
}
.sidebar-profile .sp-role {
    color: rgba(255,255,255,.55);
    font-size: .75rem;
}
.nav-sidebar .nav-link {
    border-radius: 10px;
    margin: 2px 8px;
    transition: background .2s;
}
.nav-sidebar .nav-link:hover,
.nav-sidebar .nav-link.active {
    background: rgba(255,255,255,.12) !important;
}

/* ── Hero banner ───────────────────────────────────── */
.form-hero {
    background: linear-gradient(135deg, #15304e 0%, #1f5a8c 60%, #1a7a6e 100%);
    color: #fff;
    border-radius: 22px;
    padding: 30px 32px;
    margin-bottom: 28px;
    box-shadow: 0 20px 50px rgba(15,40,70,.22);
    position: relative;
    overflow: hidden;
}
.form-hero::before {
    content: '';
    position: absolute;
    width: 260px; height: 260px;
    background: rgba(255,255,255,.05);
    border-radius: 50%;
    top: -80px; right: -60px;
}
.form-hero::after {
    content: '';
    position: absolute;
    width: 160px; height: 160px;
    background: rgba(255,255,255,.04);
    border-radius: 50%;
    bottom: -50px; right: 120px;
}
.form-hero h3 { font-weight: 800; font-size: 1.55rem; margin-bottom: 6px; }
.form-hero p  { opacity: .78; font-size: .9rem; margin: 0; }

/* ── Cards ─────────────────────────────────────────── */
.card {
    border: 0;
    border-radius: 20px;
    box-shadow: 0 10px 36px rgba(20,40,80,.08);
    overflow: hidden;
}
.card-header {
    background: #fff;
    border-bottom: 1px solid #edf2f8;
    padding: 16px 22px;
}
.card-header .card-title {
    font-weight: 700;
    font-size: .95rem;
    color: #1a2c45;
    margin: 0;
}

/* ── Form controls ──────────────────────────────────── */
.form-control {
    border-radius: 12px;
    border: 1.5px solid #d8e3f0;
    padding: 10px 14px;
    font-size: .9rem;
    transition: border-color .2s, box-shadow .2s;
}
.form-control:focus {
    border-color: #3b82f6;
    box-shadow: 0 0 0 3px rgba(59,130,246,.12);
}
label {
    font-weight: 600;
    font-size: .82rem;
    color: #4a5568;
    margin-bottom: 5px;
    display: block;
}

/* ── Fuzzy badge ────────────────────────────────────── */
#fuzzy-result {
    display: inline-block;
    padding: 6px 16px;
    border-radius: 50px;
    font-weight: 700;
    font-size: .82rem;
    letter-spacing: .4px;
    margin-top: 8px;
    transition: all .3s;
}
.fuzzy-ringan  { background: #d1fae5; color: #065f46; }
.fuzzy-sedang  { background: #fef3c7; color: #92400e; }
.fuzzy-parah   { background: #fee2e2; color: #991b1b; }
.fuzzy-empty   { background: #f1f5f9; color: #94a3b8; }

/* ── Foto upload area ───────────────────────────────── */
.upload-zone {
    border: 2.5px dashed #b5cce4;
    border-radius: 16px;
    background: #f8fbff;
    padding: 22px 18px;
    text-align: center;
    cursor: pointer;
    transition: border-color .2s, background .2s;
    position: relative;
}
.upload-zone:hover,
.upload-zone.drag-over {
    border-color: #3b82f6;
    background: #eff6ff;
}
.upload-zone input[type="file"] {
    display: block;
    width: 100%;
    margin-top: 12px;
    padding: 12px;
    border-radius: 12px;
    border: 1px solid #cbd5e1;
    background: #fff;
    cursor: pointer;
}
.upload-zone .uz-icon {
    font-size: 2.2rem;
    color: #93c5fd;
    margin-bottom: 8px;
}
.upload-zone .uz-text {
    font-size: .88rem;
    color: #64748b;
    font-weight: 600;
}
.upload-zone .uz-sub {
    font-size: .76rem;
    color: #94a3b8;
    margin-top: 2px;
}

/* ── Foto preview grid ──────────────────────────────── */
.foto-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-top: 14px;
}
.foto-card {
    position: relative;
    width: 100px;
    height: 80px;
    border-radius: 12px;
    overflow: visible;
    flex-shrink: 0;
}
.foto-card img {
    width: 100px;
    height: 80px;
    object-fit: cover;
    border-radius: 12px;
    border: 2px solid #e2e8f0;
    display: block;
    transition: transform .2s;
}
.foto-card img:hover { transform: scale(1.04); }
.foto-card .fc-del {
    position: absolute;
    top: -7px; right: -7px;
    width: 22px; height: 22px;
    background: #ef4444;
    color: #fff;
    border: 2px solid #fff;
    border-radius: 50%;
    font-size: 11px;
    display: flex;
    align-items: center;
    justify-content: center;
    text-decoration: none;
    cursor: pointer;
    transition: background .2s;
    z-index: 5;
}
.foto-card .fc-del:hover { background: #b91c1c; }
.foto-card .fc-badge {
    position: absolute;
    bottom: -8px; left: 50%;
    transform: translateX(-50%);
    background: rgba(15,40,70,.75);
    color: #fff;
    font-size: 9px;
    padding: 1px 7px;
    border-radius: 20px;
    white-space: nowrap;
    max-width: 96px;
    overflow: hidden;
    text-overflow: ellipsis;
}
.foto-counter {
    font-size: .78rem;
    font-weight: 700;
    color: #3b82f6;
    margin-top: 10px;
}

/* ── Section label ──────────────────────────────────── */
.section-label {
    font-size: .75rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: .6px;
    color: #94a3b8;
    margin-bottom: 8px;
}

/* ── Divider ────────────────────────────────────────── */
.form-divider {
    border: 0;
    height: 1.5px;
    background: linear-gradient(90deg, transparent, #e2e8f0, transparent);
    margin: 24px 0;
}

/* ── Buttons ────────────────────────────────────────── */
.btn { border-radius: 12px; font-weight: 600; font-size: .88rem; }
.btn-primary {
    background: linear-gradient(135deg, #2563eb, #1d4ed8);
    border: 0;
    box-shadow: 0 4px 14px rgba(37,99,235,.3);
}
.btn-primary:hover {
    background: linear-gradient(135deg, #1d4ed8, #1e40af);
    box-shadow: 0 6px 18px rgba(37,99,235,.4);
}
.btn-outline-secondary { border-color: #cbd5e1; color: #64748b; }
.btn-outline-secondary:hover { background: #f8fafc; }

/* ── Tips box ───────────────────────────────────────── */
.tips-box {
    background: #f8fbff;
    border: 1.5px dashed #b5cae4;
    border-radius: 16px;
    padding: 18px;
    font-size: .85rem;
}
.tips-box p { margin-bottom: 10px; color: #475569; }
.tips-box p:last-child { margin-bottom: 0; }
.tips-box b { color: #1e40af; }

/* ── Alert ──────────────────────────────────────────── */
.alert { border-radius: 14px; border: 0; font-size: .88rem; }
.alert-danger  { background: #fef2f2; color: #991b1b; }
.alert-success { background: #f0fdf4; color: #166534; }
.alert-info    { background: #eff6ff; color: #1e40af; }

/* ── Existing foto label ────────────────────────────── */
.existing-label {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 12px;
}
.existing-count-badge {
    background: #dbeafe;
    color: #1d4ed8;
    font-size: .72rem;
    font-weight: 700;
    padding: 3px 10px;
    border-radius: 20px;
}

/* ── Responsive ─────────────────────────────────────── */
@media (max-width: 576px) {
    .form-hero { padding: 20px; border-radius: 16px; }
    .foto-card { width: 80px; height: 64px; }
    .foto-card img { width: 80px; height: 64px; }
    .upload-zone { padding: 16px 14px; }
    .upload-zone .uz-icon { font-size: 1.8rem; }
    .upload-zone .uz-text { font-size: .84rem; }
}
</style>
</head>

<body class="hold-transition sidebar-mini layout-fixed dashboard-shell">
<div class="wrapper">

<!-- ── Navbar ──────────────────────────────────────────────────────────── -->
<nav class="main-header navbar navbar-expand navbar-white navbar-light">
    <ul class="navbar-nav">
        <li class="nav-item">
            <a class="nav-link" data-widget="pushmenu" href="#"><i class="fas fa-bars"></i></a>
        </li>
    </ul>
    <ul class="navbar-nav ml-auto mr-2">
        <li class="nav-item d-flex align-items-center">
            <span class="text-muted small mr-2"><?= htmlspecialchars($profileUser['username']) ?></span>
            <img src="<?= komplain_profile_photo_url($profileUser) ?>"
                 style="width:32px;height:32px;border-radius:50%;object-fit:cover;border:2px solid #cbd5e1;">
        </li>
    </ul>
</nav>

<!-- ── Sidebar ─────────────────────────────────────────────────────────── -->
<aside class="main-sidebar sidebar-dark-primary elevation-4">
    <a href="dashboard.php" class="brand-link text-center">
        <span class="brand-text">⚙ PT. ALVINDO</span>
    </a>
    <div class="sidebar">
        <div class="sidebar-profile">
            <img src="<?= komplain_profile_photo_url($profileUser) ?>" alt="Foto profil">
            <div class="sp-name"><?= htmlspecialchars($profileUser['username']) ?></div>
            <div class="sp-role"><?= htmlspecialchars(ucfirst($profileUser['role'])) ?></div>
        </div>
        <nav class="mt-2">
            <ul class="nav nav-pills nav-sidebar flex-column">
                <li class="nav-item">
                    <a href="dashboard.php" class="nav-link">
                        <i class="nav-icon fas fa-home"></i><p>Dashboard</p>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="data_komplain.php?filter=total" class="nav-link">
                        <i class="nav-icon fas fa-table"></i><p>Data Komplain</p>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="absen.php" class="nav-link">
                        <i class="nav-icon fas fa-user-check"></i><p>Absen Saya</p>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="data_absensi.php" class="nav-link">
                        <i class="nav-icon fas fa-users"></i><p>Data Absensi</p>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="gaji.php" class="nav-link">
                        <i class="nav-icon fas fa-money-bill-wave"></i><p>Gaji</p>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="users.php" class="nav-link">
                        <i class="nav-icon fas fa-user-cog"></i><p>Akses User</p>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="profil.php" class="nav-link">
                        <i class="nav-icon fas fa-user-circle"></i><p>Profil Pengguna</p>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="notif.php" class="nav-link">
                        <i class="nav-icon fas fa-bell"></i><p>Notifikasi <span class="badge badge-warning float-right"><?= $notifCount ?></span></p>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="input_komplain_admin.php" class="nav-link active">
                        <i class="nav-icon fas fa-plus"></i><p>Input Komplain</p>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="cetak_pdf.php" class="nav-link">
                        <i class="nav-icon fas fa-print"></i><p>Cetak PDF</p>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="gaji.php" class="nav-link">
                        <i class="nav-icon fas fa-money-bill-wave"></i><p>Gaji</p>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="../middleware/logout.php" class="nav-link">
                        <i class="nav-icon fas fa-sign-out-alt"></i><p>Logout</p>
                    </a>
                </li>
            </ul>
        </nav>
    </div>
</aside>

<!-- ── Content ─────────────────────────────────────────────────────────── -->
<div class="content-wrapper">
<section class="content pt-3 pb-5">
<div class="container-fluid">

    <!-- Hero -->
    <div class="form-hero">
        <h3><?= $isEdit ? '<i class="fas fa-edit mr-2"></i>Edit Komplain' : '<i class="fas fa-plus-circle mr-2"></i>Input Komplain Baru' ?></h3>
        <p>Input admin mencatat wilayah, cluster, keterangan komplain, skor fuzzy, dan foto before. Data ini akan terbawa ke pelaksana saat penugasan.</p>
    </div>

    <!-- Alert notifikasi hapus foto -->
    <?php if (isset($_GET['msg']) && $_GET['msg'] === 'foto_dihapus'): ?>
    <div class="alert alert-info mb-3">
        <i class="fas fa-check-circle mr-2"></i> Foto berhasil dihapus dari daftar.
    </div>
    <?php endif; ?>

    <div class="row">

        <!-- ── Kolom kiri: Form utama ─────────────────────────── -->
        <div class="col-lg-8">
            <div class="card mb-4">
                <div class="card-header">
                    <h3 class="card-title">
                        <i class="fas fa-file-alt mr-2 text-primary"></i>Form Komplain
                    </h3>
                </div>
                <div class="card-body p-4">

                    <?php if ($error !== ""): ?>
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-circle mr-2"></i><?= htmlspecialchars($error) ?>
                    </div>
                    <?php endif; ?>

                    <form method="POST" enctype="multipart/form-data" id="form-komplain">

                        <!-- ── Wilayah & Cluster ────────────────────────── -->
                        <div class="section-label"><i class="fas fa-map-marker-alt mr-1"></i>Lokasi</div>

                        <div class="form-row">
                            <div class="form-group col-md-6">
                                <label>Wilayah <span class="text-danger">*</span></label>
                                <input type="text" name="wilayah_nama" id="wilayah_nama"
                                       list="wilayah_list" class="form-control"
                                       placeholder="Ketik atau pilih wilayah"
                                       value="<?= htmlspecialchars($formData['wilayah_nama']) ?>"
                                       autocomplete="off" required>
                                <input type="hidden" name="wilayah_id" id="wilayah_id"
                                       value="<?= htmlspecialchars((string) $formData['wilayah_id']) ?>">
                                <datalist id="wilayah_list">
                                    <?php foreach ($wilayahOptions as $wilayah): ?>
                                    <option value="<?= htmlspecialchars($wilayah['nama']) ?>"
                                            data-id="<?= $wilayah['id'] ?>"></option>
                                    <?php endforeach; ?>
                                </datalist>
                            </div>
                            <div class="form-group col-md-6">
                                <label>Cluster <span class="text-danger">*</span></label>
                                <input type="text" name="cluster_nama" id="cluster_nama"
                                       list="cluster_list" class="form-control"
                                       placeholder="Ketik atau pilih cluster"
                                       value="<?= htmlspecialchars($formData['cluster_nama']) ?>"
                                       autocomplete="off" required>
                                <input type="hidden" name="cluster_id" id="cluster_id"
                                       value="<?= htmlspecialchars((string) $formData['cluster_id']) ?>"
                                       data-selected="<?= htmlspecialchars((string) $formData['cluster_id']) ?>">
                                <datalist id="cluster_list"></datalist>
                            </div>
                        </div>

                        <div class="form-group">
                            <label>Detail Lokasi <small class="text-muted font-weight-normal">(opsional)</small></label>
                            <input type="text" name="lokasi_detail" class="form-control"
                                   placeholder="Contoh: Blok A5, dekat gerbang utama"
                                   value="<?= htmlspecialchars($formData['lokasi_detail']) ?>">
                        </div>

                        <hr class="form-divider">

                        <!-- ── Deskripsi ────────────────────────────────── -->
                        <div class="section-label"><i class="fas fa-comment-alt mr-1"></i>Detail Komplain</div>

                        <div class="form-group">
                            <label>Keterangan Komplain <span class="text-danger">*</span></label>
                            <textarea name="deskripsi_komplain" class="form-control" rows="4"
                                      placeholder="Jelaskan kerusakan yang dilaporkan secara rinci..."
                                      required><?= htmlspecialchars($formData['deskripsi_komplain']) ?></textarea>
                        </div>

                        <hr class="form-divider">

                        <!-- ── Skor Fuzzy ───────────────────────────────── -->
                        <div class="section-label"><i class="fas fa-sliders-h mr-1"></i>Penilaian Fuzzy</div>

                        <div class="form-row">
                            <div class="form-group col-md-6">
                                <label>Nilai Kerusakan <span class="text-danger">*</span>
                                    <small class="text-muted font-weight-normal">(1 – 100)</small>
                                </label>
                                <input type="number" name="kerusakan" id="inp-kerusakan"
                                       min="1" max="100" class="form-control"
                                       placeholder="Misal: 75"
                                       value="<?= htmlspecialchars((string) $formData['kerusakan']) ?>"
                                       required>
                            </div>
                            <div class="form-group col-md-6">
                                <label>Tenggat Waktu / Urgensi <span class="text-danger">*</span>
                                    <small class="text-muted font-weight-normal">(hari)</small>
                                </label>
                                <input type="number" name="waktu" id="inp-waktu"
                                       min="1" class="form-control"
                                       placeholder="Misal: 7"
                                       value="<?= htmlspecialchars((string) $formData['waktu']) ?>"
                                       required>
                            </div>
                        </div>

                        <div id="fuzzy-result" class="fuzzy-empty">
                            <i class="fas fa-robot mr-1"></i>
                            <span id="fuzzy-text">Isi nilai kerusakan &amp; waktu untuk melihat prioritas</span>
                        </div>

                        <hr class="form-divider">

                        <div class="section-label"><i class="fas fa-user-tie mr-1"></i>Kirim ke Pelaksana</div>
                        <div class="form-group">
                            <label>Pilih Pelaksana <span class="text-danger">*</span></label>
                            <select name="pelaksana_id" class="form-control" required>
                                <option value="">-- Pilih pelaksana tujuan --</option>
                                <?php mysqli_data_seek($pelaksanaOptions, 0); while($p = mysqli_fetch_assoc($pelaksanaOptions)): ?>
                                <option value="<?= (int) $p['id'] ?>" <?= (string)$formData['pelaksana_id'] === (string)$p['id'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($p['username']) ?>
                                </option>
                                <?php endwhile; ?>
                            </select>
                        </div>

                        <hr class="form-divider">

                        <!-- ── Upload Foto Before ──────────────────────── -->
                        <div class="section-label">
                            <i class="fas fa-camera mr-1"></i>Foto Before
                            <?php if (!$isEdit): ?>
                            <span class="text-danger">*</span>
                            <?php endif; ?>
                            <small class="text-muted font-weight-normal ml-1">— bisa pilih banyak sekaligus</small>
                        </div>

                        <?php if ($isEdit && !empty($existingPhotos)): ?>
                        <!-- Foto tersimpan (mode edit) -->
                        <div class="existing-label">
                            <span class="section-label mb-0">Foto Tersimpan</span>
                            <span class="existing-count-badge"><?= count($existingPhotos) ?> foto</span>
                        </div>
                        <div class="foto-grid mb-4" id="existing-foto-grid">
                            <?php foreach ($existingPhotos as $fotoFile): ?>
                            <div class="foto-card">
                                <a href="../uploads/before/<?= htmlspecialchars($fotoFile) ?>"
                                   target="_blank">
                                    <img src="../uploads/before/<?= htmlspecialchars($fotoFile) ?>"
                                         alt="<?= htmlspecialchars($fotoFile) ?>"
                                         title="Klik untuk lihat penuh">
                                </a>
                                <a href="input_komplain_admin.php?id=<?= $editId ?>&hapus_before=<?= urlencode($fotoFile) ?>"
                                   class="fc-del"
                                   title="Hapus foto ini"
                                   onclick="return confirm('Yakin hapus foto ini dari daftar?')">
                                    <i class="fas fa-times"></i>
                                </a>
                                <span class="fc-badge"><?= htmlspecialchars($fotoFile) ?></span>
                            </div>
                            <?php endforeach; ?>
                        </div>

                        <div class="section-label mb-2">Tambah Foto Baru (opsional)</div>
                        <?php endif; ?>

                        <!-- Upload zone -->
                        <div class="upload-zone" id="upload-zone-before">
                            <input type="file" name="foto[]" id="foto-before-input"
                                   accept="image/*"
                                   multiple <?= (!$isEdit) ? 'required' : '' ?>>
                            <div class="uz-icon"><i class="fas fa-cloud-upload-alt"></i></div>
                            <div class="uz-text">Tap untuk pilih foto dari kamera atau galeri</div>
                            <div class="uz-sub">Format JPG, PNG, WEBP. Bisa pilih banyak sekaligus dari HP.</div>
                        </div>

                        <!-- Preview foto baru yang dipilih -->
                        <div class="foto-grid" id="preview-before"></div>
                        <div class="foto-counter" id="counter-before" style="display:none;">
                            <i class="fas fa-images mr-1"></i><span id="counter-num">0</span> foto dipilih
                        </div>

                        <hr class="form-divider">

                        <!-- ── Tombol ───────────────────────────────────── -->
                        <div class="d-flex justify-content-between flex-wrap" style="gap:10px;">
                            <a href="data_komplain.php?filter=total" class="btn btn-outline-secondary">
                                <i class="fas fa-arrow-left mr-1"></i> Lihat Data Komplain
                            </a>
                            <button type="submit" name="simpan" class="btn btn-primary px-4">
                                <i class="fas fa-save mr-1"></i>
                                <?= $isEdit ? 'Update Komplain' : 'Simpan Komplain' ?>
                            </button>
                        </div>

                    </form>
                </div>
            </div>
        </div>

        <!-- ── Kolom kanan: Panduan ────────────────────────────── -->
        <div class="col-lg-4">

            <!-- Panduan -->
            <div class="card mb-4">
                <div class="card-header">
                    <h3 class="card-title">
                        <i class="fas fa-info-circle mr-2 text-info"></i>Panduan Singkat
                    </h3>
                </div>
                <div class="card-body p-3">
                    <div class="tips-box">
                        <p><b>Status awal:</b> data otomatis masuk ke
                            <span class="badge badge-warning text-dark">Pending</span> menunggu penugasan pelaksana.</p>
                        <p><b>Skor Kerusakan (1-100):</b><br>
                            🟢 1–33 → Ringan<br>
                            🟡 34–66 → Sedang<br>
                            🔴 67–100 → Parah</p>
                        <p><b>Tenggat Waktu:</b> semakin kecil angka hari, semakin tinggi urgensi perbaikan.</p>
                        <p><b>Foto Before:</b> bisa upload 1 foto atau lebih sekaligus. Foto lama tidak terhapus saat update.</p>
                        <p class="mb-0"><b>Lokasi:</b> tersusun per wilayah → cluster → detail, agar data tidak tercecer.</p>
                    </div>
                </div>
            </div>

            <!-- Ringkasan fuzzy realtime -->
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">
                        <i class="fas fa-chart-bar mr-2 text-warning"></i>Kalkulasi Prioritas
                    </h3>
                </div>
                <div class="card-body p-3">
                    <table class="table table-sm table-borderless mb-0" style="font-size:.85rem;">
                        <tr>
                            <td class="text-muted pl-0">Nilai Kerusakan</td>
                            <td class="font-weight-bold" id="disp-kerusakan">—</td>
                        </tr>
                        <tr>
                            <td class="text-muted pl-0">Tenggat (hari)</td>
                            <td class="font-weight-bold" id="disp-waktu">—</td>
                        </tr>
                        <tr>
                            <td class="text-muted pl-0">Kategori</td>
                            <td class="font-weight-bold" id="disp-kategori">—</td>
                        </tr>
                        <tr>
                            <td class="text-muted pl-0">Prioritas</td>
                            <td class="font-weight-bold" id="disp-prioritas">—</td>
                        </tr>
                    </table>
                </div>
            </div>

        </div>
    </div>

</div>
</section>
</div>

</div><!-- .wrapper -->

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/js/bootstrap.bundle.min.js" integrity="sha384-FKyoEForCGlyvwx9Hj09JcYn3nv7wiPVlz7YYwJrWVcXK/BmnVDxM+D2scQbITxI" crossorigin="anonymous"></script>
<script src="../assets/bootstrap5-compat.js"></script>
<script src="../assets/sikompro-theme.js?v=20260722.11"></script>
<script>
/* ──────────────────────────────────────────────────────────────────────────
   Data dari PHP
   ────────────────────────────────────────────────────────────────────────── */
const wilayahOptions = <?= json_encode($wilayahOptions, JSON_UNESCAPED_UNICODE) ?>;
const clusterMap     = <?= json_encode($clusterMap, JSON_UNESCAPED_UNICODE) ?>;

/* ──────────────────────────────────────────────────────────────────────────
   Wilayah & Cluster datalist logic
   ────────────────────────────────────────────────────────────────────────── */
const wilayahInput   = document.getElementById('wilayah_nama');
const wilayahIdInput = document.getElementById('wilayah_id');
const clusterInput   = document.getElementById('cluster_nama');
const clusterIdInput = document.getElementById('cluster_id');
const clusterList    = document.getElementById('cluster_list');

function findWilayahIdByName(name) {
    const item = wilayahOptions.find(
        o => o.nama.toLowerCase() === String(name).trim().toLowerCase()
    );
    return item ? item.id : '';
}

function renderClusters(wilayahId) {
    const items = clusterMap[wilayahId] || [];
    const selectedClusterId = clusterIdInput.dataset.selected || clusterIdInput.value || '';
    clusterList.innerHTML = '';

    items.forEach(item => {
        const opt = document.createElement('option');
        opt.value = item.nama;
        opt.dataset.id = item.id;
        clusterList.appendChild(opt);

        if (String(item.id) === String(selectedClusterId) && !clusterInput.value) {
            clusterInput.value   = item.nama;
            clusterIdInput.value = item.id;
        }
    });
}

function syncClusterId() {
    const items   = clusterMap[wilayahIdInput.value] || [];
    const current = items.find(
        item => item.nama.toLowerCase() === String(clusterInput.value).trim().toLowerCase()
    );
    clusterIdInput.value = current ? current.id : '';
}

wilayahInput.addEventListener('input', () => {
    wilayahIdInput.value          = findWilayahIdByName(wilayahInput.value);
    clusterInput.value            = '';
    clusterIdInput.value          = '';
    clusterIdInput.dataset.selected = '';
    renderClusters(wilayahIdInput.value);
});

clusterInput.addEventListener('input', syncClusterId);

if (wilayahInput.value) {
    if (!wilayahIdInput.value) {
        wilayahIdInput.value = findWilayahIdByName(wilayahInput.value);
    }
    renderClusters(wilayahIdInput.value);
    syncClusterId();
}

/* ──────────────────────────────────────────────────────────────────────────
   Fuzzy realtime preview (client-side estimasi)
   ────────────────────────────────────────────────────────────────────────── */
const inpKerusakan  = document.getElementById('inp-kerusakan');
const inpWaktu      = document.getElementById('inp-waktu');
const fuzzyResult   = document.getElementById('fuzzy-result');
const fuzzyText     = document.getElementById('fuzzy-text');
const dispKerusakan = document.getElementById('disp-kerusakan');
const dispWaktu     = document.getElementById('disp-waktu');
const dispKategori  = document.getElementById('disp-kategori');
const dispPrioritas = document.getElementById('disp-prioritas');

function getKategori(k) {
    if (k <= 33) return 'Ringan';
    if (k <= 66) return 'Sedang';
    return 'Parah';
}

function getPrioritas(k, w) {
    // Estimasi sederhana — sesuaikan dengan fungsi fuzzy_prioritas() PHP Anda
    const normK = k / 100;          // 0-1 (makin tinggi makin parah)
    const normW = 1 - Math.min(w, 30) / 30; // 0-1 (makin kecil waktu makin urgent)
    const score = (normK * 0.6 + normW * 0.4) * 100;

    if (score >= 70) return { label: 'Tinggi',  cls: 'fuzzy-parah',  icon: '🔴' };
    if (score >= 40) return { label: 'Sedang',  cls: 'fuzzy-sedang', icon: '🟡' };
    return             { label: 'Rendah', cls: 'fuzzy-ringan', icon: '🟢' };
}

function updateFuzzy() {
    const k = parseInt(inpKerusakan.value) || 0;
    const w = parseInt(inpWaktu.value) || 0;

    if (k < 1 || k > 100 || w < 1) {
        fuzzyResult.className = 'fuzzy-empty';
        fuzzyText.textContent = 'Isi nilai kerusakan & waktu untuk melihat prioritas';
        dispKerusakan.textContent = '—';
        dispWaktu.textContent     = '—';
        dispKategori.textContent  = '—';
        dispPrioritas.textContent = '—';
        return;
    }

    const kategori  = getKategori(k);
    const prioritas = getPrioritas(k, w);

    fuzzyResult.className = prioritas.cls;
    fuzzyText.textContent = prioritas.icon + ' Prioritas: ' + prioritas.label
        + ' — Kategori Kerusakan: ' + kategori;

    dispKerusakan.textContent = k;
    dispWaktu.textContent     = w + ' hari';
    dispKategori.textContent  = kategori;
    dispPrioritas.textContent = prioritas.icon + ' ' + prioritas.label;
}

inpKerusakan.addEventListener('input', updateFuzzy);
inpWaktu.addEventListener('input', updateFuzzy);
updateFuzzy(); // inisialisasi saat halaman load

/* ──────────────────────────────────────────────────────────────────────────
   Preview foto before — multiple files
   ────────────────────────────────────────────────────────────────────────── */
const fotoInput     = document.getElementById('foto-before-input');
const previewGrid   = document.getElementById('preview-before');
const counterWrap   = document.getElementById('counter-before');
const counterNum    = document.getElementById('counter-num');
const uploadZone    = document.getElementById('upload-zone-before');
let selectedBeforeFiles = [];

function syncBeforeInput() {
    const dt = new DataTransfer();
    selectedBeforeFiles.forEach(file => dt.items.add(file));
    fotoInput.files = dt.files;
}

function normalizeFileKey(file) {
    return [file.name, file.size, file.lastModified].join('::');
}

function renderBeforePreview(files) {
    previewGrid.innerHTML = '';

    if (!files || files.length === 0) {
        counterWrap.style.display = 'none';
        return;
    }

    counterNum.textContent = files.length;
    counterWrap.style.display = 'block';

    Array.from(files).forEach((file, index) => {
        const url = URL.createObjectURL(file);
        const card = document.createElement('div');
        card.className = 'foto-card';

        const img = document.createElement('img');
        img.src = url;
        img.alt = file.name;
        img.title = file.name + ' (' + (file.size / 1024).toFixed(0) + ' KB)';

        const badge = document.createElement('span');
        badge.className = 'fc-badge';
        badge.textContent = file.name.length > 14
            ? file.name.substring(0, 12) + '…'
            : file.name;

        const removeBtn = document.createElement('button');
        removeBtn.type = 'button';
        removeBtn.className = 'fc-del';
        removeBtn.innerHTML = '<i class="fas fa-times"></i>';
        removeBtn.title = 'Hapus file dari pilihan';
        removeBtn.addEventListener('click', () => {
            selectedBeforeFiles = selectedBeforeFiles.filter((_, i) => i !== index);
            syncBeforeInput();
            renderBeforePreview(selectedBeforeFiles);
            uploadZone.querySelector('.uz-text').textContent = selectedBeforeFiles.length
                ? selectedBeforeFiles.length + ' foto dipilih'
                : 'Tap untuk pilih foto dari kamera atau galeri';
        });

        card.appendChild(img);
        card.appendChild(removeBtn);
        card.appendChild(badge);
        previewGrid.appendChild(card);
    });
}

fotoInput.addEventListener('change', function () {
    const incoming = Array.from(this.files || []);
    const seen = new Set(selectedBeforeFiles.map(normalizeFileKey));

    incoming.forEach(file => {
        const key = normalizeFileKey(file);
        if (!seen.has(key)) {
            selectedBeforeFiles.push(file);
            seen.add(key);
        }
    });

    syncBeforeInput();
    renderBeforePreview(selectedBeforeFiles);
    uploadZone.querySelector('.uz-text').textContent = selectedBeforeFiles.length
        ? selectedBeforeFiles.length + ' foto dipilih'
        : 'Tap untuk pilih foto dari kamera atau galeri';
});

document.addEventListener('DOMContentLoaded', () => {
    renderBeforePreview(selectedBeforeFiles);
});

// Drag & drop visual feedback sudah via CSS (ondragover/ondragleave di HTML)
</script>
<?php include '../partials/mobile_nav.php'; ?>
</body>
</html>










