<?php
require_once 'config.php';
require_once 'settings.php';
requireLogin();

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // Obtener configuración del sistema
    $systemSettings = getSystemSettings();
    
    // Obtener estadísticas del usuario actual
    if (isAdmin()) {
        // Admin ve estadísticas globales
        $query_total = "SELECT COUNT(*) as total FROM contactos";
        $query_mes = "SELECT COUNT(*) as total_mes FROM contactos WHERE MONTH(fecha_registro) = MONTH(CURRENT_DATE()) AND YEAR(fecha_registro) = YEAR(CURRENT_DATE())";
        $query_hoy = "SELECT COUNT(*) as total_hoy FROM contactos WHERE DATE(fecha_registro) = CURRENT_DATE()";
        $query_usuarios = "SELECT COUNT(*) as total_usuarios FROM usuarios WHERE tipo = 'usuario'";
    } else {
        // Usuario ve solo sus estadísticas
        $query_total = "SELECT COUNT(*) as total FROM contactos WHERE usuario_id = :user_id";
        $query_mes = "SELECT COUNT(*) as total_mes FROM contactos WHERE usuario_id = :user_id AND MONTH(fecha_registro) = MONTH(CURRENT_DATE()) AND YEAR(fecha_registro) = YEAR(CURRENT_DATE())";
        $query_hoy = "SELECT COUNT(*) as total_hoy FROM contactos WHERE usuario_id = :user_id AND DATE(fecha_registro) = CURRENT_DATE()";
    }
    
    $stmt_total = $db->prepare($query_total);
    $stmt_mes = $db->prepare($query_mes);
    $stmt_hoy = $db->prepare($query_hoy);
    
    if (!isAdmin()) {
        $stmt_total->bindParam(':user_id', $_SESSION['user_id']);
        $stmt_mes->bindParam(':user_id', $_SESSION['user_id']);
        $stmt_hoy->bindParam(':user_id', $_SESSION['user_id']);
    }
    
    $stmt_total->execute();
    $stmt_mes->execute();
    $stmt_hoy->execute();
    
    $total_contactos = $stmt_total->fetch()['total'];
    $contactos_mes = $stmt_mes->fetch()['total_mes'];
    $contactos_hoy = $stmt_hoy->fetch()['total_hoy'];
    
    if (isAdmin()) {
        $stmt_usuarios = $db->prepare($query_usuarios);
        $stmt_usuarios->execute();
        $total_usuarios = $stmt_usuarios->fetch()['total_usuarios'];
    }
    
    // Obtener contactos por mes para gráfico
    if (isAdmin()) {
        $query_grafico = "SELECT MONTH(fecha_registro) as mes, COUNT(*) as cantidad 
                         FROM contactos 
                         WHERE YEAR(fecha_registro) = YEAR(CURRENT_DATE()) 
                         GROUP BY MONTH(fecha_registro) 
                         ORDER BY mes";
        $stmt_grafico = $db->prepare($query_grafico);
    } else {
        $query_grafico = "SELECT MONTH(fecha_registro) as mes, COUNT(*) as cantidad 
                         FROM contactos 
                         WHERE usuario_id = :user_id AND YEAR(fecha_registro) = YEAR(CURRENT_DATE()) 
                         GROUP BY MONTH(fecha_registro) 
                         ORDER BY mes";
        $stmt_grafico = $db->prepare($query_grafico);
        $stmt_grafico->bindParam(':user_id', $_SESSION['user_id']);
    }
    
    $stmt_grafico->execute();
    $datos_grafico = $stmt_grafico->fetchAll();
    
    // Preparar datos para el gráfico
    $meses = ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'];
    $datos_meses = array_fill(0, 12, 0);
    foreach ($datos_grafico as $dato) {
        $datos_meses[$dato['mes'] - 1] = $dato['cantidad'];
    }
    
} catch (Exception $e) {
    error_log("Dashboard error: " . $e->getMessage());
    die("Error al cargar el dashboard. Por favor, contacte al administrador.");
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - <?php echo SITE_NAME; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body {
            background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
            font-family: 'Poppins', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            color: #1f2937;
        }
        
        .main-content {
            padding: 2rem;
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .dashboard-title {
            background: linear-gradient(135deg, #dc2626, #b91c1c);
            color: white;
            padding: 2rem;
            border-radius: 15px;
            margin-bottom: 2rem;
            text-align: center;
            box-shadow: 0 8px 25px rgba(220, 38, 38, 0.3);
        }
        
        .dashboard-title h1 {
            margin: 0;
            font-size: 2.5rem;
            font-weight: 700;
        }
        
        .dashboard-title p {
            margin: 0.5rem 0 0 0;
            opacity: 0.9;
            font-size: 1.1rem;
        }
        
        .stat-card {
            background: white;
            border-radius: 15px;
            padding: 2rem;
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
            border: 1px solid #e5e7eb;
            transition: all 0.3s ease;
            height: 100%;
            position: relative;
            overflow: hidden;
        }
        
        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, #dc2626, #b91c1c);
        }
        
        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
        }
        
        .stat-icon {
            width: 60px;
            height: 60px;
            border-radius: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            color: white;
            margin-bottom: 1rem;
        }
        
        .stat-number {
            font-size: 2.5rem;
            font-weight: 700;
            color: #dc2626;
            margin: 0;
        }
        
        .stat-label {
            color: #6b7280;
            font-weight: 600;
            font-size: 0.9rem;
            margin: 0.5rem 0 0 0;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .chart-container {
            background: white;
            border-radius: 15px;
            padding: 2rem;
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
            border: 1px solid #e5e7eb;
            margin-top: 2rem;
        }
        
        .chart-wrapper {
            position: relative;
            height: 400px;
        }
        
        .no-data-message {
            text-align: center;
            color: #6b7280;
            padding: 3rem;
        }
        
        .no-data-message i {
            font-size: 3rem;
            margin-bottom: 1rem;
            opacity: 0.5;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .main-content {
                padding: 1rem;
            }
            
            .dashboard-title h1 {
                font-size: 2rem;
            }
            
            .stat-card {
                margin-bottom: 1rem;
            }
            
            .stat-number {
                font-size: 2rem;
            }
        }
    </style>
</head>

<?php include 'header.php'; ?>

<body>
    <div class="main-content">
        <!-- Título del Dashboard -->
        <div class="dashboard-title">
            <h1><i class="fas fa-chart-line me-3"></i>Dashboard</h1>
            <p>Bienvenido, <?php echo htmlspecialchars($_SESSION['user_name']); ?> | <?php echo isAdmin() ? 'Administrador' : 'Usuario'; ?></p>
        </div>

        <!-- Tarjetas de Estadísticas -->
        <div class="row g-4 mb-4">
            <div class="col-lg-3 col-md-6">
                <div class="stat-card">
                    <div class="stat-icon" style="background: linear-gradient(135deg, #3b82f6, #1d4ed8);">
                        <i class="fas fa-users"></i>
                    </div>
                    <h2 class="stat-number"><?php echo number_format($total_contactos); ?></h2>
                    <p class="stat-label">Total Contactos</p>
                </div>
            </div>
            
            <div class="col-lg-3 col-md-6">
                <div class="stat-card">
                    <div class="stat-icon" style="background: linear-gradient(135deg, #10b981, #059669);">
                        <i class="fas fa-calendar-alt"></i>
                    </div>
                    <h2 class="stat-number"><?php echo number_format($contactos_mes); ?></h2>
                    <p class="stat-label">Este Mes</p>
                </div>
            </div>
            
            <div class="col-lg-3 col-md-6">
                <div class="stat-card">
                    <div class="stat-icon" style="background: linear-gradient(135deg, #f59e0b, #d97706);">
                        <i class="fas fa-calendar-day"></i>
                    </div>
                    <h2 class="stat-number"><?php echo number_format($contactos_hoy); ?></h2>
                    <p class="stat-label">Hoy</p>
                </div>
            </div>
            
            <?php if (isAdmin()): ?>
            <div class="col-lg-3 col-md-6">
                <div class="stat-card">
                    <div class="stat-icon" style="background: linear-gradient(135deg, #8b5cf6, #7c3aed);">
                        <i class="fas fa-user-tie"></i>
                    </div>
                    <h2 class="stat-number"><?php echo number_format($total_usuarios); ?></h2>
                    <p class="stat-label">Usuarios</p>
                </div>
            </div>
            <?php endif; ?>
        </div>

        <!-- Gráfico de Contactos por Mes -->
        <div class="chart-container">
            <h3 class="mb-4"><i class="fas fa-chart-bar me-2"></i>Contactos por Mes - <?php echo date('Y'); ?></h3>
            <?php if (array_sum($datos_meses) > 0): ?>
                <div class="chart-wrapper">
                    <canvas id="contactosChart"></canvas>
                </div>
            <?php else: ?>
                <div class="no-data-message">
                    <i class="fas fa-chart-bar"></i>
                    <h5>No hay datos para mostrar</h5>
                    <p>Aún no tienes contactos registrados este año.</p>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <?php if (array_sum($datos_meses) > 0): ?>
    <script>
        // Configuración del gráfico
        const ctx = document.getElementById('contactosChart').getContext('2d');
        const contactosChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: <?php echo json_encode($meses); ?>,
                datasets: [{
                    label: 'Contactos',
                    data: <?php echo json_encode($datos_meses); ?>,
                    backgroundColor: 'rgba(220, 38, 38, 0.8)',
                    borderColor: 'rgba(220, 38, 38, 1)',
                    borderWidth: 2,
                    borderRadius: 8,
                    borderSkipped: false,
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1
                        },
                        grid: {
                            color: 'rgba(0, 0, 0, 0.1)'
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        }
                    }
                }
            }
        });
    </script>
    <?php endif; ?>
</body>
</html>