<?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');

$statusMap = [
    'total' => [
        'label' => 'Total Komplain',
        'query' => "SELECT COUNT(*) as jml FROM komplain"
    ],
    'pending' => [
        'label' => 'Pending',
        'query' => "SELECT COUNT(*) as jml FROM komplain WHERE " . komplain_group_sql('status', 'pending')
    ],
    'proses' => [
        'label' => 'Proses',
        'query' => "SELECT COUNT(*) as jml FROM komplain WHERE " . komplain_group_sql('status', 'proses')
    ],
    'selesai' => [
        'label' => 'Selesai',
        'query' => "SELECT COUNT(*) as jml FROM komplain WHERE " . komplain_group_sql('status', 'selesai')
    ]
];

$total = mysqli_fetch_assoc(mysqli_query($conn, $statusMap['total']['query']))['jml'];
$pending = mysqli_fetch_assoc(mysqli_query($conn, $statusMap['pending']['query']))['jml'];
$proses = mysqli_fetch_assoc(mysqli_query($conn, $statusMap['proses']['query']))['jml'];
$selesai = mysqli_fetch_assoc(mysqli_query($conn, $statusMap['selesai']['query']))['jml'];

$prosesPelaksana = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as jml FROM komplain WHERE status='diproses_pelaksana'"))['jml'];
$prosesTeknisi = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as jml FROM komplain WHERE status IN ('dikirim_ke_teknisi', 'diproses_teknisi')"))['jml'];
$hasilTeknisi = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as jml FROM komplain WHERE status IN ('selesai_teknisi', 'menunggu_pelaksana')"))['jml'];
$hasilPelaksana = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as jml FROM komplain WHERE status IN ('selesai_pelaksana', 'menunggu_admin')"))['jml'];
$hasilAdmin = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as jml FROM komplain WHERE status IN ('selesai', 'final_selesai')"))['jml'];

$q = mysqli_query($conn,"SELECT status, COUNT(*) jml FROM komplain GROUP BY status");
$label=[]; $data=[];
while($d=mysqli_fetch_assoc($q)){
    $label[]=$d['status'];
    $data[]=$d['jml'];
}

