<?php
include "../config/koneksi.php";
include "../middleware/auth.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');

$filter = isset($_GET['filter']) ? strtolower(trim($_GET['filter'])) : 'total';
$qSearch = trim((string) ($_GET['q'] ?? ''));
$searchSql = $qSearch !== ''
    ? " AND (lokasi LIKE '%" . komplain_escape($conn, $qSearch) . "%' OR lokasi_detail LIKE '%" . komplain_escape($conn, $qSearch) . "%' OR deskripsi_komplain LIKE '%" . komplain_escape($conn, $qSearch) . "%')"
    : "";
$allowedFilter = [
    'total' => [
        'title' => 'Semua Data Komplain',
        'sql' => "SELECT * FROM komplain ORDER BY wilayah_id ASC, cluster_id ASC, prioritas DESC, waktu ASC, kerusakan DESC, lokasi_detail ASC, tanggal DESC, id DESC"
    ],
    'pending' => [
        'title' => 'Data Komplain Pending',
        'sql' => "SELECT * FROM komplain WHERE " . komplain_group_sql('status', 'pending') . " ORDER BY wilayah_id ASC, cluster_id ASC, prioritas DESC, waktu ASC, kerusakan DESC, lokasi_detail ASC, tanggal DESC, id DESC"
    ],
    'proses' => [
        'title' => 'Data Komplain Proses',
        'sql' => "SELECT * FROM komplain WHERE " . komplain_group_sql('status', 'proses') . " ORDER BY wilayah_id ASC, cluster_id ASC, prioritas DESC, waktu ASC, kerusakan DESC, lokasi_detail ASC, tanggal DESC, id DESC"
    ],
    'selesai' => [
        'title' => 'Data Komplain Selesai',
        'sql' => "SELECT * FROM komplain WHERE " . komplain_group_sql('status', 'selesai') . " ORDER BY wilayah_id ASC, cluster_id ASC, prioritas DESC, waktu ASC, kerusakan DESC, lokasi_detail ASC, tanggal DESC, id DESC"
    ]
];

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

$pageTitle = $allowedFilter[$filter]['title'];
$baseSql = $allowedFilter[$filter]['sql'];
if ($qSearch !== '') {
    $baseSql = preg_replace('/ ORDER BY /', $filter === 'total' ? " WHERE 1=1 {$searchSql} ORDER BY " : " {$searchSql} ORDER BY ", $baseSql, 1);
}
$dataKomplain = mysqli_query($conn, $baseSql);

?>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= $pageTitle ?></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="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap4.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">
<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="mt-2 font-weight-bold"><?= htmlspecialchars($profileUser['username']) ?></div>
<small><?= htmlspecialchars(ucfirst($profileUser['role'])) ?></small>
</div>
<nav>
<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="users.php" class="nav-link"><i class="nav-icon fas fa-user-cog"></i> Akses User</a>
</li>
<li class="nav-item">
<a href="profil.php" class="nav-link">
<i class="nav-icon fas fa-user-circle"></i> Profil Pengguna
</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="input_komplain_admin.php" class="nav-link">
<i class="nav-icon fas fa-plus"></i> Input Komplain
</a>
</li>
<li class="nav-item">
<a href="cetak_pdf.php" class="nav-link">
<i class="nav-icon fas fa-print"></i> Cetak PDF
</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>
</nav>
</div>
</aside>

<div class="content-wrapper">
<section class="content pt-3">
<div class="container-fluid">

<div class="hero-panel">
<div class="d-flex justify-content-between align-items-center flex-wrap">
<div>
<h3 class="mb-2"><?= $pageTitle ?></h3>
<p class="mb-0">Choose a status / pilih status untuk memfilter data, lalu buka detail komplain untuk melihat dokumentasi before dan after.</p>
</div>
<div class="page-actions mt-3 mt-md-0 d-flex align-items-center">
<div class="dropdown action-kebab">
<button class="btn btn-light dropdown-toggle" 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="input_komplain_admin.php"><i class="fas fa-plus mr-2"></i>Input Komplain</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-light">
<i class="fas fa-arrow-left"></i> Back / Kembali
</a>
<a href="cetak_pdf.php?filter=<?= urlencode($filter) ?>" class="btn btn-outline-light" target="_blank">
<i class="fas fa-print"></i> Print PDF / Cetak
</a>
</div>
</div>
</div>

