<?php
/**
 * Mis Clientes - 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 = 'Mis Clientes - Vendedor';

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

// Filtros
$busqueda = $_GET['busqueda'] ?? '';
$filtroSaldo = $_GET['saldo'] ?? '';

// Construir consulta con filtros
$whereConditions = ["c.vendedor_id = ?"];
$params = [$vendedorId];

if (!empty($busqueda)) {
    $whereConditions[] = "(c.nombre LIKE ? OR c.direccion LIKE ?)";
    $params[] = "%$busqueda%";
    $params[] = "%$busqueda%";
}

$whereClause = 'WHERE ' . implode(' AND ', $whereConditions);

// Obtener clientes con resumen completo
$query = "
    SELECT 
        c.*,
        (SELECT COUNT(*) FROM ventas v WHERE v.cliente_id = c.id) as total_entregas,
        (SELECT SUM(v.cantidad_bidones) FROM ventas v WHERE v.cliente_id = c.id) as total_bidones,
        (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 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 MAX(v.fecha) FROM ventas v WHERE v.cliente_id = c.id) as ultima_entrega
    FROM clientes c
    $whereClause
    ORDER BY c.nombre ASC
";

$clientes = $db->select($query, $params);

// Calcular saldos y aplicar filtro de saldo si es necesario
$clientesFiltrados = [];
foreach ($clientes 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;
    
    // Aplicar filtro de saldo
    if ($filtroSaldo === 'positivo' && $cliente['saldo'] <= 0) continue;
    if ($filtroSaldo === 'negativo' && $cliente['saldo'] >= 0) continue;
    if ($filtroSaldo === 'cero' && $cliente['saldo'] != 0) continue;
    
    $clientesFiltrados[] = $cliente;
}

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-users me-2"></i>Mis Clientes
            </h1>
            <a href="nueva-venta.php" class="btn btn-primary">
                <i class="fas fa-plus me-2"></i>Nueva Venta
            </a>
        </div>
    </div>
</div>

<!-- Estadísticas rápidas -->
<div class="row mb-4">
    <div class="col-md-3">
        <div class="card bg-primary text-white">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <div class="h4"><?= count($clientesFiltrados) ?></div>
                        <div>Total Clientes</div>
                    </div>
                    <div class="align-self-center">
                        <i class="fas fa-users fa-2x"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card bg-success text-white">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <div class="h4">
                            <?= count(array_filter($clientesFiltrados, function($c) { return $c['entregas_mes'] > 0; })) ?>
                        </div>
                        <div>Activos este Mes</div>
                    </div>
                    <div class="align-self-center">
                        <i class="fas fa-check-circle fa-2x"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card bg-warning text-white">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <div class="h4">
                            <?= count(array_filter($clientesFiltrados, function($c) { return $c['saldo'] > 0; })) ?>
                        </div>
                        <div>Con Saldo Pendiente</div>
                    </div>
                    <div class="align-self-center">
                        <i class="fas fa-exclamation-triangle fa-2x"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card bg-info text-white">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <div class="h4">
                            <?= array_sum(array_column($clientesFiltrados, 'bidones_mes')) ?>
                        </div>
                        <div>Bidones este Mes</div>
                    </div>
                    <div class="align-self-center">
                        <i class="fas fa-tint fa-2x"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Filtros -->
<div class="card mb-4">
    <div class="card-body">
        <form method="GET" class="row g-3">
            <div class="col-md-4">
                <label for="busqueda" class="form-label">Buscar Cliente</label>
                <input type="text" name="busqueda" id="busqueda" class="form-control" 
                       placeholder="Nombre o dirección" value="<?= htmlspecialchars($busqueda) ?>">
            </div>
            
            <div class="col-md-3">
                <label for="saldo" class="form-label">Filtrar por Saldo</label>
                <select name="saldo" id="saldo" class="form-select">
                    <option value="">Todos</option>
                    <option value="positivo" <?= $filtroSaldo === 'positivo' ? 'selected' : '' ?>>Con saldo a favor</option>
                    <option value="negativo" <?= $filtroSaldo === 'negativo' ? 'selected' : '' ?>>Con saldo en contra</option>
                    <option value="cero" <?= $filtroSaldo === 'cero' ? 'selected' : '' ?>>Saldo en cero</option>
                </select>
            </div>
            
            <div class="col-md-5 d-flex align-items-end">
                <button type="submit" class="btn btn-outline-primary me-2">
                    <i class="fas fa-search me-1"></i>Filtrar
                </button>
                <a href="mis-clientes.php" class="btn btn-outline-secondary me-2">
                    <i class="fas fa-times me-1"></i>Limpiar
                </a>
                <a href="mapa.php" class="btn btn-success">
                    <i class="fas fa-map-marker-alt me-1"></i>Ver en Mapa
                </a>
            </div>
        </form>
    </div>
</div>

<!-- Lista de clientes -->
<div class="row">
    <?php if (empty($clientesFiltrados)): ?>
        <div class="col-12">
            <div class="card">
                <div class="card-body text-center py-5">
                    <i class="fas fa-users fa-3x text-muted mb-3"></i>
                    <h5 class="text-muted">No se encontraron clientes</h5>
                    <p class="text-muted">No hay clientes que coincidan con los filtros aplicados.</p>
                    <a href="mis-clientes.php" class="btn btn-primary">Ver Todos los Clientes</a>
                </div>
            </div>
        </div>
    <?php else: ?>
        <?php foreach ($clientesFiltrados as $cliente): ?>
            <?php
            $saldoClass = $cliente['saldo'] > 0 ? 'text-danger' : ($cliente['saldo'] < 0 ? 'text-success' : 'text-muted');
            $saldoIcon = $cliente['saldo'] > 0 ? 'fa-arrow-up' : ($cliente['saldo'] < 0 ? 'fa-arrow-down' : 'fa-minus');
            ?>
            <div class="col-lg-6 col-xl-4 mb-4">
                <div class="card h-100 shadow-sm">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h6 class="mb-0 fw-bold"><?= htmlspecialchars($cliente['nombre']) ?></h6>
                        <?php if ($cliente['activo']): ?>
                            <span class="badge bg-success">Activo</span>
                        <?php else: ?>
                            <span class="badge bg-secondary">Inactivo</span>
                        <?php endif; ?>
                    </div>
                    
                    <div class="card-body">
                        <div class="mb-3">
                            <small class="text-muted">
                                <i class="fas fa-map-marker-alt me-1"></i>
                                <?= htmlspecialchars($cliente['direccion']) ?>
                            </small>
                        </div>
                        
                        <!-- Estadísticas del mes -->
                        <div class="row text-center mb-3">
                            <div class="col-4">
                                <div class="border-end">
                                    <div class="h5 mb-0 text-primary"><?= $cliente['entregas_mes'] ?></div>
                                    <small class="text-muted">Entregas</small>
                                </div>
                            </div>
                            <div class="col-4">
                                <div class="border-end">
                                    <div class="h5 mb-0 text-info"><?= $cliente['bidones_mes'] ?></div>
                                    <small class="text-muted">Bidones</small>
                                </div>
                            </div>
                            <div class="col-4">
                                <div class="h6 mb-0 <?= $saldoClass ?>">
                                    <i class="fas <?= $saldoIcon ?> me-1"></i>
                                    <?= formatCurrency(abs($cliente['saldo'])) ?>
                                </div>
                                <small class="text-muted">Saldo</small>
                            </div>
                        </div>
                        
                        <!-- Información adicional -->
                        <div class="mb-3">
                            <div class="row">
                                <div class="col-6">
                                    <small class="text-muted">Total Entregas:</small>
                                    <div class="fw-bold"><?= number_format($cliente['total_entregas']) ?></div>
                                </div>
                                <div class="col-6">
                                    <small class="text-muted">Total Bidones:</small>
                                    <div class="fw-bold"><?= number_format($cliente['total_bidones']) ?></div>
                                </div>
                            </div>
                        </div>
                        
                        <?php if ($cliente['ultima_entrega']): ?>
                            <div class="mb-3">
                                <small class="text-muted">Última entrega:</small>
                                <div class="fw-bold"><?= formatDate($cliente['ultima_entrega']) ?></div>
                            </div>
                        <?php endif; ?>
                    </div>
                    
                    <div class="card-footer">
                        <div class="btn-group w-100" role="group">
                            <a href="nueva-venta.php?cliente_id=<?= $cliente['id'] ?>" 
                               class="btn btn-primary btn-sm">
                                <i class="fas fa-plus me-1"></i>Venta
                            </a>
                            
                            <a href="cliente-detalle.php?id=<?= $cliente['id'] ?>" 
                               class="btn btn-info btn-sm">
                                <i class="fas fa-eye me-1"></i>Detalle
                            </a>
                            
                            <?php if ($cliente['latitud'] && $cliente['longitud']): ?>
                                <a href="https://maps.google.com/?q=<?= $cliente['latitud'] ?>,<?= $cliente['longitud'] ?>" 
                                   target="_blank" class="btn btn-success btn-sm">
                                    <i class="fas fa-map-marker-alt me-1"></i>Mapa
                                </a>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

<!-- Resumen al final -->
<?php if (!empty($clientesFiltrados)): ?>
<div class="row mt-4">
    <div class="col-12">
        <div class="card bg-light">
            <div class="card-body">
                <div class="row text-center">
                    <div class="col-md-3">
                        <div class="h4 text-primary"><?= count($clientesFiltrados) ?></div>
                        <div class="text-muted">Clientes Mostrados</div>
                    </div>
                    <div class="col-md-3">
                        <div class="h4 text-success"><?= array_sum(array_column($clientesFiltrados, 'entregas_mes')) ?></div>
                        <div class="text-muted">Entregas del Mes</div>
                    </div>
                    <div class="col-md-3">
                        <div class="h4 text-info"><?= array_sum(array_column($clientesFiltrados, 'bidones_mes')) ?></div>
                        <div class="text-muted">Bidones del Mes</div>
                    </div>
                    <div class="col-md-3">
                        <div class="h4 text-warning">
                            <?= formatCurrency(array_sum(array_column($clientesFiltrados, 'saldo'))) ?>
                        </div>
                        <div class="text-muted">Saldo Total</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

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