<?= $this->extend('layouts/main_layout') ?>
<?= $this->section('content') ?>

<div class="flex justify-between items-center mb-7">
    <div>
        <h1 class="text-2xl font-bold text-gray-900">Dashboard</h1>
        <p class="text-sm text-gray-500 mt-0.5">Panel de control administrativo</p>
    </div>
</div>

<div class="grid grid-cols-1 md:grid-cols-4 gap-5 mb-7">
    <a href="<?= site_url('products') ?>" class="bg-[#EBDF00] rounded-xl shadow-sm border-l-4 border-[#D4C800] p-5 no-underline block card-hover">
        <div class="flex justify-between items-start">
            <div>
                <p class="text-gray-500 text-xs font-semibold uppercase tracking-wide">Total Productos</p>
                <p class="text-3xl font-extrabold text-gray-900 mt-1.5"><?= $totalProducts ?></p>
            </div>
            <div class="w-12 h-12 bg-[#D4C800] rounded-xl flex items-center justify-center">
                <i class="bi bi-box-seam text-xl text-gray-900"></i>
            </div>
        </div>
    </a>
    <a href="<?= site_url('sales') ?>" class="bg-emerald-300 rounded-xl shadow-sm border-l-4 border-emerald-500 p-5 no-underline block card-hover">
        <div class="flex justify-between items-start">
            <div>
                <p class="text-gray-500 text-xs font-semibold uppercase tracking-wide">Ventas Hoy</p>
                <p class="text-3xl font-extrabold text-gray-900 mt-1.5">S/ <?= number_format($totalSalesToday, 2) ?></p>
            </div>
            <div class="w-12 h-12 bg-emerald-200 rounded-xl flex items-center justify-center">
                <i class="bi bi-cart-check text-xl text-emerald-700"></i>
            </div>
        </div>
    </a>
    <a href="<?= site_url('products?stock_bajo=1') ?>" class="bg-red-300 rounded-xl shadow-sm border-l-4 border-red-500 p-5 no-underline block card-hover">
        <div class="flex justify-between items-start">
            <div>
                <p class="text-gray-500 text-xs font-semibold uppercase tracking-wide">Stock Bajo</p>
                <p class="text-3xl font-extrabold text-gray-900 mt-1.5"><?= $lowStockCount ?></p>
            </div>
            <div class="w-12 h-12 bg-red-400 rounded-xl flex items-center justify-center">
                <i class="bi bi-exclamation-triangle text-xl text-red-700"></i>
            </div>
        </div>
    </a>
    <a href="<?= site_url('users') ?>" class="bg-violet-300 rounded-xl shadow-sm border-l-4 border-violet-600 p-5 no-underline block card-hover">
        <div class="flex justify-between items-start">
            <div>
                <p class="text-gray-500 text-xs font-semibold uppercase tracking-wide">Total Usuarios</p>
                <p class="text-3xl font-extrabold text-gray-900 mt-1.5"><?= $totalUsers ?></p>
            </div>
            <div class="w-12 h-12 bg-violet-400 rounded-xl flex items-center justify-center">
                <i class="bi bi-people text-xl text-gray-900"></i>
            </div>
        </div>
    </a>
</div>

<?php if ($lowStockCount > 0): ?>
<div class="bg-red-100 border border-red-200 rounded-xl p-4 mb-7 flex items-center gap-3">
    <span class="w-9 h-9 rounded-lg bg-rose-100 flex items-center justify-center text-red-700"><i class="bi bi-exclamation-circle text-lg"></i></span>
    <span class="text-sm font-medium text-red-800"><strong>Stock minimo alcanzado!</strong> Hay <?= $lowStockCount ?> producto(s) con stock menor o igual a 5.</span>
    <a href="<?= site_url('products?stock_bajo=1') ?>" class="bg-red-600 hover:bg-red-700 text-white text-sm font-semibold px-5 py-2 rounded-lg no-underline ml-auto whitespace-nowrap flex items-center gap-2 flex-shrink-0 transition">Ver productos <i class="bi bi-arrow-right"></i></a>
