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

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

// Verificar que sea vendedor
if ($_SESSION['user_role'] !== 'vendedor') {
    redirect('../admin/dashboard.php');
}

$pageTitle = 'Dashboard - Vendedor';

$db = Database::getInstance();
$vendedorId = $_SESSION['user_id'];

// Obtener estadísticas del vendedor
// Total de clientes asignados
$totalClientes = $db->select("SELECT COUNT(*) as total FROM clientes WHERE vendedor_id = ? AND activo = 1", [$vendedorId])[0]['total'];

// Ventas del mes actual
$ventasMes = $db->select("
    SELECT 
        COUNT(*) as total_entregas,
        SUM(v.cantidad_bidones) as total_bidones,
        SUM(v.total) as total_ingresos
    FROM ventas v
    INNER JOIN clientes c ON v.cliente_id = c.id
    WHERE c.vendedor_id = ?
    AND MONTH(v.fecha) = MONTH(CURDATE()) 
    AND YEAR(v.fecha) = YEAR(CURDATE())
", [$vendedorId])[0];

// Ventas del mes anterior para comparación
$ventasMesAnterior = $db->select("
    SELECT 
        COUNT(*) as total_entregas,
        SUM(v.cantidad_bidones) as total_bidones,
        SUM(v.total) as total_ingresos
    FROM ventas v
    INNER JOIN clientes c ON v.cliente_id = c.id
    WHERE c.vendedor_id = ?
    AND MONTH(v.fecha) = MONTH(DATE_SUB(CURDATE(), INTERVAL 1 MONTH))
    AND YEAR(v.fecha) = YEAR(DATE_SUB(CURDATE(), INTERVAL 1 MONTH))
", [$vendedorId])[0];

// Calcular porcentajes de cambio
function calcularCambio($actual, $anterior) {
    if ($anterior == 0) return $actual > 0 ? 100 : 0;
    return round((($actual - $anterior) / $anterior) * 100, 1);
}

$cambioEntregas = calcularCambio($ventasMes['total_entregas'], $ventasMesAnterior['total_entregas']);
$cambioBidones = calcularCambio($ventasMes['total_bidones'], $ventasMesAnterior['total_bidones']);
$cambioIngresos = calcularCambio($ventasMes['total_ingresos'], $ventasMesAnterior['total_ingresos']);

// Resumen de clientes con saldos
$resumenClientes = $db->select("
    SELECT 
        c.id,
        c.nombre,
        c.direccion,
        c.latitud,
        c.longitud,
        (SELECT COUNT(*) FROM ventas v WHERE v.cliente_id = c.id AND MONTH(v.fecha) = MONTH(CURDATE()) AND YEAR(v.fecha) = YEAR(CURDATE())) as entregas_mes,
        (SELECT SUM(v.cantidad_bidones) FROM ventas v WHERE v.cliente_id = c.id AND MONTH(v.fecha) = MONTH(CURDATE()) AND YEAR(v.fecha) = YEAR(CURDATE())) as bidones_mes,
        (SELECT SUM(v.total) FROM ventas v WHERE v.cliente_id = c.id) as total_ventas,
        (SELECT SUM(p.monto) FROM pagos p WHERE p.cliente_id = c.id) as total_pagos,
        (SELECT MAX(v.fecha) FROM ventas v WHERE v.cliente_id = c.id) as ultima_entrega
    FROM clientes c
    WHERE c.vendedor_id = ? AND c.activo = 1
    ORDER BY c.nombre
", [$vendedorId]);

// Calcular saldos
foreach ($resumenClientes as &$cliente) {
    $cliente['saldo'] = ($cliente['total_ventas'] ?? 0) - ($cliente['total_pagos'] ?? 0);
    $cliente['entregas_mes'] = $cliente['entregas_mes'] ?? 0;
    $cliente['bidones_mes'] = $cliente['bidones_mes'] ?? 0;
}

// Entregas de hoy
$entregasHoy = $db->select("
    SELECT 
        c.nombre as cliente_nombre,
        v.cantidad_bidones,
        v.total,
        v.observaciones
    FROM ventas v
    INNER JOIN clientes c ON v.cliente_id = c.id
    WHERE c.vendedor_id = ? AND DATE(v.fecha) = CURDATE()
    ORDER BY v.created_at DESC
", [$vendedorId]);

// Ventas de los últimos 7 días para gráfico
$ventasUltimos7Dias = $db->select("
    SELECT 
        DATE(v.fecha) as fecha,
        COUNT(*) as entregas,
        SUM(v.cantidad_bidones) as bidones,
        SUM(v.total) as ingresos
    FROM ventas v
    INNER JOIN clientes c ON v.cliente_id = c.id
    WHERE c.vendedor_id = ? AND v.fecha >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
    GROUP BY DATE(v.fecha)
    ORDER BY fecha ASC
", [$vendedorId]);

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

<div class="row">
    <div class="col-12">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1 class="h3">
                <i class="fas fa-tachometer-alt me-2"></i>Dashboard del Vendedor - <?= htmlspecialchars($_SESSION['user_name']) ?>
            </h1>
            <a href="cliente-nuevo.php" class="btn btn-primary">
                <i class="fas fa-user-plus me-2"></i>Nuevo Cliente
            </a>
        </div>
    </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">
                            <?= safeNumber($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">
                            Ventas 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">
                            Mis Clientes
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800">
                            <?= number_format($totalClientes) ?>
                        </div>
                        <div class="text-xs text-muted">
                            Clientes activos
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-users fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Acciones rápidas -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <h5 class="card-title">Acciones Rápidas</h5>
                <div class="row">
                    <div class="col-md-3 mb-2">
                        <a href="nueva-venta.php" class="btn btn-primary btn-lg w-100">
                            <i class="fas fa-plus-circle me-2"></i>Nueva Venta
                        </a>
                    </div>
                    <div class="col-md-3 mb-2">
                        <a href="mis-clientes.php" class="btn btn-info btn-lg w-100">
                            <i class="fas fa-users me-2"></i>Ver Clientes
                        </a>
                    </div>
                    <div class="col-md-3 mb-2">
                        <a href="mapa.php" class="btn btn-success btn-lg w-100">
                            <i class="fas fa-map-marker-alt me-2"></i>Ver Mapa
                        </a>
                    </div>
                    <div class="col-md-3 mb-2">
                        <a href="mis-ventas.php" class="btn btn-secondary btn-lg w-100">
                            <i class="fas fa-list me-2"></i>Mis Ventas
                        </a>
                    </div>
                    <div class="col-md-3 mb-2">
                        <a href="cliente-nuevo.php" class="btn btn-success btn-lg w-100">
                            <i class="fas fa-user-plus me-2"></i>Nuevo Cliente
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- Gráfico de ventas -->
    <div class="col-xl-8 col-lg-7">
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">Mis Ventas - Últimos 7 Días</h6>
            </div>
            <div class="card-body">
                <canvas id="ventasChart" width="400" height="200"></canvas>
            </div>
        </div>
    </div>

    <!-- Entregas de hoy -->
    <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">Entregas de Hoy</h6>
            </div>
            <div class="card-body">
                <?php if (empty($entregasHoy)): ?>
                    <p class="text-muted text-center">No hay entregas registradas hoy</p>
                    <div class="text-center">
                        <a href="nueva-venta.php" class="btn btn-primary btn-sm">
                            <i class="fas fa-plus me-1"></i>Registrar Entrega
                        </a>
                    </div>
                <?php else: ?>
                    <?php foreach ($entregasHoy as $entrega): ?>
                        <div class="d-flex justify-content-between align-items-center mb-3 p-2 border rounded">
                            <div>
                                <div class="fw-bold"><?= htmlspecialchars($entrega['cliente_nombre']) ?></div>
                                <small class="text-muted">
                                    <?= $entrega['cantidad_bidones'] ?> bidones - <?= formatCurrency($entrega['total']) ?>
                                </small>
                                <?php if ($entrega['observaciones']): ?>
                                    <br><small class="text-info"><?= htmlspecialchars($entrega['observaciones']) ?></small>
                                <?php endif; ?>
                            </div>
                            <span class="badge bg-success">
                                <i class="fas fa-check"></i>
                            </span>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Resumen de clientes -->
<div class="row">
    <div class="col-12">
        <div class="card shadow mb-4">
            <div class="card-header py-3 d-flex justify-content-between align-items-center">
                <h6 class="m-0 font-weight-bold text-primary">Resumen de Mis Clientes</h6>
                <a href="mis-clientes.php" class="btn btn-sm btn-outline-primary">Ver Todos</a>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead class="table-light">
                            <tr>
                                <th>Cliente</th>
                                <th>Entregas Mes</th>
                                <th>Bidones Mes</th>
                                <th>Saldo</th>
                                <th>Última Entrega</th>
                                <th>Ubicación</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($resumenClientes)): ?>
                                <tr>
                                    <td colspan="6" class="text-center text-muted py-4">
                                        No tiene clientes asignados.
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach (array_slice($resumenClientes, 0, 10) as $cliente): ?>
                                    <?php
                                    $saldoClass = $cliente['saldo'] > 0 ? 'text-danger' : ($cliente['saldo'] < 0 ? 'text-success' : 'text-muted');
                                    ?>
                                    <tr>
                                        <td>
                                            <div>
                                                <strong><?= htmlspecialchars($cliente['nombre']) ?></strong>
                                                <br>
                                                <small class="text-muted"><?= htmlspecialchars($cliente['direccion']) ?></small>
                                            </div>
                                        </td>
                                        <td>
                                            <span class="badge bg-info">
                                                <?= safeNumber($cliente['entregas_mes']) ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="badge bg-primary">
                                                <?= safeNumber($cliente['bidones_mes']) ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="<?= $saldoClass ?>">
                                                <strong><?= safeCurrency($cliente['saldo']) ?></strong>
                                            </span>
                                        </td>
                                        <td>
                                            <?php if ($cliente['ultima_entrega']): ?>
                                                <small><?= formatDate($cliente['ultima_entrega']) ?></small>
                                            <?php else: ?>
                                                <small class="text-muted">Sin entregas</small>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($cliente['latitud'] && $cliente['longitud']): ?>
                                                <a href="https://maps.google.com/?q=<?= $cliente['latitud'] ?>,<?= $cliente['longitud'] ?>" 
                                                   target="_blank" class="btn btn-sm btn-outline-success">
                                                    <i class="fas fa-map-marker-alt"></i>
                                                </a>
                                            <?php else: ?>
                                                <span class="text-muted">Sin ubicación</span>
                                            <?php endif; ?>
                                        </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';
?>
