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

$reportRole = defined('KOMPLAIN_PDF_ROLE') ? (string) KOMPLAIN_PDF_ROLE : 'admin';
$reportRole = in_array($reportRole, ['admin', 'pelaksana', 'teknisi'], true) ? $reportRole : 'admin';
sikompro_require_role($reportRole);
$reportBasePath = defined('KOMPLAIN_PDF_BASE') ? (string) KOMPLAIN_PDF_BASE : '';
$reportUserId = (int) ($_SESSION['user_id'] ?? 0);
$reportScopeSql = '';

if ($reportRole === 'pelaksana') {
    $reportScopeSql = " AND k.pelaksana_id = '{$reportUserId}'";
} elseif ($reportRole === 'teknisi') {
    $reportScopeSql = " AND k.teknisi_id = '{$reportUserId}'";
}

$filter = isset($_GET['filter']) ? strtolower(trim($_GET['filter'])) : 'total';
$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
$layout = isset($_GET['layout']) && strtolower(trim($_GET['layout'])) === 'portrait' ? 'portrait' : 'landscape';

function report_value(array $row, array $keys, string $default = '-'): string {
    return komplain_first_non_empty($row, $keys, $default);
}

function report_date_value(array $row): string {
    $raw = komplain_first_non_empty($row, ['tanggal_update', 'tanggal', 'created_at'], '');
    if ($raw === '') {
        return '-';
    }

    $timestamp = strtotime($raw);
    if ($timestamp === false) {
        return $raw;
    }

    return date('d-m-Y H:i', $timestamp);
}

function report_logo_options(): array {
    $assetDir = realpath(__DIR__ . '/../assets');
    if ($assetDir === false) {
        return [];
    }

    $files = glob($assetDir . DIRECTORY_SEPARATOR . '*.{png,jpg,jpeg,webp,svg,avif}', GLOB_BRACE) ?: [];
    $options = [];

    foreach ($files as $file) {
        $base = basename($file);
        if (stripos($base, 'logo') === false && stripos($base, 'template') === false) {
            continue;
        }
        $options[$base] = '../assets/' . $base;
    }

    if (!isset($options['template-logo.png'])) {
        $options['template-logo.png'] = '../assets/template-logo.png';
    }
    if (!isset($options['alvindo-logo.svg'])) {
        $options['alvindo-logo.svg'] = '../assets/alvindo-logo.svg';
    }

    return $options;
}

function report_logo_path(string $choice): string {
    $options = report_logo_options();
    return $options[$choice] ?? ($options['template-logo.png'] ?? '../assets/template-logo.png');
}