</div>
<?php endif; ?>

<div class="grid grid-cols-1 lg:grid-cols-3 gap-5 mb-6">
    <div class="lg:col-span-2 bg-teal-300 rounded-xl shadow-sm p-6">
        <div class="flex items-center gap-2.5 mb-5">
            <div class="w-9 h-9 bg-teal-400 rounded-lg flex items-center justify-center text-white"><i class="bi bi-bar-chart-line text-lg"></i></div>
            <h3 class="font-semibold text-gray-900">Ventas Ultimos 7 Dias</h3>
        </div>
        <canvas id="salesWeekChart" height="140"></canvas>
    </div>
    <div class="bg-fuchsia-300 rounded-xl shadow-sm p-6">
        <div class="flex items-center gap-2.5 mb-5">
            <div class="w-9 h-9 bg-fuchsia-400 rounded-lg flex items-center justify-center text-white"><i class="bi bi-pie-chart text-lg"></i></div>
            <h3 class="font-semibold text-gray-900">Ventas por Categoria</h3>
        </div>
        <canvas id="categoryChart" height="180"></canvas>
    </div>
</div>

<div class="grid grid-cols-1 lg:grid-cols-3 gap-5 mb-6">
    <div class="bg-green-300 rounded-xl shadow-sm p-6">
        <div class="flex items-center gap-2.5 mb-5">
            <div class="w-9 h-9 bg-green-400 rounded-lg flex items-center justify-center text-white"><i class="bi bi-credit-card-2-front text-lg"></i></div>
            <h3 class="font-semibold text-gray-900">Forma de Pago</h3>
        </div>
        <canvas id="paymentChart" height="180"></canvas>
    </div>
    <div class="lg:col-span-2 bg-slate-100 rounded-xl shadow-sm overflow-hidden">
        <div class="px-6 py-4 border-b border-gray-100">
            <h5 class="font-semibold text-gray-900 flex items-center gap-2">
                <div class="w-9 h-9 bg-slate-200 rounded-lg flex items-center justify-center text-slate-600"><i class="bi bi-clock-history text-lg"></i></div>
                Ventas Recientes
            </h5>
        </div>
        <div class="overflow-x-auto">
            <table class="w-full text-sm">
                <thead>
                    <tr class="border-b border-gray-100">
                        <th class="text-left px-6 py-3.5 font-semibold text-gray-500 text-xs uppercase tracking-wider">#</th>
                        <th class="text-left px-6 py-3.5 font-semibold text-gray-500 text-xs uppercase tracking-wider">Fecha</th>
                        <th class="text-left px-6 py-3.5 font-semibold text-gray-500 text-xs uppercase tracking-wider">Usuario</th>
                        <th class="text-right px-6 py-3.5 font-semibold text-gray-500 text-xs uppercase tracking-wider">Total</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-50">
                    <?php if (empty($recentSales)): ?>
                    <tr>
                        <td colspan="4" class="text-center text-gray-400 py-10">
                            <i class="bi bi-inbox text-3xl block mb-2 opacity-40"></i>
                            <span class="text-sm">No hay ventas registradas</span>
                        </td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($recentSales as $sale): ?>
                    <tr class="hover:bg-gray-50 transition-colors">
                        <td class="px-6 py-3.5"><span class="bg-emerald-100 text-emerald-700 text-xs font-semibold px-2.5 py-1 rounded-lg">#<?= $sale['id_venta'] ?></span></td>
                        <td class="px-6 py-3.5 text-gray-600"><?= date('d/m/Y H:i', strtotime($sale['fecha'])) ?></td>
                        <td class="px-6 py-3.5 text-gray-600"><?= $sale['username'] ?></td>
                        <td class="px-6 py-3.5 text-right font-extrabold text-gray-900">S/ <?= number_format($sale['total'], 2) ?></td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
