<?= view('admin/layouts/header', ['title' => 'Dashboard']) ?>
<?= view('admin/layouts/sidebar', [
    'activeMenu' => 'dashboard',
    'userName'   => $userName,
    'userEmail'  => $userEmail,
    'userRole'   => $userRole,
]) ?>
<?php
$isAdministrator = ($userRole ?? '') === 'administrator';
$isKasir = ($userRole ?? '') === 'kasir';
$dashboardSubtitle = $isKasir
    ? 'Ringkasan transaksi kasir, service aktif, dan stok yang perlu dicek.'
    : 'Ringkasan penjualan, service, stok, dan pembayaran NusaPOS.';
?>
<?= view('admin/layouts/topbar', [
    'pageTitle'    => 'Dashboard',
    'pageSubtitle' => $dashboardSubtitle,
    'userName'     => $userName,
    'userRole'     => $userRole,
]) ?>

<?php
$isOperationalRole = in_array(($userRole ?? ''), ['administrator', 'kasir'], true);
$money = static fn ($value): string => 'Rp ' . number_format((float) ($value ?? 0), 0, ',', '.');
$number = static fn ($value): string => number_format((float) ($value ?? 0), 0, ',', '.');
$serviceStatusLabels = [
    'menunggu' => 'Menunggu',
    'dalam_pengerjaan' => 'Dalam Pengerjaan',
    'selesai_siap_ambil' => 'Siap Ambil',
    'selesai_diambil' => 'Selesai',
];
$serviceStatusBadges = [
    'menunggu' => 'text-bg-warning',
    'dalam_pengerjaan' => 'text-bg-primary',
    'selesai_siap_ambil' => 'text-bg-info',
    'selesai_diambil' => 'text-bg-success',
];
?>