if ($id > 0) {
    $sql = "SELECT k.*,
                   ua.username AS admin_username,
                   ua.email AS admin_email,
                   up.username AS pelaksana_username,
                   up.email AS pelaksana_email,
                   ut.username AS teknisi_username,
                   ut.email AS teknisi_email
            FROM komplain k
            LEFT JOIN users ua ON ua.id = k.admin_id
            LEFT JOIN users up ON up.id = k.pelaksana_id
            LEFT JOIN users ut ON ut.id = k.teknisi_id
            WHERE k.id = '{$id}'{$reportScopeSql} ORDER BY k.id DESC LIMIT 1";
    $title = "Detail Komplain";
} else {
    $map = [
        'pending' => "SELECT k.*,
                             ua.username AS admin_username,
                             ua.email AS admin_email,
                             up.username AS pelaksana_username,
                             up.email AS pelaksana_email,
                             ut.username AS teknisi_username,
                             ut.email AS teknisi_email
                      FROM komplain k
                      LEFT JOIN users ua ON ua.id = k.admin_id
                      LEFT JOIN users up ON up.id = k.pelaksana_id
                      LEFT JOIN users ut ON ut.id = k.teknisi_id
                      WHERE " . komplain_group_sql('k.status', 'pending') . "{$reportScopeSql} ORDER BY k.wilayah_id ASC, k.cluster_id ASC, k.prioritas DESC, k.waktu ASC, k.kerusakan DESC, k.lokasi_detail ASC, k.tanggal DESC, k.id DESC",
        'proses' => "SELECT k.*,
                            ua.username AS admin_username,
                            ua.email AS admin_email,
                            up.username AS pelaksana_username,
                            up.email AS pelaksana_email,
                            ut.username AS teknisi_username,
                            ut.email AS teknisi_email
                     FROM komplain k
                     LEFT JOIN users ua ON ua.id = k.admin_id
                     LEFT JOIN users up ON up.id = k.pelaksana_id
                     LEFT JOIN users ut ON ut.id = k.teknisi_id
                     WHERE " . komplain_group_sql('k.status', 'proses') . "{$reportScopeSql} ORDER BY k.wilayah_id ASC, k.cluster_id ASC, k.prioritas DESC, k.waktu ASC, k.kerusakan DESC, k.lokasi_detail ASC, k.tanggal DESC, k.id DESC",
        'selesai' => "SELECT k.*,
                             ua.username AS admin_username,
                             ua.email AS admin_email,
                             up.username AS pelaksana_username,
                             up.email AS pelaksana_email,
                             ut.username AS teknisi_username,
                             ut.email AS teknisi_email
                      FROM komplain k
                      LEFT JOIN users ua ON ua.id = k.admin_id
                      LEFT JOIN users up ON up.id = k.pelaksana_id
                      LEFT JOIN users ut ON ut.id = k.teknisi_id
                      WHERE " . komplain_group_sql('k.status', 'selesai') . "{$reportScopeSql} ORDER BY k.wilayah_id ASC, k.cluster_id ASC, k.prioritas DESC, k.waktu ASC, k.kerusakan DESC, k.lokasi_detail ASC, k.tanggal DESC, k.id DESC",
        'total' => "SELECT k.*,
                           ua.username AS admin_username,
                           ua.email AS admin_email,
                           up.username AS pelaksana_username,
                           up.email AS pelaksana_email,
                           ut.username AS teknisi_username,
                           ut.email AS teknisi_email
                    FROM komplain k
                    LEFT JOIN users ua ON ua.id = k.admin_id
                    LEFT JOIN users up ON up.id = k.pelaksana_id
                    LEFT JOIN users ut ON ut.id = k.teknisi_id
                    " . ($reportScopeSql ? "WHERE 1=1{$reportScopeSql} " : '') . "ORDER BY k.wilayah_id ASC, k.cluster_id ASC, k.prioritas DESC, k.waktu ASC, k.kerusakan DESC, k.lokasi_detail ASC, k.tanggal DESC, k.id DESC",
    ];
    $sql = $map[$filter] ?? $map['total'];
    $title = "Laporan Komplain " . ucfirst($filter === 'total' ? 'Semua Data' : $filter);
    if ($reportRole === 'pelaksana') {
        $title .= " Pelaksana";
    } elseif ($reportRole === 'teknisi') {
        $title .= " Teknisi";
    }
}

$result = mysqli_query($conn, $sql);
$singleRow = $id > 0 ? ($result ? mysqli_fetch_assoc($result) : null) : null;
$logoOptions = report_logo_options();
$selectedLogo = isset($_GET['mitra_logo']) ? basename((string) $_GET['mitra_logo']) : 'template-logo.png';
if (!isset($logoOptions[$selectedLogo])) {
    $selectedLogo = 'template-logo.png';
}
$selectedLogoPath = report_logo_path($selectedLogo);
$backUrl = $reportRole === 'pelaksana'
    ? $reportBasePath . 'data_komplain.php?filter=' . urlencode($filter)
    : ($reportRole === 'teknisi'
        ? $reportBasePath . 'data_komplain.php?filter=' . urlencode($filter)
        : ($id > 0 ? $reportBasePath . 'detail_komplain.php?id=' . (int) $id : $reportBasePath . 'data_komplain.php?filter=' . urlencode($filter)));
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= htmlspecialchars($title) ?></title>
<style>
:root {
    --ink: #1f2937;
    --muted: #64748b;
    --line: #d7e2f0;
    --brand: #0f2742;
    --accent: #fc5e28;
    --panel: #ffffff;
    --soft: #f5f8fc;
}