<?php
$weekLabels = json_encode($chartSalesWeek['labels']);
$weekData = json_encode($chartSalesWeek['data']);
$catLabels = json_encode(array_column($chartCategory, 'label'));
$catValues = json_encode(array_column($chartCategory, 'value'));
$payLabels = json_encode(array_column($chartPayment, 'label'));
$payValues = json_encode(array_column($chartPayment, 'value'));
?>

Chart.defaults.locale = 'es';
Chart.defaults.font.family = "'Inter', sans-serif";

const chartColors = ['#033A40','#F59E0B','#EF4444','#D946EF','#8B5CF6','#F43F5E','#10B981'];

new Chart(document.getElementById('salesWeekChart'), {
    type: 'line',
    data: {
        labels: <?= $weekLabels ?>,
        datasets: [{
            label: 'Ventas (S/)',
            data: <?= $weekData ?>,
            borderColor: '#033A40',
            backgroundColor: function(ctx) {
                const g = ctx.chart.ctx.createLinearGradient(0, 0, 0, ctx.chart.height);
                g.addColorStop(0, 'rgba(3,58,64,0.2)');
                g.addColorStop(1, 'rgba(3,58,64,0.02)');
                return g;
            },
            fill: true, tension: 0.4,
            pointBackgroundColor: '#033A40', pointBorderColor: '#fff', pointBorderWidth: 3, pointRadius: 5, pointHoverRadius: 7,
            borderWidth: 3,
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: { display: false },
            tooltip: { backgroundColor: '#1e293b', titleColor: '#fff', bodyColor: '#fff', padding: 12, cornerRadius: 12, callbacks: { label: function(ctx) { return 'S/ ' + ctx.parsed.y.toFixed(2); } } }
        },
        scales: {
            y: { beginAtZero: true, grid: { color: 'rgba(0,0,0,0.04)', drawBorder: false }, ticks: { color: '#6b7280' } },
            x: { grid: { display: false }, ticks: { color: '#6b7280' } }
        }
    }
});

new Chart(document.getElementById('categoryChart'), {
    type: 'doughnut',
    data: {
        labels: <?= $catLabels ?>,
        datasets: [{ data: <?= $catValues ?>, backgroundColor: chartColors.slice(0, <?= count($chartCategory) ?>), borderWidth: 0, hoverOffset: 10 }]
    },
    options: {
        responsive: true, cutout: '70%',
        plugins: {
            legend: { position: 'bottom', labels: { boxWidth: 10, padding: 14, font: { size: 11 }, usePointStyle: true } },
            tooltip: { backgroundColor: '#1e293b', titleColor: '#fff', bodyColor: '#fff', padding: 12, cornerRadius: 12, callbacks: { label: function(ctx) { var t = ctx.dataset.data.reduce(function(a,b){return a+b}, 0); return ctx.label + ': S/ ' + ctx.parsed.toFixed(2) + ' (' + ((ctx.parsed/t)*100).toFixed(1) + '%)'; } } }
        }
    }
});

new Chart(document.getElementById('paymentChart'), {
    type: 'doughnut',
    data: {
        labels: <?= $payLabels ?>,
        datasets: [{ data: <?= $payValues ?>, backgroundColor: ['#EF4444','#F59E0B','#10B981','#8B5CF6'], borderWidth: 0, hoverOffset: 10 }]
    },
    options: {
        responsive: true, cutout: '70%',
        plugins: {
            legend: { position: 'bottom', labels: { boxWidth: 10, padding: 14, font: { size: 11 }, usePointStyle: true } },
            tooltip: { backgroundColor: '#1e293b', titleColor: '#fff', bodyColor: '#fff', padding: 12, cornerRadius: 12, callbacks: { label: function(ctx) { var t = ctx.dataset.data.reduce(function(a,b){return a+b}, 0); return ctx.label + ': S/ ' + ctx.parsed.toFixed(2) + ' (' + ((ctx.parsed/t)*100).toFixed(1) + '%)'; } } }
        }
    }
});
</script>

<?= $this->endSection() ?>