<section class="content-area">
    <?php if (session()->getFlashdata('success')) : ?>
        <div class="alert alert-success"><?= esc(session()->getFlashdata('success')) ?></div>
    <?php endif; ?>

    <?php if (session()->getFlashdata('error')) : ?>
        <div class="alert alert-danger"><?= esc(session()->getFlashdata('error')) ?></div>
    <?php endif; ?>

    <?php if ($isKasir) : ?>
        <div class="panel p-4 mb-4">
            <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-3">
                <div>
                    <div class="fw-bold">Aksi Cepat Kasir</div>
                    <div class="small text-secondary">Menu operasional yang biasa dipakai saat transaksi.</div>
                </div>
            </div>

            <div class="row g-3">
                <div class="col-12 col-md-6 col-xl-3">
                    <a href="<?= site_url('admin/penjualan/create') ?>" class="btn btn-dark w-100 h-100 py-3 d-flex align-items-center justify-content-center gap-2">
                        <i class="bi bi-cart-plus"></i>Tambah Penjualan
                    </a>
                </div>
                <div class="col-12 col-md-6 col-xl-3">
                    <a href="<?= site_url('admin/service/create') ?>" class="btn btn-outline-dark w-100 h-100 py-3 d-flex align-items-center justify-content-center gap-2">
                        <i class="bi bi-wrench-adjustable"></i>Tambah Service
                    </a>
                </div>
                <div class="col-12 col-md-6 col-xl-3">
                    <a href="<?= site_url('admin/service?status_service=selesai_siap_ambil') ?>" class="btn btn-outline-dark w-100 h-100 py-3 d-flex align-items-center justify-content-center gap-2">
                        <i class="bi bi-bag-check"></i>Service Siap Ambil
                    </a>
                </div>
                <div class="col-12 col-md-6 col-xl-3">
                    <a href="<?= site_url('admin/barang?stok=hampir-habis') ?>" class="btn btn-outline-dark w-100 h-100 py-3 d-flex align-items-center justify-content-center gap-2">
                        <i class="bi bi-box-seam"></i>Cek Stok Kritis
                    </a>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <div class="row g-3 mb-4">
        <div class="col-12 col-md-6 col-xl-3">
            <div class="panel p-3 h-100">
                <div class="d-flex justify-content-between gap-3">
                    <div>
                        <div class="small text-secondary">Penjualan Hari Ini</div>
                        <div class="h4 fw-bold mb-0"><?= esc($money($summary['total_penjualan_hari_ini'] ?? 0)) ?></div>
                        <div class="small text-secondary mt-1">
                            <?= esc((string) ($summary['penjualan_hari_ini'] ?? 0)) ?> transaksi
                            <?php if ($isAdministrator) : ?>
                                <span class="mx-1">.</span>Laba <?= esc($money($summary['laba_penjualan_hari_ini'] ?? 0)) ?>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="text-primary fs-3"><i class="bi bi-cart-check-fill"></i></div>
                </div>
            </div>
        </div>

        <div class="col-12 col-md-6 col-xl-3">
            <div class="panel p-3 h-100">
                <div class="d-flex justify-content-between gap-3">
                    <div>
                        <div class="small text-secondary">Service Hari Ini</div>
                        <div class="h4 fw-bold mb-0"><?= esc($money($summary['total_service_hari_ini'] ?? 0)) ?></div>
                        <div class="small text-secondary mt-1">
                            <?= esc((string) ($summary['service_hari_ini'] ?? 0)) ?> transaksi
                            <span class="mx-1">.</span>Jasa <?= esc($money($summary['pendapatan_jasa_hari_ini'] ?? 0)) ?>
                        </div>
                    </div>
                    <div class="text-success fs-3"><i class="bi bi-wrench-adjustable"></i></div>
                </div>
            </div>
        </div>

        
        <div class="col-12 col-md-6 col-xl-3">
            <div class="panel p-3 h-100">
                <div class="d-flex justify-content-between gap-3">
                    <div>
                        <div class="small text-secondary">Stok Kritis</div>
                        <div class="h4 fw-bold mb-0"><?= esc((string) ($summary['stok_hampir_habis'] ?? 0)) ?></div>
                        <div class="small text-secondary mt-1">
                            Stok kosong <?= esc((string) ($summary['stok_kosong'] ?? 0)) ?>
                            <span class="mx-1">.</span>Total item <?= esc((string) ($summary['total_barang'] ?? 0)) ?>
                        </div>
                    </div>
                    <div class="text-warning fs-3"><i class="bi bi-exclamation-triangle-fill"></i></div>
                </div>
            </div>
        </div>

        <div class="col-12 col-md-6 col-xl-3">
            <div class="panel p-3 h-100">
                <div class="d-flex justify-content-between gap-3">
                    <div>
                        <div class="small text-secondary">Total Item Barang</div>
                        <div class="h4 fw-bold mb-0"><?= esc((string) ($summary['total_barang'] ?? 0)) ?></div>
                        <div class="small text-secondary mt-1">
                            Total qty stok <?= esc((string) ($summary['total_qty_barang'] ?? 0)) ?>
                        </div>
                    </div>
                    <div class="text-primary fs-3"><i class="bi bi-box-seam-fill"></i></div>
                </div>
            </div>
        </div>

        <div class="col-12 col-md-6 col-xl-3">
            <div class="panel p-3 h-100">
                <div class="d-flex justify-content-between gap-3">
                    <div>
                        <div class="small text-secondary">Service Menunggu</div>
                        <div class="h4 fw-bold mb-0"><?= esc((string) ($summary['service_menunggu'] ?? 0)) ?></div>
                        <div class="small text-secondary mt-1">Belum mulai dikerjakan</div>
                    </div>
                    <div class="text-warning fs-3"><i class="bi bi-hourglass-split"></i></div>
                </div>
            </div>
        </div>

        <div class="col-12 col-md-6 col-xl-3">
            <div class="panel p-3 h-100">
                <div class="d-flex justify-content-between gap-3">
                    <div>
                        <div class="small text-secondary">Dalam Pengerjaan</div>
                        <div class="h4 fw-bold mb-0"><?= esc((string) ($summary['service_dalam_pengerjaan'] ?? 0)) ?></div>
                        <div class="small text-secondary mt-1">Sedang ditangani teknisi</div>
                    </div>
                    <div class="text-primary fs-3"><i class="bi bi-tools"></i></div>
                </div>
            </div>
        </div>

        <div class="col-12 col-md-6 col-xl-3">
            <div class="panel p-3 h-100">
                <div class="d-flex justify-content-between gap-3">
                    <div>
                        <div class="small text-secondary">Selesai Siap Ambil</div>
                        <div class="h4 fw-bold mb-0"><?= esc((string) ($summary['service_siap_ambil'] ?? 0)) ?></div>
                        <div class="small text-secondary mt-1">Menunggu pelanggan ambil</div>
                    </div>
                    <div class="text-info fs-3"><i class="bi bi-bag-check"></i></div>
                </div>
            </div>
        </div>

        <div class="col-12 col-md-6 col-xl-3">
            <div class="panel p-3 h-100">
                <div class="d-flex justify-content-between gap-3">
                    <div>
                        <div class="small text-secondary">Service Selesai</div>
                        <div class="h4 fw-bold mb-0"><?= esc((string) ($summary['service_selesai'] ?? 0)) ?></div>
                        <div class="small text-secondary mt-1">Sudah diambil pelanggan</div>
                    </div>
                    <div class="text-success fs-3"><i class="bi bi-check-circle-fill"></i></div>
                </div>
            </div>
        </div>


        <?php if ($isAdministrator) : ?>
            <div class="col-12 col-md-6 col-xl-3">
                <div class="panel p-3 h-100">
                    <div class="d-flex justify-content-between gap-3">
                        <div>
                            <div class="small text-secondary">Laba Bulan Ini</div>
                            <div class="h4 fw-bold mb-0"><?= esc($money($summary['total_laba_bulan_ini'] ?? 0)) ?></div>
                            <div class="small text-secondary mt-1">
                                Barang <?= esc($money($summary['laba_penjualan_bulan_ini'] ?? 0)) ?>,
                                service <?= esc($money($summary['laba_service_bulan_ini'] ?? 0)) ?>
                            </div>
                        </div>
                        <div class="text-success fs-3"><i class="bi bi-graph-up-arrow"></i></div>
                    </div>
                </div>
            </div>

            <div class="col-12 col-md-6 col-xl-3">
                <div class="panel p-3 h-100">
                    <div class="d-flex justify-content-between gap-3">
                        <div>
                            <div class="small text-secondary">Omzet Bulan Ini</div>
                            <div class="h4 fw-bold mb-0"><?= esc($money(($summary['total_penjualan_bulan_ini'] ?? 0) + ($summary['total_service_bulan_ini'] ?? 0))) ?></div>
                            <div class="small text-secondary mt-1">
                                Penjualan <?= esc($money($summary['total_penjualan_bulan_ini'] ?? 0)) ?>
                            </div>
                        </div>
                        <div class="text-primary fs-3"><i class="bi bi-cash-stack"></i></div>
                    </div>
                </div>
            </div>

            <div class="col-12 col-md-6 col-xl-3">
                <div class="panel p-3 h-100">
                    <div class="d-flex justify-content-between gap-3">
                        <div>
                            <div class="small text-secondary">Piutang Pelanggan</div>
                            <div class="h4 fw-bold mb-0"><?= esc($money(($summary['piutang_penjualan'] ?? 0) + ($summary['piutang_service'] ?? 0))) ?></div>
                            <div class="small text-secondary mt-1">
                                Penjualan <?= esc($money($summary['piutang_penjualan'] ?? 0)) ?>,
                                service <?= esc($money($summary['piutang_service'] ?? 0)) ?>
                            </div>
                        </div>
                        <div class="text-danger fs-3"><i class="bi bi-receipt-cutoff"></i></div>
                    </div>
                </div>
            </div>

            <div class="col-12 col-md-6 col-xl-3">
                <div class="panel p-3 h-100">
                    <div class="d-flex justify-content-between gap-3">
                        <div>
                            <div class="small text-secondary">Hutang Pembelian</div>
                            <div class="h4 fw-bold mb-0"><?= esc($money($summary['hutang_pembelian'] ?? 0)) ?></div>
                            <div class="small text-secondary mt-1">
                                Pembelian bulan ini <?= esc((string) ($summary['pembelian_bulan_ini'] ?? 0)) ?> transaksi
                            </div>
                        </div>
                        <div class="text-secondary fs-3"><i class="bi bi-box-arrow-in-down"></i></div>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <div class="row g-4 mb-4">
        <?php if ($isAdministrator) : ?>
            <div class="col-12">
                <div class="panel p-4 h-100">
                    <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-3">
                        <div>
                            <div class="fw-bold">Penjualan, Service, dan Laba Harian Bulan Ini</div>
                            <div class="small text-secondary">Nominal transaksi dan estimasi laba per hari pada bulan berjalan.</div>
                        </div>
                    </div>
                    <div style="height: 330px;">
                        <canvas id="salesProfitChart"></canvas>
                    </div>
                </div>
            </div>

            <div class="col-12">
                <div class="panel p-4 h-100">
                    <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-3">
                        <div>
                            <div class="fw-bold">Penjualan, Service, dan Laba Bulanan Tahun Ini</div>
                            <div class="small text-secondary">Rekap nominal transaksi dan estimasi laba per bulan dalam tahun berjalan.</div>
                        </div>
                    </div>
                    <div style="height: 330px;">
                        <canvas id="annualSalesProfitChart"></canvas>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <div class="col-12 col-xl-6">
            <div class="panel p-4 h-100">
                <div class="fw-bold mb-1">Status Service Aktif</div>
                <div class="small text-secondary mb-3">Pekerjaan yang belum selesai diambil pelanggan.</div>
                <div style="height: 330px;">
                    <canvas id="serviceStatusChart"></canvas>
                </div>
            </div>
        </div>

        <div class="col-12 col-xl-6">
            <div class="panel p-4 h-100">
                <div class="fw-bold mb-1">Stok per Kategori</div>
                <div class="small text-secondary mb-3">Total qty stok berdasarkan kategori barang.</div>
                <div style="height: 330px;">
                    <canvas id="stockByCategoryChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-4 mb-4">
        <div class="col-12 col-xl-6">
            <div class="panel p-4 h-100">
                <div class="d-flex align-items-center justify-content-between gap-3 mb-3">
                    <div>
                        <div class="fw-bold">Antrian Service Aktif</div>
                        <div class="small text-secondary">Service yang perlu ditindaklanjuti.</div>
                    </div>
                    <a href="<?= site_url('admin/service') ?>" class="btn btn-sm btn-outline-dark">Lihat</a>
                </div>
                <div class="table-responsive">
                    <table class="table table-sm align-middle mb-0">
                        <thead>
                            <tr>
                                <th>Transaksi</th>
                                <th>Objek</th>
                                <th>Teknisi</th>
                                <th class="text-center">Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach (($activeServices ?? []) as $item) : ?>
                                <tr>
                                    <td>
                                        <a class="fw-semibold text-decoration-none" href="<?= site_url('admin/service/detail/' . $item['id']) ?>"><?= esc($item['no_transaksi']) ?></a>
                                        <div class="small text-secondary"><?= esc($item['nama_pelanggan'] ?? '-') ?></div>
                                    </td>
                                    <td>
                                        <?= esc($item['merk_tipe'] ?: '-') ?>
                                        <div class="small text-secondary"><?= esc($item['nomor_objek'] ?: '-') ?></div>
                                    </td>
                                    <td><?= esc($item['nama_teknisi'] ?? '-') ?></td>
                                    <td class="text-center"><span class="badge <?= esc($serviceStatusBadges[$item['status_service'] ?? 'menunggu'] ?? 'text-bg-secondary', 'attr') ?>"><?= esc($serviceStatusLabels[$item['status_service'] ?? 'menunggu'] ?? '-') ?></span></td>
                                </tr>
                            <?php endforeach; ?>
                            <?php if (empty($activeServices)) : ?>
                                <tr><td colspan="4" class="text-center text-secondary py-4">Tidak ada service aktif.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="col-12 col-xl-6">
            <div class="panel p-4 h-100">
                <div class="d-flex align-items-center justify-content-between gap-3 mb-3">
                    <div>
                        <div class="fw-bold">Stok Hampir Habis</div>
                        <div class="small text-secondary">Barang dengan stok paling rendah.</div>
                    </div>
                    <?php if ($isOperationalRole) : ?>
                        <a href="<?= site_url('admin/barang?stok=hampir-habis') ?>" class="btn btn-sm btn-outline-dark">Lihat</a>
                    <?php endif; ?>
                </div>
                <div class="table-responsive">
                    <table class="table table-sm align-middle mb-0">
                        <thead>
                            <tr>
                                <th>Barang</th>
                                <th>Lokasi</th>
                                <th class="text-end">Stok</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach (($lowStockItems ?? []) as $item) : ?>
                                <tr>
                                    <td>
                                        <span class="fw-semibold d-block"><?= esc($item['kode_barang']) ?></span>
                                        <?= esc($item['nama_barang']) ?>
                                    </td>
                                    <td><?= ! empty($item['lokasi_barang']) ? esc($item['lokasi_barang']) : '<span class="text-secondary">-</span>' ?></td>
                                    <td class="text-end">
                                        <span class="badge text-bg-warning"><?= esc((string) $item['stok']) ?> <?= esc($item['satuan']) ?></span>
                                        <div class="small text-secondary">Min. <?= esc((string) $item['stok_minimum']) ?></div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                            <?php if (empty($lowStockItems)) : ?>
                                <tr><td colspan="3" class="text-center text-secondary py-4">Tidak ada stok hampir habis.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <?php if ($isAdministrator) : ?>
        <div class="row g-4 mb-4">
            <div class="col-12 col-xl-6">
                <div class="panel p-4 h-100">
                    <div class="fw-bold mb-1">Barang/Part Terlaris Bulan Ini</div>
                    <div class="small text-secondary mb-3">Grafik horizontal qty barang dari penjualan biasa dan part yang dipakai di service.</div>
                    <div style="height: 360px;">
                        <canvas id="topProductsChart"></canvas>
                    </div>
                    <?php if (empty($topProducts)) : ?>
                        <div class="text-center text-secondary py-3">Belum ada barang terjual bulan ini.</div>
                    <?php endif; ?>
                    <div class="row g-3 mt-2">
                        <?php foreach (($topProducts ?? []) as $item) : ?>
                            <div class="col-12 col-md-6 col-xl-4">
                                <div class="border rounded-2 p-3 h-100">
                                    <div class="fw-semibold text-truncate"><?= esc($item['nama_barang']) ?></div>
                                    <div class="small text-secondary"><?= esc($item['kode_barang']) ?> . <?= esc($number($item['total_qty'] ?? 0)) ?> <?= esc($item['satuan'] ?? '') ?></div>
                                    <div class="small text-secondary mt-2">Omzet <?= esc($money($item['total_omzet'] ?? 0)) ?> . Laba <?= esc($money($item['total_laba'] ?? 0)) ?></div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>

            <div class="col-12 col-xl-6">
                <div class="panel p-4 h-100">
                    <div class="fw-bold mb-1">Jasa Terlaris Bulan Ini</div>
                    <div class="small text-secondary mb-3">Grafik horizontal jumlah jasa yang dipakai pada transaksi service.</div>
                    <div style="height: 360px;">
                        <canvas id="topServicesChart"></canvas>
                    </div>
                    <?php if (empty($topServices)) : ?>
                        <div class="text-center text-secondary py-3">Belum ada jasa service bulan ini.</div>
                    <?php endif; ?>
                    <div class="row g-3 mt-2">
                        <?php foreach (($topServices ?? []) as $item) : ?>
                            <div class="col-12 col-md-6">
                                <div class="border rounded-2 p-3 h-100">
                                    <div class="fw-semibold text-truncate"><?= esc($item['nama_jasa']) ?></div>
                                    <div class="small text-secondary"><?= esc((string) ($item['total_transaksi'] ?? 0)) ?> transaksi</div>
                                    <div class="small text-secondary mt-2">Pendapatan <?= esc($money($item['total_omzet'] ?? 0)) ?></div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>