* { box-sizing: border-box; }

body {
    font-family: Arial, sans-serif;
    margin: 0;
    color: var(--ink);
    background:
        linear-gradient(180deg, #f8fbff 0%, #eef4fb 100%);
    line-height: 1.55;
}

.page {
    width: min(1180px, calc(100% - 32px));
    margin: 24px auto;
}

@page {
    size: <?= $layout ?>;
    margin: 12mm;
}

.report-card {
    background: var(--panel);
    border: 1px solid var(--line);
    border-radius: 20px;
    box-shadow: 0 14px 34px rgba(15, 23, 42, 0.08);
    overflow: hidden;
}

.report-header {
    display: grid;
    grid-template-columns: 1fr auto 1fr;
    gap: 14px;
    align-items: center;
    padding: 18px 22px 10px;
}

.logo-box {
    min-height: 86px;
    padding: 14px 16px;
    border: 1px solid var(--line);
    border-radius: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #fff;
}

.logo-box img {
    max-width: 100%;
    max-height: 56px;
    object-fit: contain;
}

.logo-box.right {
    justify-content: center;
    gap: 10px;
    flex-direction: column;
}

.report-title {
    text-align: center;
    padding: 6px 22px 18px;
}

.report-title h1 {
    margin: 0;
    font-size: clamp(1.6rem, 3.1vw, 2.4rem);
    line-height: 1.12;
    color: var(--brand);
}

.report-title p {
    margin: 8px 0 0;
    color: var(--muted);
}

.meta-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 12px;
    padding: 0 22px 18px;
}

.meta-card {
    border: 1px solid var(--line);
    border-radius: 16px;
    background: linear-gradient(180deg, #fff 0%, #f7fbff 100%);
    padding: 14px 16px;
}

.meta-card .label {
    display: block;
    color: var(--muted);
    font-size: 0.78rem;
    text-transform: uppercase;
    letter-spacing: 0.08em;
    margin-bottom: 5px;
    font-weight: 700;
}

.meta-card .value {
    font-size: 1rem;
    line-height: 1.45;
    font-weight: 700;
    color: var(--ink);
}

.detail-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 12px;
    padding: 0 22px 18px;
}

.detail-block {
    border: 1px solid var(--line);
    border-radius: 16px;
    background: #fff;
    padding: 16px;
}

.detail-block .label {
    display: block;
    font-size: 0.78rem;
    letter-spacing: 0.08em;
    text-transform: uppercase;
    color: var(--muted);
    font-weight: 700;
    margin-bottom: 6px;
}

.detail-block .value {
    font-size: 0.98rem;
    line-height: 1.7;
}

.detail-block.full {
    grid-column: 1 / -1;
}

.section-title {
    padding: 0 22px 12px;
    font-size: 0.88rem;
    font-weight: 800;
    letter-spacing: 0.12em;
    text-transform: uppercase;
    color: var(--accent);
}

table {
    width: calc(100% - 44px);
    margin: 0 22px 22px;
    border-collapse: collapse;
    background: #fff;
    border: 1px solid var(--line);
    border-radius: 16px;
    overflow: hidden;
    table-layout: fixed;
    font-size: 11px;
}

th, td {
    border: 1px solid var(--line);
    padding: 6px 8px;
    font-size: 11px;
    line-height: 1.45;
    vertical-align: top;
    word-break: break-word;
    overflow-wrap: anywhere;
}

th {
    background: #eaf2ff;
    text-align: left;
    color: #10233d;
    font-size: 12px;
}

thead {
    display: table-header-group;
}

