<div class="hero">
    <div>
        <h2 style="margin:0 0 6px;">Selamat datang, <?= esc($user['name']) ?></h2>
        <p style="margin:0; opacity:0.95;">Pantau performa penjualan barber dari satu panel yang fokus.</p>
    </div>
</div>

<div class="grid">
    <div class="stat-card">
        <span class="stat-icon green"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="1" x2="12" y2="23"></line><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"></path></svg></span>
        <div>
            <h3>Penjualan Hari Ini</h3>
            <div class="big">Rp <?= number_format($dashboardStats['todaySales'], 0, ',', '.') ?></div>
        </div>
    </div>
    <div class="stat-card">
        <span class="stat-icon blue"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="20" x2="18" y2="10"></line><line x1="12" y1="20" x2="12" y2="4"></line><line x1="6" y1="20" x2="6" y2="14"></line></svg></span>
        <div>
            <h3>Penjualan Bulan Ini</h3>
            <div class="big">Rp <?= number_format($dashboardStats['monthlySales'], 0, ',', '.') ?></div>
        </div>
    </div>
    <div class="stat-card">
        <span class="stat-icon violet"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 11l3 3L22 4"></path><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"></path></svg></span>
        <div>
            <h3>Total Transaksi</h3>
            <div class="big"><?= esc($stats['transactionCount']) ?></div>
        </div>
    </div>
    <div class="stat-card">
        <span class="stat-icon amber"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20.59 13.41L11 3.83V3H3v8h.83l9.58 9.59a2 2 0 0 0 2.83 0l4.35-4.35a2 2 0 0 0 0-2.83z"></path><circle cx="6.5" cy="6.5" r="1.5"></circle></svg></span>
        <div>
            <h3>Promo Digunakan Hari Ini</h3>
            <div class="big"><?= esc($promoUsageToday) ?></div>
        </div>
    </div>
    <div class="stat-card">
        <span class="stat-icon blue"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="9" cy="7" r="4"></circle><path d="M23 21v-2a4 4 0 0 0-3-3.87"></path><path d="M16 3.13a4 4 0 0 1 0 7.75"></path></svg></span>
        <div>
            <h3>Total Member</h3>
            <div class="big"><?= esc($totalMembers) ?></div>
        </div>
    </div>
</div>

<?php
$paymentIcons = [
    'cash' => '<rect x="2" y="6" width="20" height="12" rx="2"></rect><circle cx="12" cy="12" r="2"></circle><path d="M6 12h.01"></path><path d="M18 12h.01"></path>',
    'debit' => '<rect x="1" y="4" width="22" height="16" rx="2" ry="2"></rect><line x1="1" y1="10" x2="23" y2="10"></line>',
    'qris' => '<rect x="3" y="3" width="7" height="7"></rect><rect x="14" y="3" width="7" height="7"></rect><rect x="3" y="14" width="7" height="7"></rect><path d="M14 14h3v3h-3zM19 14h2v2h-2zM14 19h2v2h-2zM19 19h2v2h-2z"></path>',
    'transfer' => '<polyline points="17 1 21 5 17 9"></polyline><path d="M3 11V9a4 4 0 0 1 4-4h14"></path><polyline points="7 23 3 19 7 15"></polyline><path d="M21 13v2a4 4 0 0 1-4 4H3"></path>',
];
$paymentColors = ['cash' => 'green', 'debit' => 'blue', 'qris' => 'violet', 'transfer' => 'amber'];
?>
<div class="panel">
    <span class="pill">Pembayaran Hari Ini</span>
    <h3 style="margin:6px 0 14px;">Total penjualan hari ini berdasarkan metode bayar</h3>
    <div class="grid" style="margin-bottom:0;">
        <?php foreach ($dashboardStats['paymentBreakdown'] as $payment) : ?>
            <div class="stat-card">
                <span class="stat-icon <?= esc($paymentColors[$payment['method']] ?? 'green') ?>"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><?= $paymentIcons[$payment['method']] ?? '' ?></svg></span>
                <div>
                    <h3><?= esc($payment['label']) ?></h3>
                    <div class="big">Rp <?= number_format($payment['total'], 0, ',', '.') ?></div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>

