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

sikompro_require_role('teknisi');

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

$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 Teknisi', 'where' => "k.teknisi_id='{$userId}'"],
    'pending' => ['label' => 'Komplain Menunggu', 'where' => "k.teknisi_id='{$userId}' AND k.status='dikirim_ke_teknisi'"],
    'proses' => ['label' => 'Komplain Diproses', 'where' => "k.teknisi_id='{$userId}' AND k.status='diproses_teknisi'"],
    'selesai' => ['label' => 'Hasil Komplain', 'where' => "k.teknisi_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'], 'teknisi', $userId);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_teknisi'])) {
    $id = (int) $_POST['id'];
    $keterangan = komplain_escape($conn, $_POST['hasil_teknisi'] ?? '');
    $uploadedAfter = komplain_upload_multiple_images('foto_after', '../uploads/after/', 'after_' . $id);
    $existingRow = mysqli_fetch_assoc(mysqli_query($conn, "SELECT foto_after FROM komplain WHERE id='{$id}' AND teknisi_id='{$userId}' LIMIT 1"));
    $fotoAfter = komplain_escape($conn, komplain_merge_images($existingRow['foto_after'] ?? '', $uploadedAfter));

    mysqli_query($conn, "
        UPDATE komplain SET
        hasil_teknisi='{$keterangan}',
        keterangan='{$keterangan}',
        foto_after=CASE
            WHEN '{$fotoAfter}' <> '' THEN '{$fotoAfter}'
            ELSE foto_after
        END,
        tanggal_update=NOW()
        WHERE id='{$id}' AND teknisi_id='{$userId}'
    ");

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['hapus_teknisi'])) {
    $id = (int) $_POST['id'];
    mysqli_query($conn, "
        DELETE FROM komplain
        WHERE id='{$id}'
          AND teknisi_id='{$userId}'
    ");
    header("Location: data_komplain.php?filter=" . urlencode($filter) . "&msg=data_teknisi_dihapus");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['terima_teknisi'])) {
    $id = (int) $_POST['id'];
    mysqli_query($conn, "
        UPDATE komplain
        SET status='diproses_teknisi',
            tanggal_update=NOW()
        WHERE id='{$id}' AND teknisi_id='{$userId}'
    ");
    header("Location: data_komplain.php?filter=" . urlencode($filter) . "&msg=Komplain+diterima");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['selesaikan_teknisi'])) {
    $id = (int) $_POST['id'];
    $keterangan = komplain_escape($conn, $_POST['keterangan'] ?? '');
    $uploadedAfter = komplain_upload_multiple_images('foto_after', '../uploads/after/', 'after_done_' . $id);
    $existingRow = mysqli_fetch_assoc(mysqli_query($conn, "SELECT foto_after FROM komplain WHERE id='{$id}' AND teknisi_id='{$userId}' LIMIT 1"));
    $fotoAfter = komplain_escape($conn, komplain_merge_images($existingRow['foto_after'] ?? '', $uploadedAfter));

    mysqli_query($conn, "
        UPDATE komplain SET
        status='selesai_teknisi',
        hasil_teknisi=CASE
            WHEN '{$keterangan}' <> '' THEN '{$keterangan}'
            ELSE hasil_teknisi
        END,
        keterangan=CASE
            WHEN '{$keterangan}' <> '' THEN '{$keterangan}'
            ELSE keterangan
        END,
        foto_after=CASE
            WHEN '{$fotoAfter}' <> '' THEN '{$fotoAfter}'
            ELSE foto_after
        END,
        tanggal_update=NOW()
        WHERE id='{$id}' AND teknisi_id='{$userId}'
    ");

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

$data = mysqli_query($conn, "
    SELECT k.*, u.username AS pelaksana_nama
    FROM komplain k
    LEFT JOIN users u ON u.id = k.pelaksana_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
");
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Data Komplain Teknisi | 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">
<?php include '../partials/sidebar_menu.php'; komplain_render_sidebar([
    'role' => 'teknisi',
    'home' => 'dashboard.php',
    'active' => 'data_komplain',
    'profileUser' => $profileUser,
    'notifCount' => $notifCount,
]); ?>

<div class="content-wrapper p-3">
<div class="container-fluid">
<a href="dashboard.php" class="dashboard-back-button mb-3"><i class="fa fa-arrow-left" aria-hidden="true"></i><span>Kembali</span></a>

<div class="hero-panel">
    <div class="d-flex justify-content-between flex-wrap align-items-center" style="gap:10px;">
        <div>
            <h4 class="mb-1"><?= htmlspecialchars($pageTitle) ?></h4>
            <p class="mb-0">Complaint list / daftar komplain teknisi dengan tampilan tabel geser yang lebih nyaman di mobile.</p>
        </div>
        <div class="page-actions 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="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 / 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="card">
    <div class="card-header d-flex justify-content-between align-items-center flex-wrap" style="gap:12px;">
        <h3 class="card-title mb-0"><?= htmlspecialchars($pageTitle) ?></h3>
        <span class="text-muted small">Geser tabel ke samping untuk melihat seluruh kolom dan tombol.</span>
    </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($data)): ?>
        <?php
        $beforeFiles = komplain_image_files($d['foto_before']);
        $afterFiles = komplain_image_files($d['foto_after']);
        $pelaksanaNama = komplain_row_value($d, 'pelaksana_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'], '-');
        $catatanRevisi = komplain_first_non_empty($d, ['catatan_pelaksana'], '-');
        $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_teknisi" 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($pelaksanaNama) ?></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">Catatan Revisi</span>
                                <p class="complaint-field-value"><?= nl2br(htmlspecialchars($catatanRevisi)) ?></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 Teknisi</span>
                                    <p class="complaint-field-value"><?= nl2br(htmlspecialchars($hasilTeknisi)) ?></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="hasil_teknisi" class="form-control mb-2" placeholder="Edit hasil teknisi..." required><?= htmlspecialchars($hasilTeknisi === '-' ? '' : $hasilTeknisi) ?></textarea>
                                    <input type="file" name="foto_after[]" class="form-control mb-2" accept="image/*" multiple>
                                    <div class="admin-action-grid complaint-card-actions">
                                        <button name="edit_teknisi" class="btn btn-warning btn-sm"><i class="fas fa-pen"></i> Simpan Edit</button>
                                        <button name="hapus_teknisi" 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 ($d['status'] === 'dikirim_ke_teknisi'): ?>
                                    <form method="post" action="data_komplain.php?filter=<?= urlencode($filter) ?>" class="mb-3">
                                        <input type="hidden" name="id" value="<?= $d['id'] ?>">
                                        <button name="terima_teknisi" class="btn btn-warning btn-sm w-100"><i class="fas fa-check"></i> Terima</button>
                                    </form>
                                <?php endif; ?>

                                <?php if ($d['status'] === 'diproses_teknisi'): ?>
                                    <form method="post" action="data_komplain.php?filter=<?= urlencode($filter) ?>" enctype="multipart/form-data">
                                        <input type="hidden" name="id" value="<?= $d['id'] ?>">
                                        <textarea name="keterangan" class="form-control mt-2" placeholder="Keterangan hasil akhir..." required><?= htmlspecialchars($hasilTeknisi === '-' ? '' : $hasilTeknisi) ?></textarea>
                                        <input type="file" name="foto_after[]" class="form-control mt-2" accept="image/*" multiple required>
                                        <div class="photo-grid js-after-preview mt-2"></div>
                                        <button name="selesaikan_teknisi" class="btn btn-success btn-sm mt-2 w-100"><i class="fas fa-flag-checkered"></i> Selesaikan</button>
                                    </form>
                                <?php endif; ?>

                                <?php if (in_array($d['status'], ['selesai_teknisi', 'menunggu_pelaksana', 'selesai_pelaksana', 'menunggu_admin', 'selesai'])): ?>
                                    <div class="alert alert-info mt-3 mb-0">Hasil perbaikan sudah terkirim ke pelaksana. Menunggu pengecekan lanjutan.</div>
                                <?php endif; ?>
                            </div>
                        </div>

                        <div class="admin-action-grid complaint-footer-actions mt-3">
                            <a href="data_komplain.php?filter=<?= urlencode($filter) ?>" class="btn btn-outline-primary btn-sm"><i class="fas fa-pen"></i> Buka 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>

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