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

sikompro_require_role('pelaksana');

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

$filter = isset($_GET['filter']) ? strtolower(trim($_GET['filter'])) : 'total';
$search = trim((string) ($_GET['q'] ?? ''));
$searchSql = $search !== ''
    ? " AND (k.lokasi LIKE '%" . komplain_escape($conn, $search) . "%' OR k.lokasi_detail LIKE '%" . komplain_escape($conn, $search) . "%' OR k.deskripsi_komplain LIKE '%" . komplain_escape($conn, $search) . "%')"
    : '';

$filterMap = [
    'total' => ['label' => 'Semua Komplain Pelaksana', 'where' => "k.pelaksana_id='{$userId}'"],
    'pending' => ['label' => 'Komplain Menunggu', 'where' => "k.pelaksana_id='{$userId}' AND k.status IN ('pending','pending_pelaksana')"],
    'proses' => ['label' => 'Komplain Diproses', 'where' => "k.pelaksana_id='{$userId}' AND k.status IN ('diproses_pelaksana','dikirim_ke_teknisi','diproses_teknisi')"],
    'selesai' => ['label' => 'Hasil Komplain', 'where' => "k.pelaksana_id='{$userId}' AND k.status IN ('selesai_teknisi','menunggu_pelaksana','selesai_pelaksana','menunggu_admin','selesai')"],
];

if (!isset($filterMap[$filter])) {
    $filter = 'total';
}

$pageTitle = $filterMap[$filter]['label'];

