<?php
/**
 * Dashboard del Administrador
 * Sistema de Gestión de Agua Mineral
 */

require_once '../../includes/init.php';

// Verificar que sea administrador
checkPermission('administrador');

$pageTitle = 'Dashboard - Administrador';

// Obtener estadísticas generales
$db = Database::getInstance();

// Total de clientes
$totalClientes = $db->select("SELECT COUNT(*) as total FROM clientes WHERE activo = 1")[0]['total'];

// Total de vendedores
$totalVendedores = $db->select("SELECT COUNT(*) as total FROM usuarios WHERE rol = 'vendedor' AND activo = 1")[0]['total'];

// Ventas del mes actual
$ventasMes = $db->select("
    SELECT 
        COUNT(*) as total_entregas,
        COALESCE(SUM(cantidad_bidones), 0) as total_bidones,
        COALESCE(SUM(total), 0) as total_ingresos
    FROM ventas 
    WHERE MONTH(fecha) = MONTH(CURDATE()) 
    AND YEAR(fecha) = YEAR(CURDATE())
")[0];

// Ventas del mes anterior para comparación
$ventasMesAnterior = $db->select("
    SELECT 
        COUNT(*) as total_entregas,
        COALESCE(SUM(cantidad_bidones), 0) as total_bidones,
        COALESCE(SUM(total), 0) as total_ingresos
    FROM ventas 
    WHERE MONTH(fecha) = MONTH(DATE_SUB(CURDATE(), INTERVAL 1 MONTH))
    AND YEAR(fecha) = YEAR(DATE_SUB(CURDATE(), INTERVAL 1 MONTH))
")[0];

// Calcular porcentajes de cambio usando función segura
$cambioEntregas = calcularCambioSeguro($ventasMes['total_entregas'], $ventasMesAnterior['total_entregas']);
$cambioBidones = calcularCambioSeguro($ventasMes['total_bidones'], $ventasMesAnterior['total_bidones']);
$cambioIngresos = calcularCambioSeguro($ventasMes['total_ingresos'], $ventasMesAnterior['total_ingresos']);

// Top 5 clientes del mes
$topClientes = $db->select("
    SELECT 
        c.nombre,
        COUNT(v.id) as entregas,
        SUM(v.cantidad_bidones) as bidones,
        SUM(v.total) as total_compras
    FROM clientes c
    INNER JOIN ventas v ON c.id = v.cliente_id
    WHERE MONTH(v.fecha) = MONTH(CURDATE()) 
    AND YEAR(v.fecha) = YEAR(CURDATE())
    GROUP BY c.id, c.nombre
    ORDER BY total_compras DESC
    LIMIT 5
");

// Ventas por vendedor del mes
$ventasPorVendedor = $db->select("
    SELECT 
        u.nombre as vendedor,
        COUNT(v.id) as entregas,
        COALESCE(SUM(v.cantidad_bidones), 0) as bidones,
        COALESCE(SUM(v.total), 0) as total_ventas
    FROM usuarios u
    INNER JOIN clientes c ON u.id = c.vendedor_id
    LEFT JOIN ventas v ON c.id = v.cliente_id 
        AND MONTH(v.fecha) = MONTH(CURDATE()) 
        AND YEAR(v.fecha) = YEAR(CURDATE())
    WHERE u.rol = 'vendedor' AND u.activo = 1
    GROUP BY u.id, u.nombre
    ORDER BY total_ventas DESC
");

// Ventas de los últimos 7 días para gráfico
$ventasUltimos7Dias = $db->select("
    SELECT 
        DATE(fecha) as fecha,
        COUNT(*) as entregas,
        COALESCE(SUM(cantidad_bidones), 0) as bidones,
        COALESCE(SUM(total), 0) as ingresos
    FROM ventas 
    WHERE fecha >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
    GROUP BY DATE(fecha)
    ORDER BY fecha ASC
");

include '../../includes/header.php';
?>

<div class="row">
    <div class="col-12">
        <h1 class="h3 mb-4">
            <i class="fas fa-tachometer-alt me-2"></i>Dashboard del Administrador
        </h1>
    </div>
</div>

<!-- Tarjetas de estadísticas -->
<div class="row mb-4">
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card border-left-primary shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                            Entregas del Mes
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800">
                            <?= number_format($ventasMes['total_entregas']) ?>
                        </div>
                        <div class="text-xs">
                            <span class="<?= $cambioEntregas >= 0 ? 'text-success' : 'text-danger' ?>">
                                <i class="fas fa-arrow-<?= $cambioEntregas >= 0 ? 'up' : 'down' ?>"></i>
                                <?= abs($cambioEntregas) ?>%
                            </span>
                            vs mes anterior
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-truck fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card border-left-success shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                            Bidones Vendidos
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800">
                            <?= safeNumber($ventasMes['total_bidones']) ?>
                        </div>
                        <div class="text-xs">
                            <span class="<?= $cambioBidones >= 0 ? 'text-success' : 'text-danger' ?>">
                                <i class="fas fa-arrow-<?= $cambioBidones >= 0 ? 'up' : 'down' ?>"></i>
                                <?= abs($cambioBidones) ?>%
                            </span>
                            vs mes anterior
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-tint fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card border-left-info shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                            Ingresos del Mes
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800">
                            <?= safeCurrency($ventasMes['total_ingresos']) ?>
                        </div>
                        <div class="text-xs">
                            <span class="<?= $cambioIngresos >= 0 ? 'text-success' : 'text-danger' ?>">
                                <i class="fas fa-arrow-<?= $cambioIngresos >= 0 ? 'up' : 'down' ?>"></i>
                                <?= abs($cambioIngresos) ?>%
                            </span>
                            vs mes anterior
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-dollar-sign fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card border-left-warning shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                            Total Clientes
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800">
                            <?= number_format($totalClientes) ?>
                        </div>
                        <div class="text-xs text-muted">
                            <?= number_format($totalVendedores) ?> vendedores activos
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-users fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Gráficos y tablas -->
<div class="row">
    <!-- Gráfico de ventas de los últimos 7 días -->
    <div class="col-xl-8 col-lg-7">
        <div class="card shadow mb-4">
            <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                <h6 class="m-0 font-weight-bold text-primary">Ventas de los Últimos 7 Días</h6>
            </div>
            <div class="card-body">
                <canvas id="ventasChart" width="400" height="200"></canvas>
            </div>
        </div>
    </div>

    <!-- Top 5 Clientes -->
    <div class="col-xl-4 col-lg-5">
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">Top 5 Clientes del Mes</h6>
            </div>
            <div class="card-body">
                <?php if (empty($topClientes)): ?>
                    <p class="text-muted text-center">No hay datos disponibles</p>
                <?php else: ?>
                    <?php foreach ($topClientes as $index => $cliente): ?>
                        <div class="d-flex align-items-center mb-3">
                            <div class="me-3">
                                <span class="badge bg-primary rounded-pill"><?= $index + 1 ?></span>
                            </div>
                            <div class="flex-grow-1">
                                <div class="fw-bold"><?= htmlspecialchars($cliente['nombre']) ?></div>
                                <small class="text-muted">
                                    <?= $cliente['bidones'] ?> bidones - <?= formatCurrency($cliente['total_compras']) ?>
                                </small>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Tabla de ventas por vendedor -->
<div class="row">
    <div class="col-12">
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">Rendimiento por Vendedor - <?= date('F Y') ?></h6>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered" id="dataTable">
                        <thead>
                            <tr>
                                <th>Vendedor</th>
                                <th>Entregas</th>
                                <th>Bidones</th>
                                <th>Total Ventas</th>
                                <th>Promedio por Entrega</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($ventasPorVendedor)): ?>
                                <tr>
                                    <td colspan="5" class="text-center text-muted">No hay datos disponibles</td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($ventasPorVendedor as $vendedor): ?>
                                    <tr>
                                        <td><?= htmlspecialchars($vendedor['vendedor']) ?></td>
                                        <td><?= number_format($vendedor['entregas']) ?></td>
                                        <td><?= number_format($vendedor['bidones']) ?></td>
                                        <td><?= formatCurrency($vendedor['total_ventas']) ?></td>
                                        <td><?= formatCurrency($vendedor['total_ventas'] / max($vendedor['entregas'], 1)) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
$extraJS = '
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// Gráfico de ventas de los últimos 7 días
const ctx = document.getElementById("ventasChart").getContext("2d");
const ventasData = ' . json_encode($ventasUltimos7Dias) . ';

const labels = ventasData.map(item => {
    const date = new Date(item.fecha);
    return date.toLocaleDateString("es-ES", { month: "short", day: "numeric" });
});

const bidones = ventasData.map(item => parseInt(item.bidones));
const ingresos = ventasData.map(item => parseFloat(item.ingresos));

const myChart = new Chart(ctx, {
    type: "line",
    data: {
        labels: labels,
        datasets: [{
            label: "Bidones Vendidos",
            data: bidones,
            borderColor: "rgb(54, 162, 235)",
            backgroundColor: "rgba(54, 162, 235, 0.1)",
            yAxisID: "y"
        }, {
            label: "Ingresos ($)",
            data: ingresos,
            borderColor: "rgb(255, 99, 132)",
            backgroundColor: "rgba(255, 99, 132, 0.1)",
            yAxisID: "y1"
        }]
    },
    options: {
        responsive: true,
        interaction: {
            mode: "index",
            intersect: false,
        },
        scales: {
            y: {
                type: "linear",
                display: true,
                position: "left",
                title: {
                    display: true,
                    text: "Bidones"
                }
            },
            y1: {
                type: "linear",
                display: true,
                position: "right",
                title: {
                    display: true,
                    text: "Ingresos ($)"
                },
                grid: {
                    drawOnChartArea: false,
                },
            }
        }
    }
});
</script>
';

include '../../includes/footer.php';
?>