tbody {
    display: table-row-group;
}

tr {
    page-break-inside: avoid;
    break-inside: avoid;
}

td strong {
    color: #10233d;
}

.image-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 4px;
}

.print-img {
    width: 100%;
    height: 40px;
    object-fit: cover;
    border-radius: 10px;
    border: 1px solid var(--line);
}

.print-list {
    display: grid;
    gap: 14px;
    padding: 0 22px 22px;
}

.print-item {
    border: 1px solid var(--line);
    border-radius: 18px;
    background: #fff;
    overflow: hidden;
    break-inside: avoid;
    page-break-inside: avoid;
}

.print-item-header {
    display: flex;
    justify-content: space-between;
    gap: 12px;
    padding: 14px 16px;
    background: linear-gradient(135deg, #f7fbff 0%, #eef5ff 100%);
    border-bottom: 1px solid var(--line);
}

.print-item-title {
    font-size: 1rem;
    font-weight: 800;
    color: var(--brand);
}

.print-item-meta {
    font-size: 0.85rem;
    color: var(--muted);
}

.print-item-grid {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 10px;
    padding: 14px 16px 16px;
}

.print-chip {
    border: 1px solid var(--line);
    border-radius: 14px;
    padding: 10px 12px;
    background: #fafcff;
}

.print-chip .label {
    display: block;
    color: var(--muted);
    font-size: 0.72rem;
    text-transform: uppercase;
    letter-spacing: 0.08em;
    margin-bottom: 4px;
    font-weight: 700;
}

.print-chip .value {
    font-size: 0.94rem;
    line-height: 1.45;
    font-weight: 700;
}

.print-text {
    grid-column: 1 / -1;
}

.print-image-block {
    grid-column: 1 / -1;
}

.print-image-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(86px, 1fr));
    gap: 8px;
}

.toolbar {
    display: flex;
    gap: 10px;
    padding: 0 22px 22px;
    align-items: center;
    flex-wrap: wrap;
}

.toolbar-top {
    padding: 0 0 14px;
    justify-content: flex-end;
    margin: 0 0 8px;
    position: sticky;
    top: 10px;
    z-index: 20;
}