$q2 = mysqli_query($conn,"
SELECT MONTH(tanggal) bulan, COUNT(*) jml
FROM komplain GROUP BY MONTH(tanggal)
");
$bulan=[]; $jml_bulan=[];
while($d=mysqli_fetch_assoc($q2)){
    $bulan[]="Bulan ".$d['bulan'];
    $jml_bulan[]=$d['jml'];
}

$weeklyLabels = [];
$weeklyData = [];
for ($i = 6; $i >= 0; $i--) {
    $date = date('Y-m-d', strtotime("-{$i} day"));
    $weeklyLabels[] = date('d M', strtotime($date));
    $weeklyData[$date] = 0;
}
$qWeekly = mysqli_query($conn, "
SELECT DATE(tanggal) tgl, COUNT(*) jml
FROM komplain
WHERE tanggal >= DATE_SUB(CURDATE(), INTERVAL 6 DAY)
GROUP BY DATE(tanggal)
ORDER BY DATE(tanggal) ASC
");
while($d=mysqli_fetch_assoc($qWeekly)){
    $tgl = $d['tgl'];
    if (isset($weeklyData[$tgl])) {
        $weeklyData[$tgl] = (int) $d['jml'];
    }
}
$weeklyValues = array_values($weeklyData);

$monthlyLabels = ['Jan','Feb','Mar','Apr','Mei','Jun','Jul','Agu','Sep','Okt','Nov','Des'];
$monthlyData = array_fill(0, 12, 0);
$qMonthly = mysqli_query($conn, "
SELECT MONTH(tanggal) bulan, COUNT(*) jml
FROM komplain
WHERE YEAR(tanggal) = YEAR(CURDATE())
GROUP BY MONTH(tanggal)
ORDER BY MONTH(tanggal) ASC
");
while($d=mysqli_fetch_assoc($qMonthly)){
    $index = max(1, min(12, (int) $d['bulan'])) - 1;
    $monthlyData[$index] = (int) $d['jml'];
}

$dataKomplain = mysqli_query($conn,"SELECT * FROM komplain ORDER BY id DESC");
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Dashboard Admin | 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">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

</head>

<body class="hold-transition sidebar-mini layout-fixed 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>

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

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

<div class="content-header-card content-header-card--media">
    <div class="dashboard-hero-grid dashboard-hero-grid--single">
        <div>
            <span class="dashboard-hero-kicker"><i class="fas fa-bolt"></i> Workspace Admin</span>
            <h3 class="mb-2">Dashboard Admin</h3>
            <h6 class="mb-3">selamat datang di sistem pelayanan komplain PT.ALVINDO</h6>
        </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 Hari Ini</h4>
                <p class="dashboard-section-subtitle">Status, mingguan, dan bulanan ditampilkan dengan visual yang lebih mudah dibaca di mobile maupun desktop.</p>
            </div>
        </div>
        <div class="dashboard-chart-grid">
            <div class="dashboard-chart-cards">
                <div class="dashboard-chart-card">
                    <div class="dashboard-chart-card-head">
                        <div>
                            <h5 class="dashboard-chart-card-title">Status Komplain</h5>
                            <p class="dashboard-chart-card-note">Distribusi pending, proses, dan selesai</p>
                        </div>
                    </div>
                    <div class="dashboard-chart-box">
                        <canvas id="statusChart"></canvas>
                    </div>
                </div>
                <div class="dashboard-chart-card">
                    <div class="dashboard-chart-card-head">
                        <div>
                            <h5 class="dashboard-chart-card-title">Mingguan</h5>
                            <p class="dashboard-chart-card-note">Pergerakan komplain 7 hari terakhir</p>
                        </div>
                    </div>
                    <div class="dashboard-chart-box">
                        <canvas id="weeklyChart"></canvas>
                    </div>
                </div>
                <div class="dashboard-chart-card">
                    <div class="dashboard-chart-card-head">
                        <div>
                            <h5 class="dashboard-chart-card-title">Bulanan</h5>
                            <p class="dashboard-chart-card-note">Trend komplain sepanjang tahun</p>
                        </div>
                    </div>
                    <div class="dashboard-chart-box">
                        <canvas id="monthlyChart"></canvas>
                    </div>
                </div>
            </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>Pending</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 sistem kita.</p>
            </div>
        </div>
        <div class="dashboard-tools-grid">
            <a href="dashboard.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 utama</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">Data komplain</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 harian</div>
            </a>
            <a href="users.php" class="dashboard-tool">
                <div class="dashboard-tool-icon"><i class="fas fa-cog"></i></div>
                <div class="dashboard-tool-label">Akses user</div>
                <div class="dashboard-tool-meta">seting user</div>
            </a>
        </div>
    </div>

    <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="input_komplain_admin.php" class="btn btn-sm btn-primary">
                    <i class="fas fa-plus me-1"></i> Input baru
                </a>
                <a href="data_komplain.php?filter=total" class="btn btn-sm btn-outline-primary">
                    <i class="fas fa-list me-1"></i> Buka halaman data
                </a>
            </div>
        </div>
        <div class="dashboard-data-wrap table-responsive">

<table id="example" 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($dataKomplain)){ ?>
<tr data-href="detail_komplain.php?id=<?= $d['id'] ?>">
<td><?= $no++ ?></td>
<td><?= htmlspecialchars($d['lokasi']) ?></td>
<td><?= htmlspecialchars($d['kerusakan']) ?></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>
<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>
</td>
</tr>
<?php } ?>
</tbody>

</table>

</div>

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

</div>

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

<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>
document.querySelectorAll('#example tbody tr').forEach(function (row) {
row.addEventListener('click', function (event) {
    if (event.target.closest('a, button')) {
        return;
    }

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

const readTheme = () => (localStorage.getItem('sikompro-theme') === 'dark' ? 'dark' : 'light');
const getChartPalette = (theme) => ({
    text: theme === 'dark' ? '#eef5ff' : '#10233d',
    muted: theme === 'dark' ? '#cbd5e1' : '#475569',
    grid: theme === 'dark' ? 'rgba(148,163,184,.16)' : 'rgba(148,163,184,.20)',
    doughnut: ['#f59e0b', '#0ea5e9', '#3b82f6', '#06b6d4', '#a855f7', '#22c55e'],
    blue: theme === 'dark' ? '#60a5fa' : '#1d4ed8',
    cyan: theme === 'dark' ? '#38bdf8' : '#06b6d4',
    violet: theme === 'dark' ? '#a78bfa' : '#7c3aed'
});
const chartCanvas = {
    status: document.getElementById('statusChart'),
    weekly: document.getElementById('weeklyChart'),
    monthly: document.getElementById('monthlyChart')
};
const chartCtx = {
    status: chartCanvas.status ? chartCanvas.status.getContext('2d') : null,
    weekly: chartCanvas.weekly ? chartCanvas.weekly.getContext('2d') : null,
    monthly: chartCanvas.monthly ? chartCanvas.monthly.getContext('2d') : null
};
let statusChart = null;
let weeklyChart = null;
let monthlyChart = null;

function buildStatusChart(theme) {
    if (!chartCtx.status) return;
    const colors = getChartPalette(theme);
    const gradient = chartCtx.status.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(chartCtx.status, {
        type: 'doughnut',
        data: {
            labels: ['Pending', 'Pelaksana', 'Teknisi', 'Hasil Teknisi', 'Hasil Pelaksana', 'Admin'],
            datasets: [{
                data: [
                    <?= (int) $pending ?>,
                    <?= (int) $prosesPelaksana ?>,
                    <?= (int) $prosesTeknisi ?>,
                    <?= (int) $hasilTeknisi ?>,
                    <?= (int) $hasilPelaksana ?>,
                    <?= (int) $hasilAdmin ?>
                ],
                backgroundColor: colors.doughnut,
                borderColor: theme === 'dark' ? 'rgba(8,15,28,0.95)' : '#ffffff',
                borderWidth: 4,
                hoverOffset: 10
            }]
        },
        options: {
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        color: colors.muted,
                        usePointStyle: true,
                        pointStyle: 'circle',
                        boxWidth: 10,
                        boxHeight: 10,
                        padding: 14,
                        font: { size: 11, weight: '600' }
                    }
                }
            },
            cutout: '68%',
            rotation: -90,
            circumference: 360
        }
    });
}

function buildLineChart(ctx, chartRef, labels, data, color, theme, title) {
    if (!ctx) return chartRef;
    const gradient = ctx.createLinearGradient(0, 0, 0, 260);
    gradient.addColorStop(0, theme === 'dark' ? 'rgba(96,165,250,.38)' : 'rgba(29,78,216,.28)');
    gradient.addColorStop(1, 'rgba(96,165,250,0)');
    if (chartRef) {
        chartRef.destroy();
    }
    return new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [{
                label: title,
                data: data,
                borderColor: color,
                backgroundColor: gradient,
                fill: true,
                tension: .48,
                borderWidth: 3,
                pointRadius: 3,
                pointHoverRadius: 6,
                pointBackgroundColor: '#ffffff',
                pointBorderColor: color,
                pointBorderWidth: 2
            }]
        },
        options: {
            maintainAspectRatio: false,
            interaction: {
                mode: 'index',
                intersect: false
            },
            plugins: {
                legend: { display: false }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        precision: 0,
                        color: getChartPalette(theme).muted,
                        font: { size: 11 }
                    },
                    grid: { color: getChartPalette(theme).grid }
                },
                x: {
                    ticks: {
                        color: getChartPalette(theme).muted,
                        font: { size: 11, weight: '600' }
                    },
                    grid: { display: false }
                }
            },
            animation: {
                duration: 900,
                easing: 'easeOutQuart'
            }
        }
    });
}

function renderCharts(theme) {
    buildStatusChart(theme);
    weeklyChart = buildLineChart(
        chartCtx.weekly,
        weeklyChart,
        <?= json_encode($weeklyLabels) ?>,
        <?= json_encode(array_values($weeklyValues)) ?>,
        getChartPalette(theme).cyan,
        theme,
        'Mingguan'
    );
    monthlyChart = buildLineChart(
        chartCtx.monthly,
        monthlyChart,
        <?= json_encode($monthlyLabels) ?>,
        <?= json_encode($monthlyData) ?>,
        getChartPalette(theme).violet,
        theme,
        'Bulanan'
    );
}

renderCharts(readTheme());

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

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

</body>
</html>