<div class="panel">
    <div style="display:flex; flex-wrap:wrap; gap:12px; align-items:center; justify-content:space-between; margin-bottom:12px;">
        <div>
            <span class="pill">Grafik Penjualan</span>
            <h3 style="margin:6px 0 0;">Grafik penjualan berdasarkan filter</h3>
        </div>
        <div style="display:flex; gap:10px; flex-wrap:wrap;">
            <select id="rangeFilter" style="min-width:140px;">
                <option value="weekly" <?= ($selectedRange ?? 'weekly') === 'weekly' ? 'selected' : '' ?>>Mingguan</option>
                <option value="monthly" <?= ($selectedRange ?? 'weekly') === 'monthly' ? 'selected' : '' ?>>Bulanan</option>
                <option value="yearly" <?= ($selectedRange ?? 'weekly') === 'yearly' ? 'selected' : '' ?>>Tahunan</option>
            </select>
            <select id="barberFilter" style="min-width:180px;">
                <option value="">Semua Barber</option>
                <?php foreach ($barbers as $barber) : ?>
                    <option value="<?= esc($barber['name']) ?>" <?= ($selectedBarber ?? '') === $barber['name'] ? 'selected' : '' ?>><?= esc($barber['name']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
    </div>
    <canvas id="salesChart" height="140"></canvas>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
window.addEventListener('DOMContentLoaded', function () {
    const ctx = document.getElementById('salesChart');
    if (!ctx) return;
    let chart;
    const renderChart = (labels, values) => {
        if (chart) chart.destroy();
        chart = new Chart(ctx, {
            type: 'line',
            data: {
                labels,
                datasets: [{
                    label: 'Penjualan',
                    data: values,
                    borderColor: '#2563eb',
                    backgroundColor: 'rgba(37, 99, 235, 0.15)',
                    fill: true,
                    tension: 0.3,
                    pointRadius: 4
                }]
            },
            options: { responsive: true, scales: { y: { beginAtZero: true } } }
        });
    };

    const fetchData = () => {
        const range = document.getElementById('rangeFilter').value;
        const barber = document.getElementById('barberFilter').value;
        fetch(`/dashboard/chart-data?range=${range}&barber=${encodeURIComponent(barber)}`)
            .then(response => response.json())
            .then(data => renderChart(data.labels || [], data.data || []));
    };

    document.getElementById('rangeFilter').addEventListener('change', fetchData);
    document.getElementById('barberFilter').addEventListener('change', fetchData);
    fetchData();
});
</script>

<div class="panel">
    <span class="pill">Jam Tersibuk Hari Ini</span>
    <h3 style="margin:6px 0 0;">Grafik penjualan hari ini berdasarkan jam</h3>
    <?php if (($hourlyChart['busiestCount'] ?? 0) > 0) : ?>
        <p class="muted" style="margin:4px 0 12px;">Jam paling ramai: <strong style="color:var(--text);"><?= esc($hourlyChart['busiestLabel']) ?></strong> dengan <strong style="color:var(--text);"><?= esc($hourlyChart['busiestCount']) ?></strong> transaksi.</p>
    <?php else : ?>
        <p class="muted" style="margin:4px 0 12px;">Belum ada transaksi hari ini.</p>
    <?php endif; ?>
    <canvas id="hourlyChart" height="140"></canvas>
</div>

<script>
window.addEventListener('DOMContentLoaded', function () {
    const hourlyCtx = document.getElementById('hourlyChart');
    if (!hourlyCtx) return;
    new Chart(hourlyCtx, {
        type: 'bar',
        data: {
            labels: <?= json_encode($hourlyChart['labels']) ?>,
            datasets: [{
                label: 'Jumlah Transaksi',
                data: <?= json_encode($hourlyChart['counts']) ?>,
                backgroundColor: '#2563eb',
                borderRadius: 6
            }]
        },
        options: {
            responsive: true,
            scales: { y: { beginAtZero: true, ticks: { stepSize: 1 } } },
            plugins: { legend: { display: false } }
        }
    });
});
</script>

<div class="panel">
    <span class="pill">Promo Aktif Hari Ini</span>
    <h3 style="margin:6px 0 14px;">Katalog reward yang bisa ditukar member hari ini</h3>
    <?php if (empty($activePromosToday)) : ?>
        <p class="muted" style="margin:0;">Tidak ada promo yang aktif hari ini.</p>
    <?php else : ?>
        <div class="table-wrap">
            <table>
                <thead>
                    <tr><th>Nama Promo</th><th>Layanan/Produk</th><th>Diskon</th><th>Poin Dibutuhkan</th><th>Periode</th></tr>
                </thead>
                <tbody>
                    <?php foreach ($activePromosToday as $promo) : ?>
                        <tr>
                            <td><?= esc($promo['name']) ?></td>
                            <td><?= esc($promo['item_name'] ?? '-') ?></td>
                            <td><?= $promo['discount_type'] === 'percent' ? esc($promo['discount_value']) . '%' : 'Rp ' . esc(number_format((int) $promo['discount_value'], 0, ',', '.')) ?></td>
                            <td><span class="pill" style="margin:0;"><?= esc(number_format((int) $promo['points_required'], 0, ',', '.')) ?> poin</span></td>
                            <td>
                                <?php if (!empty($promo['start_date']) || !empty($promo['end_date'])) : ?>
                                    <?= $promo['start_date'] ? esc(date('d/m/Y', strtotime($promo['start_date']))) : '-' ?>
                                    s/d
                                    <?= $promo['end_date'] ? esc(date('d/m/Y', strtotime($promo['end_date']))) : '-' ?>
                                <?php else : ?>
                                    <span class="muted">Selalu berlaku</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

<div class="panel">
    <span class="pill">Layanan Paling Laku</span>
    <h3>Jasa / produk yang paling sering dipesan</h3>
    <ul class="muted">
        <?php foreach ($dashboardStats['topServices'] as $service) : ?>
            <li><?= esc($service['name']) ?> — <?= esc($service['count']) ?> transaksi</li>
        <?php endforeach; ?>
    </ul>
</div>