<div class="filter-toolbar">
<a href="data_komplain.php?filter=total" class="btn btn-info <?= $filter === 'total' ? 'active' : '' ?>"><i class="fas fa-layer-group mr-1"></i> Total / All</a>
<a href="data_komplain.php?filter=pending" class="btn btn-warning <?= $filter === 'pending' ? 'active' : '' ?>"><i class="fas fa-hourglass-half mr-1"></i> Pending / Waiting</a>
<a href="data_komplain.php?filter=proses" class="btn btn-primary <?= $filter === 'proses' ? 'active' : '' ?>"><i class="fas fa-tools mr-1"></i> Proses / Progress</a>
<a href="data_komplain.php?filter=selesai" class="btn btn-success <?= $filter === 'selesai' ? 'active' : '' ?>"><i class="fas fa-check-circle mr-1"></i> Selesai / 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($qSearch) ?>" placeholder="Search / cari wilayah, cluster, lokasi, atau keterangan komplain...">
<div class="input-group-append"><button class="btn btn-primary"><i class="fas fa-search"></i> Cari</button></div>
</div>
</form>

<div class="card">
<div class="card-header">
<h3 class="card-title"><?= $pageTitle ?></h3>
</div>
<div class="card-body">
<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($dataKomplain)){ ?>
<?php
$groupLabel = komplain_first_non_empty($d, ['lokasi'], '-');
$groupParts = explode(' - ', $groupLabel);
$wilayahCluster = trim(($groupParts[0] ?? '-') . ' / ' . ($groupParts[1] ?? '-'));
if ($wilayahCluster !== $currentGroup):
    $currentGroup = $wilayahCluster;
?>
<tr class="group-row"><td colspan="11"><i class="fas fa-map-marker-alt mr-1"></i> <?= htmlspecialchars($currentGroup) ?></td></tr>
<?php endif; ?>
<tr data-href="detail_komplain.php?id=<?= $d['id'] ?>">
<td><?= $no++ ?></td>
<td><?= htmlspecialchars($d['lokasi']) ?></td>
<td><?= htmlspecialchars(komplain_first_non_empty($d, ['kategori_kerusakan'], '-')) ?></td>
<td><?= htmlspecialchars($d['kerusakan']) ?></td>
<td><?= isset($d['waktu']) ? htmlspecialchars($d['waktu']) : '-' ?></td>
<td><?= htmlspecialchars($d['prioritas']) ?></td>
<td><span class="badge badge-<?= komplain_status_badge($d['status']) ?>"><?= htmlspecialchars(komplain_status_label($d['status'])) ?></span></td>
<td><?= htmlspecialchars($d['tanggal']) ?></td>
<td>
<?php $beforeFiles = komplain_image_files($d['foto_before']); ?>
<?php if(!empty($beforeFiles)){ ?>
<?php foreach($beforeFiles as $fotoBefore): ?>
<img src="../uploads/before/<?= rawurlencode($fotoBefore) ?>" alt="Foto before" class="img-thumb js-view-image">
<?php endforeach; ?>
<?php } else { ?>
<span class="text-muted">Belum ada</span>
<?php } ?>
</td>
<td>
<?php $afterFiles = komplain_image_files($d['foto_after']); ?>
<?php if(!empty($afterFiles)){ ?>
<?php foreach($afterFiles as $fotoAfter): ?>
<img src="../uploads/after/<?= rawurlencode($fotoAfter) ?>" alt="Foto after" class="img-thumb js-view-image">
<?php endforeach; ?>
<?php } else { ?>
<span class="text-muted">Belum ada</span>
<?php } ?>
</td>
<td>
<div class="admin-action-grid">
<a href="detail_komplain.php?id=<?= $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="input_komplain_admin.php?id=<?= $d['id'] ?>" class="btn btn-sm btn-warning">
<i class="fas fa-pen"></i> Edit
</a>
<form method="post" action="hapus_komplain.php" class="d-inline" onsubmit="return confirm('Hapus data komplain ini?');">
<input type="hidden" name="id" value="<?= $d['id'] ?>">
<button type="submit" class="btn btn-sm btn-danger">
<i class="fas fa-trash"></i> Hapus
</button>
</form>
</div>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>

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

</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>

<div class="image-viewer" id="imageViewer">
<button type="button" class="btn btn-light" id="closeImageViewer"><i class="fas fa-times"></i></button>
<img src="" alt="Preview gambar">
</div>

<script>
document.querySelectorAll('#tabel-komplain tbody tr').forEach(function (row) {
row.addEventListener('click', function (event) {
    if (event.target.closest('a, button, img')) {
        return;
    }

    const target = this.getAttribute('data-href');
    if (target) {
        window.location = target;
    }
});
});

document.addEventListener('click', function (event) {
    const image = event.target.closest('.js-view-image');
    if (!image) {
        return;
    }
    document.querySelector('#imageViewer img').setAttribute('src', image.getAttribute('src'));
    document.getElementById('imageViewer').style.display = 'flex';
});

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';
    }
});
</script>
<script src="../assets/sikompro-theme.js?v=20260722.11"></script>
<?php include '../partials/mobile_nav.php'; ?>
</body>
</html>