.toolbar-chooser {
    display: inline-flex;
    align-items: center;
    gap: 10px;
    padding: 8px 12px;
    border: 1px solid var(--line);
    border-radius: 999px;
    background: linear-gradient(180deg, #fff 0%, #f5f8fc 100%);
    box-shadow: 0 8px 18px rgba(15, 23, 42, 0.06);
}

.toolbar-chooser-label {
    font-size: 0.82rem;
    font-weight: 800;
    color: var(--brand);
    white-space: nowrap;
}

.toolbar-chooser select {
    appearance: none;
    min-width: 190px;
    border: 1px solid var(--line);
    border-radius: 999px;
    padding: 9px 34px 9px 14px;
    background: #fff url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='14' height='14' viewBox='0 0 20 20' fill='none'%3E%3Cpath d='M5 7l5 6 5-6' stroke='%2310233d' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") no-repeat right 12px center;
    color: var(--ink);
    font-weight: 700;
    line-height: 1.2;
    cursor: pointer;
}

.toolbar-chooser .toolbar-chooser-submit {
    border: 0;
    border-radius: 999px;
    padding: 9px 14px;
    background: var(--brand);
    color: #fff;
    font-weight: 700;
    cursor: pointer;
}

.toolbar-chooser .toolbar-chooser-action {
    border: 0;
    border-radius: 999px;
    padding: 9px 14px;
    background: #edf2f7;
    color: var(--ink);
    font-weight: 700;
    cursor: pointer;
    text-decoration: none;
}

.toolbar-layout {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    font-size: 0.82rem;
    font-weight: 800;
    color: var(--brand);
    white-space: nowrap;
}

.toolbar-layout select {
    appearance: none;
    min-width: 150px;
    border: 1px solid var(--line);
    border-radius: 999px;
    padding: 9px 34px 9px 14px;
    background: #fff url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='14' height='14' viewBox='0 0 20 20' fill='none'%3E%3Cpath d='M5 7l5 6 5-6' stroke='%2310233d' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") no-repeat right 12px center;
    color: var(--ink);
    font-weight: 700;
    line-height: 1.2;
    cursor: pointer;
}

.toolbar-layout select:focus {
    outline: none;
    border-color: rgba(79, 142, 247, 0.65);
    box-shadow: 0 0 0 3px rgba(79, 142, 247, 0.14);
}

.logo-picker {
    position: relative;
    width: 100%;
    cursor: pointer;
}

.logo-picker-input {
    position: absolute;
    inset: 0;
    opacity: 0;
    cursor: pointer;
}

.logo-box.clickable {
    min-height: 136px;
    padding: 18px 20px;
    border-style: dashed;
    background: linear-gradient(180deg, #fff 0%, #f7fbff 100%);
    transition: transform .15s ease, box-shadow .15s ease, border-color .15s ease;
}

.logo-box.clickable:hover {
    transform: translateY(-1px);
    box-shadow: 0 14px 34px rgba(15, 23, 42, 0.10);
    border-color: rgba(79, 142, 247, 0.45);
}

.logo-box.clickable img {
    display: block;
    max-width: 86%;
    max-height: 78px;
    object-fit: contain;
    margin: 0 auto;
}

.logo-box.clickable .logo-box-note {
    display: block;
    margin-top: 10px;
    font-size: 0.72rem;
    font-weight: 700;
    color: var(--muted);
    letter-spacing: 0.02em;
    text-align: center;
}

.toolbar-chooser select:focus {
    outline: none;
    border-color: rgba(79, 142, 247, 0.65);
    box-shadow: 0 0 0 3px rgba(79, 142, 247, 0.14);
}

.toolbar button,
.toolbar a {
    appearance: none;
    border: 0;
    border-radius: 999px;
    padding: 10px 16px;
    background: var(--brand);
    color: #fff;
    font-weight: 700;
    text-decoration: none;
    cursor: pointer;
}

.toolbar .secondary {
    background: #edf2f7;
    color: var(--ink);
}

@media print {
    body {
        background: #fff;
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
        font-size: 11px;
        line-height: 1.45;
    }

    .page {
        width: 100%;
        margin: 0;
    }

    .report-card {
        border: 0;
        box-shadow: none;
        border-radius: 0;
    }

    .toolbar {
        display: none;
    }

    .logo-box-note {
        display: none !important;
    }

    table {
        width: calc(100% - 44px);
    }

    th, td {
        padding: 5px 6px;
        font-size: 10.5px;
        line-height: 1.4;
    }

    .print-list {
        padding: 0 22px 22px;
    }
}

@media (max-width: 768px) {
    .page {
        width: min(100% - 18px, 1180px);
        margin: 12px auto;
    }

    .report-header,
    .meta-grid,
    .detail-grid {
        grid-template-columns: 1fr;
        padding-left: 14px;
        padding-right: 14px;
    }

    table {
        width: max-content;
        min-width: 1040px;
        margin: 0 14px 14px;
        display: block;
        overflow-x: auto;
        font-size: 11px;
        table-layout: auto;
    }

    th, td {
        padding: 6px 7px;
        font-size: 11px;
        line-height: 1.45;
        white-space: nowrap;
    }

    .report-title h1 {
        font-size: 1.35rem;
    }

    .report-title p {
        font-size: .88rem;
    }

    .meta-card .value,
    .detail-block .value,
    .print-item-title,
    .print-chip .value {
        font-size: .94rem;
        line-height: 1.5;
    }

    .toolbar {
        padding: 0 14px 18px;
        flex-wrap: wrap;
    }

    .print-list {
        padding: 0 14px 14px;
    }

    .print-item-grid {
        grid-template-columns: 1fr;
    }

    .toolbar button,
    .toolbar a,
    .toolbar-chooser select {
        width: 100%;
    }

    .toolbar button,
    .toolbar a {
        display: flex;
        align-items: center;
        justify-content: center;
    }
}
</style>
</head>
<body>
<div class="page">
    <div class="toolbar toolbar-top">
        <form method="get" class="toolbar-chooser" style="margin:0;">
            <input type="hidden" name="id" value="<?= (int) $id ?>">
            <input type="hidden" name="filter" value="<?= htmlspecialchars($filter) ?>">
            <label class="toolbar-layout" for="layout-select">
                <span>Ukuran Kertas</span>
                <select id="layout-select" name="layout" onchange="this.form.submit()">
                    <option value="landscape" <?= $layout === 'landscape' ? 'selected' : '' ?>>Landscape</option>
                    <option value="portrait" <?= $layout === 'portrait' ? 'selected' : '' ?>>Portrait</option>
                </select>
            </label>
            <noscript><button type="submit" class="toolbar-chooser-submit">Terapkan</button></noscript>
        </form>
        <button type="button" onclick="window.print()">Cetak / Print</button>
        <a class="secondary" href="<?= htmlspecialchars($backUrl) ?>">Kembali</a>
    </div>
    <div class="report-card">
        <div class="report-header">
            <div class="logo-box">
                <img src="../assets/alvindo-logo.svg" alt="PT Alvindo Bangun Sarana Mandiri">
            </div>
            <div class="report-title">
                <h1><?= htmlspecialchars($title) ?></h1>
                <p>Dicetak pada <?= date('d-m-Y H:i:s') ?></p>
            </div>
            <div class="logo-box right clickable" id="mitraLogoPicker" title="Klik untuk memilih logo dari komputer">
                <label class="logo-picker" for="mitraLogoInput">
                    <input
                        type="file"
                        id="mitraLogoInput"
                        class="logo-picker-input"
                        accept="image/*">
                    <img id="mitraLogoPreview" src="<?= htmlspecialchars($selectedLogoPath) ?>" alt="Logo perusahaan">
                </label>
                <span class="logo-box-note">Klik untuk pilih logo dari komputer</span>
            </div>
        </div>

        <?php if ($singleRow): ?>
            <?php
                $beforeFiles = komplain_image_files($singleRow['foto_before'] ?? '');
                $afterFiles = komplain_image_files($singleRow['foto_after'] ?? '');
            ?>
            <div class="meta-grid">
                <div class="meta-card">
                    <span class="label">Nama QC</span>
                    <div class="value"><?= htmlspecialchars(report_value($singleRow, ['nama_qc', 'qc_name', 'nama_qc_input', 'nama_qc_admin', 'admin_username'])) ?></div>
                </div>
                <div class="meta-card">
                    <span class="label">No Laporan / Reporting No.</span>
                    <div class="value"><?= htmlspecialchars(report_value($singleRow, ['reporting_no', 'no_laporan', 'nomor_laporan'], (string) $singleRow['id'])) ?></div>
                </div>
                <div class="meta-card">
                    <span class="label">Objek</span>
                    <?php
                        $lokasiUtama = report_value($singleRow, ['lokasi', 'objek'], '');
                        $lokasiDetail = trim((string) ($singleRow['lokasi_detail'] ?? ''));
                        $objekLabel = trim(($lokasiUtama !== '' ? $lokasiUtama : '') . ($lokasiDetail !== '' ? ($lokasiUtama !== '' ? ' - ' : '') . $lokasiDetail : ''));
                        if ($objekLabel === '') {
                            $objekLabel = '-';
                        }
                    ?>
                    <div class="value"><?= htmlspecialchars($objekLabel) ?></div>
                </div>
                <div class="meta-card">
                    <span class="label">Tanggal / Jam</span>
                    <div class="value"><?= htmlspecialchars(report_date_value($singleRow)) ?></div>
                </div>
            </div>

            <div class="detail-grid">
                <div class="detail-block">
                    <span class="label">Data Entry Admin</span>
                    <div class="value"><?= htmlspecialchars(report_value($singleRow, ['admin_username', 'nama_admin', 'admin_name', 'admin'], '-')) ?></div>
                </div>
                <div class="detail-block">
                    <span class="label">Field Operator</span>
                    <div class="value"><?= htmlspecialchars(report_value($singleRow, ['pelaksana_username', 'nama_pelaksana', 'pelaksana_name', 'pelaksana'], '-')) ?></div>
                </div>
                <div class="detail-block">
                    <span class="label">Building Technician</span>
                    <div class="value"><?= htmlspecialchars(report_value($singleRow, ['teknisi_username', 'nama_teknisi', 'teknisi_name', 'teknisi'], '-')) ?></div>
                </div>
                <div class="detail-block">
                    <span class="label">Category</span>
                    <div class="value"><?= htmlspecialchars(report_value($singleRow, ['kategori_kerusakan', 'kategori', 'category'], '-')) ?></div>
                </div>
                <div class="detail-block full">
                    <span class="label">Keterangan / Hasil</span>
                    <div class="value">
                        <?= nl2br(htmlspecialchars(report_value($singleRow, ['deskripsi_komplain', 'pelaksana_keterangan', 'hasil_teknisi', 'hasil_pelaksana', 'keterangan'], '-'))) ?>
                    </div>
                </div>
            </div>

            <div class="section-title">Data Komplain</div>
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Lokasi</th>
                        <th>Kategori</th>
                        <th>Nilai</th>
                        <th>Waktu</th>
                        <th>Prioritas</th>
                        <th>Status</th>
                        <th>Keterangan Admin</th>
                        <th>Keterangan Pelaksana</th>
                        <th>Hasil Teknisi</th>
                        <th>Before</th>
                        <th>After</th>
                        <th>Tanggal</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><?= htmlspecialchars($singleRow['id']) ?></td>
                        <td><?= htmlspecialchars(report_value($singleRow, ['lokasi', 'lokasi_detail'], '-')) ?></td>
                        <td><?= htmlspecialchars(report_value($singleRow, ['kategori_kerusakan', 'kategori'], '-')) ?></td>
                        <td><?= htmlspecialchars(report_value($singleRow, ['kerusakan', 'nilai'], '-')) ?></td>
                        <td><?= htmlspecialchars(report_value($singleRow, ['waktu'], '-')) ?></td>
                        <td><?= htmlspecialchars(report_value($singleRow, ['prioritas'], '-')) ?></td>
                        <td><?= htmlspecialchars(komplain_status_label($singleRow['status'] ?? '')) ?></td>
                        <td><?= nl2br(htmlspecialchars(report_value($singleRow, ['deskripsi_komplain', 'admin_keterangan'], '-'))) ?></td>
                        <td><?= nl2br(htmlspecialchars(report_value($singleRow, ['pelaksana_keterangan', 'hasil_pelaksana'], '-'))) ?></td>
                        <td><?= nl2br(htmlspecialchars(report_value($singleRow, ['hasil_teknisi', 'keterangan'], '-'))) ?></td>
                        <td>
                            <div class="image-grid">
                                <?php foreach ($beforeFiles as $foto): ?>
                                    <img class="print-img" src="../uploads/before/<?= rawurlencode($foto) ?>" alt="before">
                                <?php endforeach; ?>
                            </div>
                        </td>
                        <td>
                            <div class="image-grid">
                                <?php foreach ($afterFiles as $foto): ?>
                                    <img class="print-img" src="../uploads/after/<?= rawurlencode($foto) ?>" alt="after">
                                <?php endforeach; ?>
                            </div>
                        </td>
                        <td><?= htmlspecialchars(report_date_value($singleRow)) ?></td>
                    </tr>
                </tbody>
            </table>
        <?php else: ?>
            <div class="section-title">Daftar Komplain</div>
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Lokasi</th>
                        <th>Kategori</th>
                        <th>Nilai</th>
                        <th>Waktu</th>
                        <th>Prioritas</th>
                        <th>Status</th>
                        <th>Keterangan Admin</th>
                        <th>Keterangan Pelaksana</th>
                        <th>Hasil Teknisi</th>
                        <th>Before</th>
                        <th>After</th>
                        <th>Tanggal</th>
                    </tr>
                </thead>
                <tbody>
                <?php while ($row = $result ? mysqli_fetch_assoc($result) : null): ?>
                    <?php
                        $beforeFiles = komplain_image_files($row['foto_before'] ?? '');
                        $afterFiles = komplain_image_files($row['foto_after'] ?? '');
                    ?>
                    <tr>
                        <td><?= htmlspecialchars($row['id']) ?></td>
                        <td><?= htmlspecialchars(report_value($row, ['lokasi', 'lokasi_detail'], '-')) ?></td>
                        <td><?= htmlspecialchars(report_value($row, ['kategori_kerusakan', 'kategori'], '-')) ?></td>
                        <td><?= htmlspecialchars(report_value($row, ['kerusakan', 'nilai'], '-')) ?></td>
                        <td><?= htmlspecialchars(report_value($row, ['waktu'], '-')) ?></td>
                        <td><?= htmlspecialchars(report_value($row, ['prioritas'], '-')) ?></td>
                        <td><?= htmlspecialchars(komplain_status_label($row['status'])) ?></td>
                        <td><?= nl2br(htmlspecialchars(report_value($row, ['deskripsi_komplain', 'admin_keterangan'], '-'))) ?></td>
                        <td><?= nl2br(htmlspecialchars(report_value($row, ['pelaksana_keterangan', 'hasil_pelaksana'], '-'))) ?></td>
                        <td><?= nl2br(htmlspecialchars(report_value($row, ['hasil_teknisi', 'keterangan'], '-'))) ?></td>
                        <td>
                            <div class="image-grid">
                                <?php foreach ($beforeFiles as $foto): ?>
                                    <img class="print-img" src="../uploads/before/<?= rawurlencode($foto) ?>" alt="before">
                                <?php endforeach; ?>
                            </div>
                        </td>
                        <td>
                            <div class="image-grid">
                                <?php foreach ($afterFiles as $foto): ?>
                                    <img class="print-img" src="../uploads/after/<?= rawurlencode($foto) ?>" alt="after">
                                <?php endforeach; ?>
                            </div>
                        </td>
                        <td><?= htmlspecialchars(report_date_value($row)) ?></td>
                    </tr>
                <?php endwhile; ?>
                </tbody>
            </table>
        <?php endif; ?>

        <div class="toolbar">
            <button type="button" onclick="window.print()">Cetak</button>
            <a class="secondary" href="data_komplain.php?filter=<?= urlencode($filter) ?>">Kembali</a>
        </div>
    </div>
</div>
<script>
(function () {
    const storageKey = 'sikompro-print-mitra-logo';
    const input = document.getElementById('mitraLogoInput');
    const preview = document.getElementById('mitraLogoPreview');

    if (!input || !preview) {
        return;
    }

    try {
        const saved = localStorage.getItem(storageKey);
        if (saved) {
            preview.src = saved;
        }
    } catch (error) {}

    input.addEventListener('change', function () {
        const file = this.files && this.files[0];
        if (!file) {
            return;
        }

        const reader = new FileReader();
        reader.onload = function () {
            const result = String(reader.result || '');
            if (!result) {
                return;
            }
            preview.src = result;
            try {
                localStorage.setItem(storageKey, result);
            } catch (error) {}
        };
        reader.readAsDataURL(file);
    });
})();
</script>
<?php include '../partials/mobile_nav.php'; ?>
</body>
</html>

