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

sikompro_require_role('teknisi');

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

// ======================
// PROSES SELESAIKAN
// ======================
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['selesaikan'])){
    $id = (int)$_POST['id'];
    $keterangan = komplain_escape($conn, $_POST['keterangan']);
    $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='{$teknisi_id}' LIMIT 1"));
    $foto_after = komplain_escape($conn, komplain_merge_images($existingRow['foto_after'] ?? '', $uploadedAfter));

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

    $notifRow = mysqli_fetch_assoc(mysqli_query($conn, "SELECT lokasi FROM komplain WHERE id='{$id}' LIMIT 1"));
    komplain_notify(
        $conn,
        'pelaksana',
        'Hasil teknisi sudah masuk',
        'Komplain di lokasi ' . trim((string) ($notifRow['lokasi'] ?? 'komplain')) . ' sudah selesai dikerjakan teknisi.',
        $id
    );

    header("Location: teknisi.php?pesan=selesai");
    exit;
}

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='{$teknisi_id}' 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='$teknisi_id'
    ");

    komplain_notify(
        $conn,
        'pelaksana',
        'Hasil teknisi diperbarui',
        'Ada pembaruan hasil teknisi pada salah satu komplain yang Anda tangani.',
        $id
    );

    header("Location: teknisi.php?pesan=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='$teknisi_id'
    ");

    header("Location: teknisi.php?pesan=data_teknisi_dihapus");
    exit;
}