</section>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        if (! window.Chart) {
            return;
        }

        const chartData = <?= json_encode($chartData ?? [], JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?>;
        const gridColor = 'rgba(16, 24, 40, 0.08)';
        const labelColor = '#475467';
        const rupiah = new Intl.NumberFormat('id-ID', {
            style: 'currency',
            currency: 'IDR',
            maximumFractionDigits: 0
        });
        const number = new Intl.NumberFormat('id-ID', { maximumFractionDigits: 0 });
        const commonOptions = {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    labels: {
                        boxWidth: 12,
                        boxHeight: 12,
                        color: labelColor
                    }
                }
            },
            scales: {
                x: {
                    grid: { display: false },
                    ticks: { color: labelColor }
                },
                y: {
                    beginAtZero: true,
                    grid: { color: gridColor },
                    ticks: {
                        color: labelColor,
                        callback: function (value) {
                            return rupiah.format(value).replace('Rp', 'Rp ');
                        }
                    }
                }
            }
        };

        const salesProfitCanvas = document.getElementById('salesProfitChart');

        if (salesProfitCanvas) {
            new Chart(salesProfitCanvas, {
                data: {
                    labels: chartData.salesProfit?.labels || [],
                    datasets: [
                        {
                            type: 'bar',
                            label: 'Penjualan',
                            data: chartData.salesProfit?.penjualan || [],
                            backgroundColor: 'rgba(37, 99, 235, 0.76)',
                            borderRadius: 6
                        },
                        {
                            type: 'bar',
                            label: 'Service',
                            data: chartData.salesProfit?.service || [],
                            backgroundColor: 'rgba(22, 163, 74, 0.76)',
                            borderRadius: 6
                        },
                        {
                            type: 'line',
                            label: 'Laba',
                            data: chartData.salesProfit?.laba || [],
                            borderColor: '#f59e0b',
                            backgroundColor: 'rgba(245, 158, 11, 0.12)',
                            borderWidth: 2,
                            tension: 0.35,
                            pointRadius: 3,
                            fill: false
                        }
                    ]
                },
                options: commonOptions
            });
        }

        const annualSalesProfitCanvas = document.getElementById('annualSalesProfitChart');

        if (annualSalesProfitCanvas) {
            new Chart(annualSalesProfitCanvas, {
                data: {
                    labels: chartData.annualSalesProfit?.labels || [],
                    datasets: [
                        {
                            type: 'bar',
                            label: 'Penjualan',
                            data: chartData.annualSalesProfit?.penjualan || [],
                            backgroundColor: 'rgba(37, 99, 235, 0.76)',
                            borderRadius: 6
                        },
                        {
                            type: 'bar',
                            label: 'Service',
                            data: chartData.annualSalesProfit?.service || [],
                            backgroundColor: 'rgba(22, 163, 74, 0.76)',
                            borderRadius: 6
                        },
                        {
                            type: 'line',
                            label: 'Laba',
                            data: chartData.annualSalesProfit?.laba || [],
                            borderColor: '#f59e0b',
                            backgroundColor: 'rgba(245, 158, 11, 0.12)',
                            borderWidth: 2,
                            tension: 0.35,
                            pointRadius: 3,
                            fill: false
                        }
                    ]
                },
                options: commonOptions
            });
        }

        const topProductsCanvas = document.getElementById('topProductsChart');

        if (topProductsCanvas) {
            new Chart(topProductsCanvas, {
                type: 'bar',
                data: {
                    labels: chartData.topProducts?.labels || [],
                    datasets: [
                        {
                            label: 'Qty Terjual',
                            data: chartData.topProducts?.qty || [],
                            backgroundColor: 'rgba(37, 99, 235, 0.78)',
                            borderRadius: 6,
                            barThickness: 26
                        }
                    ]
                },
                options: {
                    indexAxis: 'y',
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            callbacks: {
                                afterLabel: function (context) {
                                    const index = context.dataIndex;
                                    const omzet = chartData.topProducts?.omzet?.[index] || 0;
                                    const laba = chartData.topProducts?.laba?.[index] || 0;

                                    return [
                                        'Omzet: ' + rupiah.format(omzet).replace('Rp', 'Rp '),
                                        'Laba: ' + rupiah.format(laba).replace('Rp', 'Rp ')
                                    ];
                                }
                            }
                        }
                    },
                    scales: {
                        x: {
                            beginAtZero: true,
                            grid: { color: gridColor },
                            ticks: {
                                color: labelColor,
                                precision: 0,
                                callback: function (value) {
                                    return number.format(value);
                                }
                            }
                        },
                        y: {
                            grid: { display: false },
                            ticks: {
                                color: labelColor
                            }
                        }
                    }
                }
            });
        }

        const topServicesCanvas = document.getElementById('topServicesChart');

        if (topServicesCanvas) {
            new Chart(topServicesCanvas, {
                type: 'bar',
                data: {
                    labels: chartData.topServices?.labels || [],
                    datasets: [
                        {
                            label: 'Jumlah Transaksi',
                            data: chartData.topServices?.qty || [],
                            backgroundColor: 'rgba(22, 163, 74, 0.78)',
                            borderRadius: 6,
                            barThickness: 26
                        }
                    ]
                },
                options: {
                    indexAxis: 'y',
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            callbacks: {
                                afterLabel: function (context) {
                                    const index = context.dataIndex;
                                    const omzet = chartData.topServices?.omzet?.[index] || 0;

                                    return 'Pendapatan: ' + rupiah.format(omzet).replace('Rp', 'Rp ');
                                }
                            }
                        }
                    },
                    scales: {
                        x: {
                            beginAtZero: true,
                            grid: { color: gridColor },
                            ticks: {
                                color: labelColor,
                                precision: 0,
                                callback: function (value) {
                                    return number.format(value);
                                }
                            }
                        },
                        y: {
                            grid: { display: false },
                            ticks: {
                                color: labelColor
                            }
                        }
                    }
                }
            });
        }

        const serviceStatusCanvas = document.getElementById('serviceStatusChart');

        if (serviceStatusCanvas) {
            new Chart(serviceStatusCanvas, {
                type: 'doughnut',
                data: {
                    labels: chartData.serviceStatus?.labels || [],
                    datasets: [
                        {
                            data: chartData.serviceStatus?.values || [],
                            backgroundColor: ['#f59e0b', '#2563eb', '#0891b2'],
                            borderWidth: 0
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                boxWidth: 12,
                                boxHeight: 12,
                                color: labelColor
                            }
                        },
                        tooltip: {
                            callbacks: {
                                label: function (context) {
                                    return context.label + ': ' + number.format(context.parsed);
                                }
                            }
                        }
                    },
                    cutout: '62%'
                }
            });
        }

        const categoryCanvas = document.getElementById('stockByCategoryChart');

        if (categoryCanvas) {
            new Chart(categoryCanvas, {
                type: 'doughnut',
                data: {
                    labels: chartData.stockByCategory?.labels || [],
                    datasets: [
                        {
                            data: chartData.stockByCategory?.values || [],
                            backgroundColor: ['#2563eb', '#16a34a', '#f59e0b', '#dc2626', '#7c3aed', '#0891b2', '#4b5563', '#ea580c'],
                            borderWidth: 0
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                boxWidth: 12,
                                boxHeight: 12,
                                color: labelColor
                            }
                        },
                        tooltip: {
                            callbacks: {
                                label: function (context) {
                                    return context.label + ': ' + number.format(context.parsed);
                                }
                            }
                        }
                    },
                    cutout: '62%'
                }
            });
        }
    });
</script>

<?= view('admin/layouts/footer') ?>
