<?php
require_once 'includes/auth_check.php';
require_once 'config/database.php';

$database = new Database();
$db = $database->getConnection();

// Obtener estadísticas
$query = "SELECT COUNT(*) as total FROM visitas WHERE DATE(fecha_registro) = CURDATE()";
$stmt = $db->prepare($query);
$stmt->execute();
$visitas_hoy = $stmt->fetch(PDO::FETCH_ASSOC)['total'];

$query = "SELECT COUNT(*) as total FROM visitas WHERE hora_salida IS NULL AND DATE(fecha_visita) = CURDATE()";
$stmt = $db->prepare($query);
$stmt->execute();
$visitas_activas = $stmt->fetch(PDO::FETCH_ASSOC)['total'];

$query = "SELECT COUNT(*) as total FROM usuarios WHERE activo = 1";
$stmt = $db->prepare($query);
$stmt->execute();
$total_usuarios = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - Sistema de Visitas</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
        :root {
            --celeste-primario: #e3f2fd;
            --celeste-secundario: #bbdefb;
            --celeste-oscuro: #1976d2;
        }
        .sidebar {
            background: linear-gradient(180deg, var(--celeste-oscuro) 0%, #1565c0 100%);
            min-height: 100vh;
            color: white;
            transition: all 0.3s;
        }
        .sidebar .nav-link {
            color: rgba(255,255,255,0.8);
            padding: 12px 20px;
            margin: 5px 0;
            border-radius: 8px;
            transition: all 0.3s;
        }
        .sidebar .nav-link:hover, .sidebar .nav-link.active {
            background: rgba(255,255,255,0.1);
            color: white;
            transform: translateX(5px);
        }
        .main-content {
            background-color: #f8f9fa;
            min-height: 100vh;
        }
        .card-stat {
            border: none;
            border-radius: 15px;
            transition: transform 0.3s;
            overflow: hidden;
        }
        .card-stat:hover {
            transform: translateY(-5px);
        }
        .card-stat.visitas {
            background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
            border-left: 5px solid var(--celeste-oscuro);
        }
        .card-stat.activas {
            background: linear-gradient(135deg, #fff3cd 0%, #ffeaa7 100%);
            border-left: 5px solid #ff9800;
        }
        .card-stat.usuarios {
            background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%);
            border-left: 5px solid #28a745;
        }
        .icon-stat {
            font-size: 2.5rem;
            opacity: 0.8;
        }
        .welcome-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            animation: slideIn 0.5s ease-out;
        }
        @keyframes slideIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <nav class="col-md-3 col-lg-2 d-md-block sidebar collapse">
                <div class="position-sticky pt-3">
                    <div class="text-center mb-4">
                        <div class="p-3">
                            <i class="fas fa-building fa-3x mb-3"></i>
                            <h5>Sistema de Visitas</h5>
                            <small>Entidad Pública</small>
                        </div>
                    </div>
                    
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link active" href="dashboard.php">
                                <i class="fas fa-home me-2"></i>Dashboard
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="modules/visitas/registrar.php">
                                <i class="fas fa-sign-in-alt me-2"></i>Registrar Ingreso
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="modules/visitas/salida.php">
                                <i class="fas fa-sign-out-alt me-2"></i>Registrar Salida
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="modules/visitas/listar.php">
                                <i class="fas fa-list me-2"></i>Listar Visitas
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="modules/reportes/generar.php">
                                <i class="fas fa-chart-bar me-2"></i>Reportes
                            </a>
                        </li>
                        
                        <?php if ($_SESSION['user_tipo'] == 'admin'): ?>
                        <li class="nav-divider my-3"></li>
                        <li class="nav-item">
                            <a class="nav-link" href="modules/usuarios/gestion.php">
                                <i class="fas fa-users me-2"></i>Gestión de Usuarios
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="modules/areas/gestion.php">
                                <i class="fas fa-sitemap me-2"></i>Áreas
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="modules/entidad/configuracion.php">
                                <i class="fas fa-cog me-2"></i>Configuración
                            </a>
                        </li>
                        <?php endif; ?>
                        
                        <li class="nav-divider my-3"></li>
                        <li class="nav-item">
                            <a class="nav-link" href="logout.php">
                                <i class="fas fa-sign-out-alt me-2"></i>Cerrar Sesión
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- Main Content -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 main-content">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">Dashboard</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <span class="badge bg-primary">
                            <i class="fas fa-user me-1"></i>
                            <?php echo $_SESSION['user_nombre']; ?>
                        </span>
                    </div>
                </div>

                <!-- Welcome Card -->
                <div class="row mb-4">
                    <div class="col-12">
                        <div class="welcome-card p-4">
                            <div class="row align-items-center">
                                <div class="col-md-8">
                                    <h3 class="mb-3">¡Bienvenido, <?php echo explode(' ', $_SESSION['user_nombre'])[0]; ?>!</h3>
                                    <p class="text-muted">Sistema de registro y control de visitas para la entidad pública.</p>
                                    <div class="d-flex gap-2">
                                        <a href="modules/visitas/registrar.php" class="btn btn-primary">
                                            <i class="fas fa-plus-circle me-2"></i>Nueva Visita
                                        </a>
                                        <a href="modules/visitas/salida.php" class="btn btn-warning">
                                            <i class="fas fa-sign-out-alt me-2"></i>Registrar Salida
                                        </a>
                                    </div>
                                </div>
                                <div class="col-md-4 text-center">
                                    <i class="fas fa-calendar-check fa-5x text-primary"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Statistics Cards -->
                <div class="row">
                    <div class="col-md-4 mb-4">
                        <div class="card card-stat visitas p-3">
                            <div class="card-body">
                                <div class="row align-items-center">
                                    <div class="col-8">
                                        <h5 class="card-title">Visitas Hoy</h5>
                                        <h2 class="mb-0"><?php echo $visitas_hoy; ?></h2>
                                        <small>Total de visitas registradas hoy</small>
                                    </div>
                                    <div class="col-4 text-end">
                                        <i class="fas fa-users icon-stat text-primary"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-4 mb-4">
                        <div class="card card-stat activas p-3">
                            <div class="card-body">
                                <div class="row align-items-center">
                                    <div class="col-8">
                                        <h5 class="card-title">Visitas Activas</h5>
                                        <h2 class="mb-0"><?php echo $visitas_activas; ?></h2>
                                        <small>Visitas sin registrar salida</small>
                                    </div>
                                    <div class="col-4 text-end">
                                        <i class="fas fa-user-clock icon-stat text-warning"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-4 mb-4">
                        <div class="card card-stat usuarios p-3">
                            <div class="card-body">
                                <div class="row align-items-center">
                                    <div class="col-8">
                                        <h5 class="card-title">Usuarios Activos</h5>
                                        <h2 class="mb-0"><?php echo $total_usuarios; ?></h2>
                                        <small>Usuarios del sistema</small>
                                    </div>
                                    <div class="col-4 text-end">
                                        <i class="fas fa-user-shield icon-stat text-success"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Recent Visits -->
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="mb-0">Últimas Visitas Registradas</h5>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-hover">
                                        <thead>
                                            <tr>
                                                <th>Hora Ingreso</th>
                                                <th>Visitante</th>
                                                <th>DNI</th>
                                                <th>Área</th>
                                                <th>Motivo</th>
                                                <th>Estado</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
                                            $query = "SELECT v.*, a.nombre_area as area 
                                                      FROM visitas v 
                                                      LEFT JOIN areas a ON v.area_id = a.id 
                                                      WHERE DATE(v.fecha_visita) = CURDATE() 
                                                      ORDER BY v.hora_ingreso DESC 
                                                      LIMIT 10";
                                            $stmt = $db->prepare($query);
                                            $stmt->execute();
                                            
                                            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)):
                                            ?>
                                            <tr>
                                                <td><?php echo date('H:i', strtotime($row['hora_ingreso'])); ?></td>
                                                <td><?php echo $row['apellidos_visitante'] . ', ' . $row['nombres_visitante']; ?></td>
                                                <td><?php echo $row['documento_visitante']; ?></td>
                                                <td><?php echo $row['area']; ?></td>
                                                <td><?php echo substr($row['motivo_visita'], 0, 30) . '...'; ?></td>
                                                <td>
                                                    <?php if ($row['hora_salida']): ?>
                                                        <span class="badge bg-success">Completada</span>
                                                    <?php else: ?>
                                                        <span class="badge bg-warning">En curso</span>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                            <?php endwhile; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://kit.fontawesome.com/your-fontawesome-kit.js" crossorigin="anonymous"></script>
    <script src="assets/js/main.js"></script>
</body>
</html>