// ======================
// HITUNG DATA
// ======================
$total   = mysqli_num_rows(mysqli_query($conn,"SELECT id FROM komplain WHERE teknisi_id='$teknisi_id'"));
$pending = mysqli_num_rows(mysqli_query($conn,"SELECT id FROM komplain WHERE teknisi_id='$teknisi_id' AND status='dikirim_ke_teknisi'"));
$proses  = mysqli_num_rows(mysqli_query($conn,"SELECT id FROM komplain WHERE teknisi_id='$teknisi_id' AND status='diproses_teknisi'"));
$selesai = mysqli_num_rows(mysqli_query($conn,"SELECT id FROM komplain WHERE teknisi_id='$teknisi_id' AND status IN ('selesai_teknisi','menunggu_pelaksana','selesai_pelaksana','menunggu_admin','selesai')"));
$q2 = mysqli_query($conn,"
    SELECT MONTH(tanggal) bulan, COUNT(*) jml
    FROM komplain
    WHERE teknisi_id='$teknisi_id'
    GROUP BY MONTH(tanggal)
    ORDER BY MONTH(tanggal)
");
$bulan=[]; $jml_bulan=[];
while($d=mysqli_fetch_assoc($q2)){
    $bulan[]="Bulan ".$d['bulan'];
    $jml_bulan[]=$d['jml'];
}
$filter = isset($_GET['filter']) ? strtolower(trim($_GET['filter'])) : 'total';
$search = trim((string) ($_GET['q'] ?? ''));
$searchSql = $search !== ''
    ? " AND (lokasi LIKE '%" . komplain_escape($conn, $search) . "%' OR lokasi_detail LIKE '%" . komplain_escape($conn, $search) . "%')"
    : "";
$filterSqlMap = [
    'total' => "teknisi_id='$teknisi_id'",
    'pending' => "teknisi_id='$teknisi_id' AND status='dikirim_ke_teknisi'",
    'proses' => "teknisi_id='$teknisi_id' AND status='diproses_teknisi'",
    'selesai' => "teknisi_id='$teknisi_id' AND status IN ('selesai_teknisi','menunggu_pelaksana','selesai_pelaksana','menunggu_admin','selesai')",
];

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

$data = mysqli_query($conn,"
    SELECT * FROM komplain
    WHERE {$filterSqlMap[$filter]} {$searchSql}
    ORDER BY wilayah_id ASC, cluster_id ASC, prioritas DESC, waktu ASC, kerusakan DESC, lokasi_detail ASC, id DESC
");
?>

<!DOCTYPE html>

<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Dashboard 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/5.15.4/css/all.min.css">
<link rel="stylesheet" href="../assets/sikompro-ux.css?v=20260722.11">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>

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

<!-- NAVBAR -->

<nav class="main-header navbar 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>

<!-- SIDEBAR -->

<?php include "../partials/sidebar_menu.php"; komplain_render_sidebar(['role' => 'teknisi', 'home' => 'teknisi.php', 'active' => 'dashboard', 'profileUser' => $profileUser, 'notifCount' => $notifCount]); ?>

<!-- CONTENT -->

<div class="content-wrapper">

<div class="content-header-card content-header-card--media">
    <div class="dashboard-hero-grid">
        <div>
            <span class="dashboard-hero-kicker"><i class="fas fa-bolt"></i> Workspace Teknisi</span>
            <h3 class="mb-2">Dashboard Teknisi</h3>
        </div>
        <div class="dashboard-hero-panel dashboard-hero-compact">
            <a href="data_komplain.php?filter=total" class="dashboard-hero-cta">
                <i class="fas fa-table"></i> Buka Data Komplain
            </a>
        </div>
    </div>
    <div class="media-strip dashboard-media-strip dashboard-media-strip--edge">
        <div class="media-strip-track">
            <div class="media-strip-card"><img src="../assets/homepage/services/services-2.avif" alt="Layanan"></div>
            <div class="media-strip-card"><img src="../assets/homepage/about/about.avif" alt="Tentang kami"></div>
            <div class="media-strip-card"><img src="../assets/homepage/project/project-1.avif" alt="Dashboard proyek"></div>
            <div class="media-strip-card"><img src="../assets/homepage/project/project-2.avif" alt="Tim kerja"></div>
            <div class="media-strip-card"><img src="../assets/homepage/home/bg_1.avif" alt="Lokasi proyek"></div>
            <div class="media-strip-card"><img src="../assets/homepage/blog/image_1.avif" alt="Laporan"></div>
            <div class="media-strip-card"><img src="../assets/homepage/contact/bg_2.avif" alt="Kantor"></div>
            <div class="media-strip-card"><img src="../assets/homepage/services/services-2.avif" alt="Layanan"></div>
            <div class="media-strip-card"><img src="../assets/homepage/about/about.avif" alt="Tentang kami"></div>
            <div class="media-strip-card"><img src="../assets/homepage/project/project-1.avif" alt="Dashboard proyek"></div>
            <div class="media-strip-card"><img src="../assets/homepage/project/project-2.avif" alt="Tim kerja"></div>
            <div class="media-strip-card"><img src="../assets/homepage/home/bg_1.avif" alt="Lokasi proyek"></div>
            <div class="media-strip-card"><img src="../assets/homepage/blog/image_1.avif" alt="Laporan"></div>
            <div class="media-strip-card"><img src="../assets/homepage/contact/bg_2.avif" alt="Kantor"></div>
        </div>
    </div>
</div>

<div class="dashboard-stack">
    <div class="dashboard-card-soft dashboard-chart-panel">
        <div class="dashboard-section-head">
            <div>
                <span class="dashboard-section-kicker"><i class="fas fa-chart-pie"></i> Grafik Baru</span>
                <h4 class="dashboard-section-title text-white">Status Komplain Teknisi</h4>
                <p class="dashboard-section-subtitle">Lihat perbandingan komplain yang menunggu, diproses, dan selesai.</p>
            </div>
            <a href="data_komplain.php?filter=total" class="btn btn-light btn-sm fw-bold">
                <i class="fas fa-table me-1"></i> Detail
            </a>
        </div>
        <div class="dashboard-chart-grid">
            <div class="dashboard-chart-box">
                <canvas id="statusChart"></canvas>
            </div>
            <div class="dashboard-insight-list">
                <div class="dashboard-insight">
                    <div class="dashboard-insight-icon text-info"><i class="fas fa-clipboard-list"></i></div>
                    <div><strong><?= $total ?></strong><span>Total komplain</span></div>
                </div>
                <div class="dashboard-insight">
                    <div class="dashboard-insight-icon text-warning"><i class="fas fa-spinner"></i></div>
                    <div><strong><?= $pending ?></strong><span>Menunggu</span></div>
                </div>
                <div class="dashboard-insight">
                    <div class="dashboard-insight-icon text-primary"><i class="fas fa-hourglass-half"></i></div>
                    <div><strong><?= $proses ?></strong><span>Proses</span></div>
                </div>
                <div class="dashboard-insight">
                    <div class="dashboard-insight-icon text-success"><i class="fas fa-check-circle"></i></div>
                    <div><strong><?= $selesai ?></strong><span>Selesai</span></div>
                </div>
            </div>
        </div>
    </div>

    <div class="dashboard-card-soft dashboard-tools-panel">
        <div class="dashboard-section-head">
            <div>
                <span class="dashboard-section-kicker"><i class="fas fa-th-large"></i> Menu Sistem</span>
                <h4 class="dashboard-section-title">Sistem Menu Kita</h4>
                <p class="dashboard-section-subtitle">Model menu ringkas seperti aplikasi mobile, tetapi isinya menyesuaikan alur teknisi.</p>
            </div>
        </div>
        <div class="dashboard-tools-grid">
            <a href="teknisi.php" class="dashboard-tool">
                <div class="dashboard-tool-icon"><i class="fas fa-home"></i></div>
                <div class="dashboard-tool-label">Dashboard</div>
                <div class="dashboard-tool-meta">Ringkasan kerja</div>
            </a>
            <a href="data_komplain.php?filter=total" class="dashboard-tool">
                <div class="dashboard-tool-icon"><i class="fas fa-table"></i></div>
                <div class="dashboard-tool-label">Komplain</div>
                <div class="dashboard-tool-meta">Pantau pekerjaan</div>
            </a>
            <a href="data_absensi.php" class="dashboard-tool">
                <div class="dashboard-tool-icon"><i class="fas fa-users"></i></div>
                <div class="dashboard-tool-label">Absensi</div>
                <div class="dashboard-tool-meta">Rekap kehadiran</div>
            </a>
            <a href="profil.php" class="dashboard-tool">
                <div class="dashboard-tool-icon"><i class="fas fa-user-circle"></i></div>
                <div class="dashboard-tool-label">Profil</div>
                <div class="dashboard-tool-meta">Akun saya</div>
            </a>
        </div>
    </div>
</div>

<?php if(isset($_GET['pesan'])): ?>
<div class="alert alert-success"><?= htmlspecialchars($_GET['pesan']) ?></div>
<?php endif; ?>

<!-- DATA -->

<div class="dashboard-card-soft dashboard-data-card">
    <div class="dashboard-data-head">
        <div>
            <span class="dashboard-section-kicker"><i class="fas fa-clipboard-check"></i> Data Komplain</span>
            <h4 class="dashboard-section-title mb-0">Daftar Komplain Terbaru</h4>
        </div>
        <div class="dashboard-data-actions">
            <a href="data_komplain.php?filter=total" class="btn btn-sm btn-outline-primary">
                <i class="fas fa-table me-1"></i> Buka halaman data
            </a>
        </div>
    </div>
    <div class="dashboard-data-wrap table-responsive">
        <table id="tabel-komplain" class="table complaint-table table-bordered table-striped table-hover table-klik align-middle mb-0">
            <thead>
            <tr>
                <th>No</th>
                <th>Lokasi</th>
                <th>Kerusakan</th>
                <th>Prioritas</th>
                <th>Status</th>
                <th>Tanggal</th>
                <th>Aksi</th>
            </tr>
            </thead>
            <tbody>
            <?php $no = 1; while($d = mysqli_fetch_assoc($data)): ?>
            <tr data-href="data_komplain.php?filter=<?= urlencode($filter) ?>#detail-<?= $d['id'] ?>">
                <td><?= $no++ ?></td>
                <td><?= htmlspecialchars(komplain_row_value($d, 'lokasi', '-')) ?></td>
                <td><?= htmlspecialchars(komplain_row_value($d, 'kerusakan', '-')) ?></td>
                <td><?= htmlspecialchars(komplain_row_value($d, 'prioritas', '-')) ?></td>
                <td><span class="badge badge-<?= komplain_status_badge($d['status']) ?>"><?= htmlspecialchars(komplain_status_label($d['status'])) ?></span></td>
                <td><?= htmlspecialchars((string) komplain_row_value($d, 'tanggal', '-')) ?></td>
                <td>
                    <a href="data_komplain.php?filter=<?= urlencode($filter) ?>#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="data_komplain.php?filter=<?= urlencode($filter) ?>#detail-<?= $d['id'] ?>" class="btn btn-sm btn-warning"><i class="fas fa-pen"></i> Edit</a>
                </td>
            </tr>
            <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>

</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>
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';
}

document.addEventListener('click', function (event) {
    const image = event.target.closest('.js-view-image');
    if (image) {
        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';
    }
});

document.querySelectorAll('.js-after-input').forEach(input => {
    let selectedFiles = [];
    input.addEventListener('change', function () {
        selectedFiles = selectedFiles.concat(Array.from(this.files));
        const unique = new Map();
        selectedFiles.forEach(file => unique.set(file.name + '-' + file.size + '-' + file.lastModified, file));
        selectedFiles = Array.from(unique.values());

        const dt = new DataTransfer();
        selectedFiles.forEach(file => dt.items.add(file));
        this.files = dt.files;

        const preview = this.parentElement.querySelector('.js-after-preview');
        if (!preview) return;
        preview.innerHTML = '';
        selectedFiles.forEach(file => {
            const img = document.createElement('img');
            img.src = URL.createObjectURL(file);
            img.alt = file.name;
            preview.appendChild(img);
        });
    });
});

const readTheme = () => (localStorage.getItem('sikompro-theme') === 'dark' ? 'dark' : 'light');
const statusCanvas = document.getElementById('statusChart');
const statusCtx = statusCanvas ? statusCanvas.getContext('2d') : null;
let statusChart = null;

function buildStatusChart(theme) {
    if (!statusCtx) return;
    const palette = theme === 'dark'
        ? ['#38bdf8', '#fbbf24', '#60a5fa', '#22c55e']
        : ['#0ea5e9', '#f59e0b', '#2563eb', '#16a34a'];
    const gradient = statusCtx.createLinearGradient(0, 0, 0, 280);
    gradient.addColorStop(0, theme === 'dark' ? 'rgba(56,189,248,.34)' : 'rgba(56,189,248,.24)');
    gradient.addColorStop(1, 'rgba(56,189,248,0)');

    if (statusChart) {
        statusChart.destroy();
    }

    statusChart = new Chart(statusCtx, {
        type: 'line',
        data: {
            labels: <?= json_encode($bulan) ?>,
            datasets: [{
                label: 'Komplain',
                data: <?= json_encode($jml_bulan) ?>,
                borderColor: theme === 'dark' ? '#60a5fa' : '#0ea5e9',
                backgroundColor: gradient,
                fill: true,
                tension: .38,
                borderWidth: 3,
                pointRadius: 3,
                pointHoverRadius: 6,
                pointBackgroundColor: '#ffffff',
                pointBorderColor: theme === 'dark' ? '#60a5fa' : '#0ea5e9',
                pointBorderWidth: 2
            }]
        },
        options: {
            maintainAspectRatio: false,
            interaction: {
                mode: 'index',
                intersect: false
            },
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        precision: 0,
                        color: theme === 'dark' ? '#cbd5e1' : '#64748b',
                        font: { size: 11 }
                    },
                    grid: { color: theme === 'dark' ? 'rgba(148,163,184,.16)' : 'rgba(148,163,184,.18)' }
                },
                x: {
                    ticks: {
                        color: theme === 'dark' ? '#cbd5e1' : '#64748b',
                        font: { size: 11, weight: '600' }
                    },
                    grid: { display: false }
                }
            },
            animation: {
                duration: 900,
                easing: 'easeOutQuart'
            }
        }
    });
}

buildStatusChart(readTheme());
document.addEventListener('sikompro:appearancechange', function (event) {
    const theme = event.detail && event.detail.theme ? event.detail.theme : readTheme();
    buildStatusChart(theme);
});
</script>

<?php include "../partials/mobile_nav.php"; ?>

<script src="../assets/sikompro-theme.js?v=20260722.11"></script>

</body>
</html>