if (isset($_GET['notif_id'])) {
    komplain_mark_notification_read_by_id($conn, (int) $_GET['notif_id'], 'pelaksana', $userId);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_pelaksana'])) {
    $id = (int) $_POST['id'];
    $ket = komplain_escape($conn, $_POST['pelaksana_keterangan'] ?? '');
    $uploadedBefore = komplain_upload_multiple_images('foto_before', '../uploads/before/', 'before_' . $id);
    $existingRow = mysqli_fetch_assoc(mysqli_query($conn, "SELECT foto_before FROM komplain WHERE id='{$id}' AND pelaksana_id='{$userId}' LIMIT 1"));
    $fotoBefore = komplain_escape($conn, komplain_merge_images($existingRow['foto_before'] ?? '', $uploadedBefore));

    mysqli_query($conn, "
        UPDATE komplain
        SET pelaksana_keterangan='{$ket}',
            foto_before=CASE
                WHEN '{$fotoBefore}' <> '' THEN '{$fotoBefore}'
                ELSE foto_before
            END,
            tanggal_update=NOW()
        WHERE id='{$id}' AND pelaksana_id='{$userId}'
    ");

    header("Location: data_komplain.php?filter=" . urlencode($filter) . "&msg=data_pelaksana_diupdate");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['hapus_pelaksana'])) {
    $id = (int) $_POST['id'];

    mysqli_query($conn, "
        DELETE FROM komplain
        WHERE id='{$id}' AND pelaksana_id='{$userId}'
          AND pelaksana_id='{$userId}'
    ");

    header("Location: data_komplain.php?filter=" . urlencode($filter) . "&msg=data_pelaksana_dihapus");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['terima_admin'])) {
    $id = (int) $_POST['id'];

    mysqli_query($conn, "
        UPDATE komplain SET
        status='diproses_pelaksana',
        pelaksana_id='{$userId}',
        tanggal_update=NOW()
        WHERE id='{$id}' AND pelaksana_id='{$userId}'
    ");

    header("Location: data_komplain.php?filter=" . urlencode($filter) . "&msg=Komplain+diterima+dari+admin");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['kirim'])) {
    $id = (int) $_POST['id'];
    $teknisi_id = (int) ($_POST['teknisi_id'] ?? 0);
    $ketInput = trim((string) ($_POST['keterangan'] ?? ''));
    $deskripsiAdmin = trim((string) ($_POST['deskripsi_admin'] ?? ''));
    $ket = komplain_escape($conn, $ketInput !== '' ? $ketInput : $deskripsiAdmin);
    $uploadedBefore = komplain_upload_multiple_images('foto_before', '../uploads/before/', 'before_' . $id);
    $existingRow = mysqli_fetch_assoc(mysqli_query($conn, "SELECT foto_before, lokasi FROM komplain WHERE id='{$id}' AND pelaksana_id='{$userId}' LIMIT 1"));
    $fotoBefore = komplain_escape($conn, komplain_merge_images($existingRow['foto_before'] ?? '', $uploadedBefore));
    $lokasiNotif = trim((string) ($existingRow['lokasi'] ?? 'komplain'));

    mysqli_query($conn, "
        UPDATE komplain SET
        status='dikirim_ke_teknisi',
        teknisi_id='{$teknisi_id}',
        pelaksana_id='{$userId}',
        pelaksana_keterangan='{$ket}',
        catatan_pelaksana=NULL,
        foto_before=CASE
            WHEN '{$fotoBefore}' <> '' THEN '{$fotoBefore}'
            ELSE foto_before
        END,
        tanggal_update=NOW()
        WHERE id='{$id}' AND pelaksana_id='{$userId}'
    ");

    if ($teknisi_id > 0) {
        $teknisiNotif = mysqli_fetch_assoc(mysqli_query($conn, "SELECT username FROM users WHERE id='{$teknisi_id}' AND role='teknisi' LIMIT 1"));
        $teknisiNama = $teknisiNotif['username'] ?? 'teknisi';
        komplain_notify(
            $conn,
            'teknisi',
            'Komplain baru untuk teknisi',
            "Ada komplain baru di lokasi {$lokasiNotif} yang menunggu penanganan Anda.",
            $id
        );
    }

    header("Location: data_komplain.php?filter=" . urlencode($filter) . "&msg=kirim_teknisi");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['terima'])) {
    $id = (int) $_POST['id'];
    $hasil = komplain_escape($conn, $_POST['hasil_pelaksana'] ?? '');

    mysqli_query($conn, "
        UPDATE komplain
        SET status='selesai_pelaksana',
            hasil_pelaksana=CASE
                WHEN '{$hasil}' <> '' THEN '{$hasil}'
                ELSE hasil_teknisi
            END,
            tanggal_update=NOW()
        WHERE id='{$id}' AND pelaksana_id='{$userId}'
    ");

    komplain_notify(
        $conn,
        'admin',
        'Komplain siap ditinjau admin',
        'Ada komplain yang sudah selesai ditangani pelaksana dan siap masuk ke antrian admin.',
        $id
    );

    header("Location: data_komplain.php?filter=" . urlencode($filter) . "&msg=hasil_teknisi_diterima");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['tolak'])) {
    $id = (int) $_POST['id'];
    $catatan = komplain_escape($conn, $_POST['catatan_pelaksana'] ?? '');

    mysqli_query($conn, "
        UPDATE komplain
        SET status='diproses_teknisi',
            catatan_pelaksana='{$catatan}',
            tanggal_update=NOW()
        WHERE id='{$id}'
    ");

    komplain_notify(
        $conn,
        'teknisi',
        'Ada revisi dari pelaksana',
        'Silakan buka kembali komplain untuk melihat catatan revisi dari pelaksana.',
        $id
    );

    header("Location: data_komplain.php?filter=" . urlencode($filter) . "&msg=revisi_ke_teknisi");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['kirim_admin'])) {
    $id = (int) $_POST['id'];
    $ket = komplain_escape($conn, $_POST['admin_keterangan'] ?? '');

    mysqli_query($conn, "
        UPDATE komplain SET
        status='menunggu_admin',
        hasil_pelaksana='{$ket}',
        admin_keterangan='{$ket}',
        tanggal_update=NOW()
        WHERE id='{$id}'
    ");

    komplain_notify(
        $conn,
        'admin',
        'Komplain menunggu persetujuan admin',
        'Ada hasil komplain yang sudah dikirim pelaksana dan menunggu persetujuan admin.',
        $id
    );

    header("Location: data_komplain.php?filter=" . urlencode($filter) . "&msg=kirim_admin");
    exit;
}

$data = mysqli_query($conn, "
    SELECT k.*, u.username AS teknisi_nama
    FROM komplain k
    LEFT JOIN users u ON u.id = k.teknisi_id
    WHERE {$filterMap[$filter]['where']} {$searchSql}
    ORDER BY k.wilayah_id ASC, k.cluster_id ASC, k.prioritas DESC, k.waktu ASC, k.kerusakan DESC, k.lokasi_detail ASC, k.id DESC
");

$daftarTeknisi = [];
$queryTeknisi = mysqli_query($conn, "SELECT id, username FROM users WHERE role='teknisi' ORDER BY username ASC");
while ($queryTeknisi && ($rowTek = mysqli_fetch_assoc($queryTeknisi))) {
    $daftarTeknisi[] = $rowTek;
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Data Komplain Pelaksana | 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">
</head>
<body class="hold-transition sidebar-mini dashboard-shell">
<div class="wrapper">
<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 align-items-center">
<li class="nav-item">
<button type="button" class="btn btn-outline-light btn-sm dashboard-theme-toggle" data-theme-toggle>
<i data-theme-toggle-icon class="fa fa-adjust"></i>
<span data-theme-toggle-label>Mode Siang</span>
</button>
</li>
</ul>
</nav>
<aside class="main-sidebar sidebar-dark-primary elevation-4">
<a href="dashboard.php" class="brand-link text-center">PT. ALVINDO</a>
<div class="sidebar">
<div class="sidebar-profile">
<img src="<?= komplain_profile_photo_url($profileUser) ?>" alt="Foto profil">
<div class="mt-2 font-weight-bold"><?= htmlspecialchars($profileUser['username']) ?></div>
<small><?= htmlspecialchars(ucfirst($profileUser['role'])) ?></small>
</div>
<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> Dashboard</a></li>
<li class="nav-item"><a href="data_komplain.php?filter=total" class="nav-link active"><i class="nav-icon fas fa-table"></i> Data Komplain</a></li>
<li class="nav-item"><a href="absen.php" class="nav-link"><i class="nav-icon fas fa-user-check"></i> Absen Saya</a></li>
<li class="nav-item"><a href="data_absensi.php" class="nav-link"><i class="nav-icon fas fa-users"></i> Data Absensi</a></li>
<li class="nav-item"><a href="gaji.php" class="nav-link"><i class="nav-icon fas fa-money-bill-wave"></i> Gaji</a></li>
<li class="nav-item"><a href="profil.php" class="nav-link"><i class="nav-icon fas fa-user-circle"></i> Profil</a></li>
<li class="nav-item"><a href="notif.php" class="nav-link"><i class="nav-icon fas fa-bell"></i> Notifikasi <span class="badge badge-warning float-right"><?= $notifCount ?></span></a></li>
<li class="nav-item"><a href="../middleware/logout.php" class="nav-link"><i class="nav-icon fas fa-sign-out-alt"></i> Logout</a></li>
<li class="nav-item mt-2 px-3"><button type="button" class="btn sidebar-theme-toggle" data-theme-toggle><i data-theme-toggle-icon class="fa fa-adjust"></i><span data-theme-toggle-label>Mode Siang</span></button></li>
</ul>
</div>
</aside>

<div class="content-wrapper p-3">
<div class="hero">
<div class="d-flex justify-content-between flex-wrap align-items-center hero-top-row">
<div>
<h4 class="mb-1"><?= htmlspecialchars($pageTitle) ?></h4>
<p class="mb-0">Complaint list / daftar komplain yang sedang atau sudah melewati pelaksana, lengkap dengan hasil teknisi dan hasil akhir.</p>
</div>
<div class="page-actions d-flex align-items-center">
<div class="dropdown action-kebab">
<button class="btn btn-light dropdown-toggle hero-menu-btn" type="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false" title="Opsi lain / More">
<i class="fas fa-ellipsis-v"></i>
</button>
<div class="dropdown-menu dropdown-menu-end">
<a class="dropdown-item" target="_blank" href="cetak_pdf.php?filter=<?= urlencode($filter) ?>"><i class="fas fa-print mr-2"></i>Cetak data / Print</a>
<a class="dropdown-item" href="dashboard.php"><i class="fas fa-home mr-2"></i>Dashboard</a>
<a class="dropdown-item" href="data_absensi.php"><i class="fas fa-users mr-2"></i>Data Absensi</a>
</div>
</div>
<a href="dashboard.php" class="btn btn-outline-secondary"><i class="fas fa-arrow-left"></i> Dashboard</a>
<a href="data_absensi.php" class="btn btn-outline-primary"><i class="fas fa-users"></i> Data Absensi</a>
</div>
</div>
</div>

<div class="filter-toolbar mb-3">
<a href="data_komplain.php?filter=total" class="btn btn-info pill">Total / All</a>
<a href="data_komplain.php?filter=pending" class="btn btn-warning pill">Menunggu / Waiting</a>
<a href="data_komplain.php?filter=proses" class="btn btn-primary pill">Proses / In Progress</a>
<a href="data_komplain.php?filter=selesai" class="btn btn-success pill">Hasil / Done</a>
</div>

<form method="get" class="mb-3">
<input type="hidden" name="filter" value="<?= htmlspecialchars($filter) ?>">
<div class="input-group">
<input type="search" name="q" class="form-control" value="<?= htmlspecialchars($search) ?>" placeholder="Search / cari lokasi, detail, atau deskripsi komplain...">
<div class="input-group-append"><button class="btn btn-primary"><i class="fas fa-search"></i> Cari</button></div>
</div>
</form>

<div class="table-responsive complaint-table-wrap">
    <table id="tabel-komplain" class="table table-bordered table-striped table-hover table-klik complaint-table complaint-table--admin">
        <thead>
            <tr>
                <th>No</th>
                <th>Lokasi</th>
                <th>Kategori</th>
                <th>Kerusakan</th>
                <th>Waktu</th>
                <th>Prioritas</th>
                <th>Status</th>
                <th>Tanggal</th>
                <th>Before</th>
                <th>After</th>
                <th>Aksi</th>
            </tr>
        </thead>
        <tbody>
        <?php $no = 1; $currentGroup = ''; while($d = mysqli_fetch_assoc($data)): ?>
        <?php
        $beforeFiles = komplain_image_files($d['foto_before']);
        $afterFiles = komplain_image_files($d['foto_after']);
        $teknisiNama = komplain_row_value($d, 'teknisi_nama', '-');
        $deskripsiAdmin = komplain_first_non_empty($d, ['deskripsi_komplain'], '-');
        $keteranganPelaksana = komplain_first_non_empty($d, ['pelaksana_keterangan'], '-');
        $hasilTeknisi = komplain_first_non_empty($d, ['hasil_teknisi', 'keterangan'], '-');
        $hasilPelaksana = komplain_first_non_empty($d, ['hasil_pelaksana', 'admin_keterangan'], '-');
        $kategori = komplain_first_non_empty($d, ['kategori_kerusakan'], '-');
        $groupLabel = komplain_first_non_empty($d, ['lokasi'], '-');
        $groupParts = explode(' - ', $groupLabel);
        $groupKey = trim(($groupParts[0] ?? '-') . ' / ' . ($groupParts[1] ?? '-'));
        if ($groupKey !== $currentGroup):
            $currentGroup = $groupKey;
        ?>
            <tr class="group-row"><td colspan="11"><i class="fas fa-map-marker-alt mr-1"></i> <?= htmlspecialchars($currentGroup) ?></td></tr>
        <?php endif; ?>
            <tr id="komplain-<?= $d['id'] ?>">
                <td><?= $no++ ?></td>
                <td>
                    <div class="font-weight-bold"><?= htmlspecialchars(komplain_row_value($d, 'lokasi', '-')) ?></div>
                    <div class="text-muted small"><?= htmlspecialchars(komplain_first_non_empty($d, ['lokasi_detail'], '-')) ?></div>
                </td>
                <td><?= htmlspecialchars($kategori) ?></td>
                <td><?= htmlspecialchars(komplain_row_value($d, 'kerusakan', '-')) ?></td>
                <td><?= htmlspecialchars((string) komplain_row_value($d, 'waktu', '-')) ?></td>
                <td><?= htmlspecialchars(komplain_row_value($d, 'prioritas', '-')) ?></td>
                <td><span class="badge badge-<?= komplain_status_badge($d['status']) ?> py-2 px-3"><?= htmlspecialchars(komplain_status_label($d['status'])) ?></span></td>
                <td><?= htmlspecialchars((string) komplain_row_value($d, 'tanggal', '-')) ?></td>
                <td>
                    <?php if ($beforeFiles): ?>
                        <div class="photo-grid">
                            <?php foreach ($beforeFiles as $foto): ?>
                                <img src="../uploads/before/<?= rawurlencode($foto) ?>" alt="Foto before" class="js-view-image" onclick="sikomproViewImage(this)">
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <span class="text-muted">Belum ada</span>
                    <?php endif; ?>
                </td>
                <td>
                    <?php if ($afterFiles): ?>
                        <div class="photo-grid">
                            <?php foreach ($afterFiles as $foto): ?>
                                <img src="../uploads/after/<?= rawurlencode($foto) ?>" alt="Foto after" class="js-view-image" onclick="sikomproViewImage(this)">
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <span class="text-muted">Belum ada</span>
                    <?php endif; ?>
                </td>
                <td>
                    <div class="admin-action-grid complaint-card-actions">
                        <a href="#detail-<?= $d['id'] ?>" data-detail-toggle="detail-<?= $d['id'] ?>" class="btn btn-sm btn-info"><i class="fas fa-eye"></i> Detail</a>
                        <a href="cetak_pdf.php?id=<?= $d['id'] ?>" class="btn btn-sm btn-secondary" target="_blank"><i class="fas fa-print"></i> Cetak</a>
                        <a href="#detail-<?= $d['id'] ?>" data-detail-toggle="detail-<?= $d['id'] ?>" class="btn btn-sm btn-warning"><i class="fas fa-pen"></i> Edit</a>
                        <form method="post" action="data_komplain.php?filter=<?= urlencode($filter) ?>" onsubmit="return confirm('Hapus data komplain ini?');">
                            <input type="hidden" name="id" value="<?= $d['id'] ?>">
                            <button name="hapus_pelaksana" class="btn btn-sm btn-danger"><i class="fas fa-trash"></i> Hapus</button>
                        </form>
                    </div>
                </td>
            </tr>
            <tr id="detail-<?= $d['id'] ?>" class="complaint-detail-row">
                <td colspan="11">
                    <div class="complaint-detail-panel">
                        <div class="d-flex justify-content-between flex-wrap align-items-start complaint-card-head">
                            <div>
                                <h5 class="mb-1"><?= htmlspecialchars(komplain_row_value($d, 'lokasi', '-')) ?></h5>
                                <div class="text-muted small"><?= htmlspecialchars(komplain_first_non_empty($d, ['lokasi_detail'], '-')) ?></div>
                            </div>
                            <span class="badge badge-<?= komplain_status_badge($d['status']) ?> py-2 px-3"><?= htmlspecialchars(komplain_status_label($d['status'])) ?></span>
                        </div>
                        <div class="complaint-overview">
                            <div class="complaint-field">
                                <span class="complaint-field-label">Teknisi</span>
                                <p class="complaint-field-value"><?= htmlspecialchars($teknisiNama) ?></p>
                            </div>
                            <div class="complaint-field">
                                <span class="complaint-field-label">Keterangan Admin</span>
                                <p class="complaint-field-value"><?= nl2br(htmlspecialchars($deskripsiAdmin)) ?></p>
                            </div>
                            <div class="complaint-field">
                                <span class="complaint-field-label">Keterangan Pelaksana</span>
                                <p class="complaint-field-value"><?= nl2br(htmlspecialchars($keteranganPelaksana)) ?></p>
                            </div>
                            <div class="complaint-field">
                                <span class="complaint-field-label">Hasil Teknisi</span>
                                <p class="complaint-field-value"><?= nl2br(htmlspecialchars($hasilTeknisi)) ?></p>
                            </div>
                        </div>
                        <hr class="complaint-card-divider">
                        <div class="row g-3">
                            <div class="col-lg-6">
                                <div class="complaint-field mb-3">
                                    <span class="complaint-field-label">Hasil Pelaksana</span>
                                    <p class="complaint-field-value"><?= nl2br(htmlspecialchars($hasilPelaksana)) ?></p>
                                </div>
                                <form method="post" action="data_komplain.php?filter=<?= urlencode($filter) ?>" enctype="multipart/form-data" class="mb-3">
                                    <input type="hidden" name="id" value="<?= $d['id'] ?>">
                                    <textarea name="pelaksana_keterangan" class="form-control mb-2" placeholder="Edit keterangan pelaksana..."><?= htmlspecialchars($keteranganPelaksana === '-' ? '' : $keteranganPelaksana) ?></textarea>
                                    <input type="file" name="foto_before[]" class="form-control mb-2" accept="image/*" multiple>
                                    <div class="admin-action-grid complaint-card-actions">
                                        <button name="edit_pelaksana" class="btn btn-warning btn-sm"><i class="fas fa-pen"></i> Edit Data</button>
                                        <button name="hapus_pelaksana" class="btn btn-outline-danger btn-sm" onclick="return confirm('Hapus data komplain ini?');"><i class="fas fa-trash"></i> Hapus Data</button>
                                    </div>
                                </form>
                            </div>
                            <div class="col-lg-6">
                                <?php if ($beforeFiles): ?>
                                    <div class="complaint-field mb-3">
                                        <span class="complaint-field-label">Foto Before</span>
                                        <div class="photo-grid">
                                            <?php foreach ($beforeFiles as $foto): ?>
                                                <img src="../uploads/before/<?= rawurlencode($foto) ?>" alt="Foto before" class="js-view-image" onclick="sikomproViewImage(this)">
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                <?php endif; ?>

                                <?php if ($afterFiles): ?>
                                    <div class="complaint-field mb-3">
                                        <span class="complaint-field-label">Foto After</span>
                                        <div class="photo-grid">
                                            <?php foreach ($afterFiles as $foto): ?>
                                                <img src="../uploads/after/<?= rawurlencode($foto) ?>" alt="Foto after" class="js-view-image" onclick="sikomproViewImage(this)">
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                <?php endif; ?>

                                <?php if(in_array($d['status'], ['pending', 'pending_pelaksana'])): ?>
                                    <form method="post" action="data_komplain.php?filter=<?= urlencode($filter) ?>" class="mb-3">
                                        <input type="hidden" name="id" value="<?= $d['id'] ?>">
                                        <button name="terima_admin" class="btn btn-success btn-sm w-100"><i class="fas fa-check"></i> Terima dari Admin</button>
                                    </form>
                                <?php endif; ?>

                                <?php if($d['status']=='diproses_pelaksana'): ?>
                                    <form method="post" action="data_komplain.php?filter=<?= urlencode($filter) ?>" enctype="multipart/form-data" class="mb-3">
                                        <input type="hidden" name="id" value="<?= $d['id'] ?>">
                                        <input type="hidden" name="deskripsi_admin" value="<?= htmlspecialchars($deskripsiAdmin === '-' ? '' : $deskripsiAdmin) ?>">
                                        <select name="teknisi_id" class="form-control mb-2" required>
                                            <option value="">Pilih Teknisi</option>
                                            <?php foreach($daftarTeknisi as $t): ?>
                                            <option value="<?= (int) $t['id'] ?>"><?= htmlspecialchars($t['username']) ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                        <textarea name="keterangan" class="form-control mb-2" placeholder="Tulis instruksi atau keterangan untuk teknisi..."><?= htmlspecialchars($keteranganPelaksana === '-' ? ($deskripsiAdmin === '-' ? '' : $deskripsiAdmin) : $keteranganPelaksana) ?></textarea>
                                        <input type="file" name="foto_before[]" class="form-control mb-2" accept="image/*" multiple>
                                        <button name="kirim" class="btn btn-primary btn-sm w-100"><i class="fas fa-paper-plane"></i> Kirim ke Teknisi</button>
                                    </form>
                                <?php endif; ?>

                                <?php if(in_array($d['status'], ['selesai_teknisi', 'menunggu_pelaksana'])): ?>
                                    <form method="post" action="data_komplain.php?filter=<?= urlencode($filter) ?>" class="mb-3">
                                        <input type="hidden" name="id" value="<?= $d['id'] ?>">
                                        <textarea name="hasil_pelaksana" class="form-control mb-2" placeholder="Ringkaskan hasil akhir untuk admin..."><?= htmlspecialchars($hasilPelaksana === '-' ? ($hasilTeknisi === '-' ? '' : $hasilTeknisi) : $hasilPelaksana) ?></textarea>
                                        <button name="terima" class="btn btn-success btn-sm w-100 mb-2">Terima Hasil Teknisi</button>
                                    </form>
                                    <form method="post" action="data_komplain.php?filter=<?= urlencode($filter) ?>" class="mb-2">
                                        <input type="hidden" name="id" value="<?= $d['id'] ?>">
                                        <textarea name="catatan_pelaksana" class="form-control mb-2" placeholder="Tulis revisi untuk teknisi..." required></textarea>
                                        <button name="tolak" class="btn btn-danger btn-sm w-100">Kembalikan ke Teknisi</button>
                                    </form>
                                <?php endif; ?>

                                <?php if($d['status'] == 'selesai_pelaksana'): ?>
                                    <div class="alert alert-warning mt-2 mb-3">
                                        <i class="fas fa-info-circle"></i> Setelah hasil sesuai, kirim ringkasan akhir ke admin.
                                    </div>
                                    <form method="post" action="data_komplain.php?filter=<?= urlencode($filter) ?>">
                                        <input type="hidden" name="id" value="<?= $d['id'] ?>">
                                        <textarea name="admin_keterangan" class="form-control mb-2" placeholder="Tulis hasil pekerjaan untuk admin..." required><?= htmlspecialchars($hasilPelaksana === '-' ? '' : $hasilPelaksana) ?></textarea>
                                        <button name="kirim_admin" class="btn btn-success btn-sm w-100"><i class="fas fa-paper-plane"></i> Kirim Hasil ke Admin</button>
                                    </form>
                                <?php endif; ?>
                            </div>
                        </div>

                        <div class="admin-action-grid complaint-footer-actions mt-3">
                            <a href="dashboard.php?filter=<?= urlencode($filter) ?>" class="btn btn-outline-primary btn-sm"><i class="fas fa-clipboard-check"></i> Validasi / Edit</a>
                            <a href="dashboard.php" class="btn btn-outline-secondary btn-sm"><i class="fas fa-eye"></i> Dashboard</a>
                        </div>
                    </div>
                </td>
            </tr>
        <?php endwhile; ?>
        </tbody>
    </table>
</div>

</div>
<div class="image-viewer" id="imageViewer">
<button type="button" class="btn btn-light close-image-viewer-btn" id="closeImageViewer"><i class="fas fa-times"></i></button>
<img src="" alt="Preview gambar">
</div>
<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>
function sikomproViewImage(image) {
    const viewer = document.getElementById('imageViewer');
    const preview = viewer.querySelector('img');
    preview.src = image.getAttribute('src');
    preview.alt = image.getAttribute('alt') || 'Preview gambar';
    viewer.style.display = 'flex';
}

function sikomproToggleDetailRow(rowId) {
    const row = document.getElementById(rowId);
    if (!row) {
        return;
    }

    const isOpen = row.classList.toggle('is-open');
    row.style.display = isOpen ? 'table-row' : 'none';

    if (isOpen) {
        row.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
}

document.addEventListener('click', function (event) {
    const toggle = event.target.closest('[data-detail-toggle]');
    if (toggle) {
        event.preventDefault();
        sikomproToggleDetailRow(toggle.getAttribute('data-detail-toggle'));
        return;
    }

    const image = event.target.closest('.js-view-image');
    if (!image) {
        return;
    }
    sikomproViewImage(image);
});

document.getElementById('closeImageViewer')?.addEventListener('click', function () {
    document.getElementById('imageViewer').style.display = 'none';
});

document.getElementById('imageViewer')?.addEventListener('click', function (event) {
    if (event.target === this) {
        this.style.display = 'none';
    }
});

(function () {
    const hash = window.location.hash.replace('#', '');
    if (!hash || !hash.startsWith('detail-')) {
        return;
    }

    const target = document.getElementById(hash);
    if (!target) {
        return;
    }

    target.classList.add('is-open');
    target.style.display = 'table-row';
})();

(function () {
    const targetId = window.location.hash;
    if (!targetId) {
        return;
    }

    const target = document.querySelector(targetId);
    if (!target) {
        return;
    }

    const reveal = () => {
        target.scrollIntoView({ behavior: 'smooth', block: 'start' });
        target.classList.add('is-target');
        window.setTimeout(() => target.classList.remove('is-target'), 2500);
    };

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', reveal, { once: true });
    } else {
        reveal();
    }
})();
</script>
<script src="../assets/sikompro-theme.js?v=20260722.11"></script>
<?php include '../partials/mobile_nav.php'; ?>
</body>
</html>















