<?php

date_default_timezone_set('America/Guatemala');
setlocale(LC_ALL,'es_GT.utf8');

session_start();

// ============================================
// CONFIGURACIÓN DE USUARIOS - ¡CAMBIA ESTO!
// ============================================
// Para generar nuevos hash de contraseñas, puedes usar:
// echo password_hash('tu_nueva_contraseña', PASSWORD_DEFAULT);
$usuarios = [
    'UIP-648' => '$2y$10$v5msiCgXWKFRjRJF9oZLje47JRPil6bX18xvw1dbU/HMZdgc.yRpG',
    'insivumeh' => '$2y$10$cmphsXrwTKUeMLsFS9blKOSOinzYagT7.GaQEk/6GOIoLuP1UQQsS'
];

// Intentos de login para prevenir ataques de fuerza bruta
if (!isset($_SESSION['intentos_login'])) {
    $_SESSION['intentos_login'] = 0;
}

// ============================================
// FUNCIONES AUXILIARES
// ============================================
function esUsuarioAutenticado() {
    return isset($_SESSION['autenticado']) && $_SESSION['autenticado'] === true;
}

function mostrarPaginaLogin($error = null) {
    global $usuarios;
    ?>
    <!DOCTYPE html>
    <html lang="es-GT">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>GEOFISCA - Sistema de Acceso</title>
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }
            
            body {
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                min-height: 100vh;
                display: flex;
                justify-content: center;
                align-items: center;
                padding: 20px;
            }
            
            .login-container {
                background: rgba(255, 255, 255, 0.95);
                border-radius: 20px;
                box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
                width: 100%;
                max-width: 400px;
                overflow: hidden;
                animation: fadeIn 0.5s ease-out;
            }
            
            @keyframes fadeIn {
                from { opacity: 0; transform: translateY(20px); }
                to { opacity: 1; transform: translateY(0); }
            }
            
            .login-header {
                background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
                color: white;
                padding: 30px 20px;
                text-align: center;
            }
            
            .login-header h1 {
                font-size: 28px;
                margin-bottom: 5px;
                display: flex;
                align-items: center;
                justify-content: center;
                gap: 10px;
            }
            
            .login-header p {
                opacity: 0.9;
                font-size: 14px;
            }
            
            .login-body {
                padding: 30px;
            }
            
            .form-group {
                margin-bottom: 20px;
            }
            
            .form-group label {
                display: block;
                margin-bottom: 8px;
                color: #333;
                font-weight: 600;
                font-size: 14px;
            }
            
            .form-control {
                width: 100%;
                padding: 12px 15px;
                border: 2px solid #e0e0e0;
                border-radius: 10px;
                font-size: 16px;
                transition: all 0.3s ease;
                background: #f8f9fa;
            }
            
            .form-control:focus {
                outline: none;
                border-color: #4CAF50;
                background: white;
                box-shadow: 0 0 0 3px rgba(76, 175, 80, 0.1);
            }
            
            .btn-login {
                width: 100%;
                padding: 14px;
                background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
                color: white;
                border: none;
                border-radius: 10px;
                font-size: 16px;
                font-weight: 600;
                cursor: pointer;
                transition: all 0.3s ease;
                display: flex;
                align-items: center;
                justify-content: center;
                gap: 10px;
            }
            
            .btn-login:hover {
                transform: translateY(-2px);
                box-shadow: 0 5px 15px rgba(76, 175, 80, 0.3);
            }
            
            .btn-login:active {
                transform: translateY(0);
            }
            
            .alert-error {
                background: #fee;
                border: 2px solid #fcc;
                color: #c00;
                padding: 12px;
                border-radius: 10px;
                margin-bottom: 20px;
                font-size: 14px;
                display: flex;
                align-items: center;
                gap: 10px;
            }
            
            .alert-error i {
                font-size: 18px;
            }
            
            .login-footer {
                text-align: center;
                margin-top: 20px;
                padding-top: 20px;
                border-top: 1px solid #eee;
                color: #666;
                font-size: 13px;
            }
            
            .demo-accounts {
                background: #f8f9fa;
                border-radius: 10px;
                padding: 15px;
                margin-top: 20px;
                font-size: 13px;
            }
            
            .demo-accounts h4 {
                margin-bottom: 10px;
                color: #333;
                font-size: 14px;
            }
            
            .demo-accounts ul {
                list-style: none;
                padding-left: 0;
            }
            
            .demo-accounts li {
                padding: 5px 0;
                border-bottom: 1px dashed #ddd;
                display: flex;
                justify-content: space-between;
            }
            
            .demo-accounts li:last-child {
                border-bottom: none;
            }
            
            @media (max-width: 480px) {
                .login-container {
                    border-radius: 15px;
                }
                
                .login-header {
                    padding: 20px 15px;
                }
                
                .login-body {
                    padding: 20px;
                }
            }
        </style>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
            

// ============================================
// PÁGINA PRINCIPAL (usuario autenticado)
// ============================================
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GEOFISCA - Panel de Archivos</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
        }
        
        .header {
            background: linear-gradient(135deg, #2c3e50 0%, #4CAF50 100%);
            color: white;
            padding: 20px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
        
        .header-content {
            max-width: 1200px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 20px;
        }
        
        .logo-section {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .logo-section h1 {
            font-size: 24px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .user-section {
            display: flex;
            align-items: center;
            gap: 20px;
        }
        
        .user-info {
            background: rgba(255, 255, 255, 0.1);
            padding: 10px 20px;
            border-radius: 10px;
            backdrop-filter: blur(10px);
        }
        
        .btn-logout {
            background: #ff4757;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s ease;
            text-decoration: none;
        }
        
        .btn-logout:hover {
            background: #ff3838;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(255, 71, 87, 0.3);
        }
        
        .container {
            max-width: 1200px;
            margin: 30px auto;
            padding: 0 20px;
        }
        
        .file-list {
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
            overflow: hidden;
        }
        
        .file-header {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            padding: 20px;
            border-bottom: 2px solid #e0e0e0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .file-header h2 {
            color: #2c3e50;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .file-count {
            background: #4CAF50;
            color: white;
            padding: 5px 15px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: bold;
        }
        
        .file-items {
            padding: 20px;
        }
        
        .file-item {
            display: flex;
            align-items: center;
            padding: 15px;
            border-bottom: 1px solid #eee;
            transition: all 0.3s ease;
        }
        
        .file-item:hover {
            background: #f8f9fa;
            transform: translateX(5px);
        }
        
        .file-icon {
            width: 50px;
            height: 50px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 20px;
            margin-right: 20px;
        }
        
        .file-info {
            flex: 1;
        }
        
        .file-name {
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 5px;
            font-size: 16px;
        }
        
        .file-meta {
            display: flex;
            gap: 20px;
            color: #666;
            font-size: 14px;
        }
        
        .file-meta i {
            margin-right: 5px;
        }
        
        .file-action {
            margin-left: 20px;
        }
        
        .btn-download {
            background: #4CAF50;
            color: white;
            text-decoration: none;
            padding: 8px 20px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s ease;
        }
        
        .btn-download:hover {
            background: #45a049;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(76, 175, 80, 0.3);
        }
        
        /* Estilo especial para botón INGRESA de IMM */
        .btn-ingresa {
            background: linear-gradient(135deg, #FF9800 0%, #F57C00 100%);
            color: white;
            text-decoration: none;
            padding: 10px 25px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            gap: 10px;
            font-weight: bold;
            font-size: 15px;
            transition: all 0.3s ease;
        }
        
        .btn-ingresa:hover {
            background: linear-gradient(135deg, #F57C00 0%, #EF6C00 100%);
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(255, 152, 0, 0.4);
        }
        
        /* Estilo especial para la carpeta IMM */
        .imm-directory {
            background: linear-gradient(135deg, rgba(255, 152, 0, 0.1) 0%, rgba(255, 152, 0, 0.05) 100%) !important;
            border-left: 4px solid #FF9800 !important;
        }
        
        .imm-badge {
            background: #FF9800;
            color: white;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 11px;
            margin-left: 8px;
            font-weight: normal;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #666;
        }
        
        .empty-state i {
            font-size: 60px;
            color: #ddd;
            margin-bottom: 20px;
        }
        
        .footer {
            text-align: center;
            padding: 20px;
            color: #666;
            font-size: 14px;
            margin-top: 40px;
        }
        
        @media (max-width: 768px) {
            .header-content {
                flex-direction: column;
                text-align: center;
            }
            
            .user-section {
                flex-direction: column;
                gap: 10px;
            }
            
            .file-item {
                flex-direction: column;
                text-align: center;
                gap: 15px;
            }
            
            .file-icon {
                margin-right: 0;
            }
            
            .file-action {
                margin-left: 0;
            }
        }
    </style>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body>
    <div class="header">
        <div class="header-content">
            <div class="logo-section">
                <h1><i class="fas fa-folder-tree"></i> GEOFISCA - Archivos</h1>
            </div>
            <div class="user-section">
                <div class="user-info">
                    <i class="fas fa-user-circle"></i>
                    <strong><?php echo htmlspecialchars($_SESSION['usuario']); ?></strong>
                    <span style="margin-left: 10px; opacity: 0.8;">
                        (<?php echo date('d/m/Y H:i'); ?>)
                    </span>
                </div>
                <a href="?logout=1" class="btn-logout">
                    <i class="fas fa-sign-out-alt"></i> Cerrar Sesión
                </a>
            </div>
        </div>
    </div>

    <div class="container">
        <?php
        // Manejar logout
        if (isset($_GET['logout'])) {
            error_log("Logout - Usuario: {$_SESSION['usuario']} - IP: " . $_SERVER['REMOTE_ADDR']);
            session_destroy();
            header('Location: ' . $_SERVER['PHP_SELF']);
            exit;
        }

        // Obtener archivos del directorio
        $dir = "./";
        $hideName = array('.', '..', '.DS_Store', 'index.php', '.index.php', '.htaccess', '.git', '.gitignore');
        $files = scandir($dir);
        $files = array_reverse($files);
        
        // Filtrar archivos ocultos
        $filteredFiles = array_filter($files, function($filename) use ($hideName) {
            return !in_array($filename, $hideName);
        });
        
        $totalArchivos = count($filteredFiles);
        ?>
        
        <div class="file-list">
            <div class="file-header">
                <h2><i class="fas fa-file-alt"></i> Archivos Disponibles</h2>
                <div class="file-count"><?php echo $totalArchivos; ?> archivo<?php echo $totalArchivos != 1 ? 's' : ''; ?></div>
            </div>
            
            <div class="file-items">
                <?php if ($totalArchivos > 0): ?>
                    <?php foreach($filteredFiles as $filename): ?>
                        <?php
                        $file_path = $dir . $filename;
                        $file_parts = pathinfo($filename);
                        $name = $file_parts['filename'];
                        $extension = strtolower($file_parts['extension'] ?? '');
                        $update = date("d/m/Y H:i", filemtime($file_path));
                        $size = filesize($file_path);
                        $sizeFormatted = $size > 1048576 ? 
                            round($size / 1048576, 2) . ' MB' : 
                            round($size / 1024, 2) . ' KB';
                        
                        // Determinar si es un directorio
                        $is_dir = is_dir($file_path);
                        
                        // Verificar si es la carpeta IMM (o variaciones)
                        $is_imm_dir = false;
                        if ($is_dir) {
                            // Detectar IMM, imm, Imm, etc.
                            $is_imm_dir = preg_match('/^imm/i', $name);
                        }
                        // Determinar icono y color según tipo
                        $icon = 'fa-file';
                        $icon_color = '#4CAF50'; // Verde por defecto
                        
                        if ($is_imm_dir) {
                            $icon = 'fa-folder-open';
                            $icon_color = '#FF9800'; // Naranja para IMM
                        } elseif ($is_dir) {
                            $icon = 'fa-folder';
                            $icon_color = '#2196F3'; // Azul para otras carpetas
                        } elseif (in_array($extension, ['pdf'])) {
                            $icon = 'fa-file-pdf';
                            $icon_color = '#F44336'; // Rojo para PDF
                        } elseif (in_array($extension, ['doc', 'docx'])) {
                            $icon = 'fa-file-word';
                            $icon_color = '#2196F3'; // Azul para Word
                        } elseif (in_array($extension, ['xls', 'xlsx'])) {
                            $icon = 'fa-file-excel';
                            $icon_color = '#4CAF50'; // Verde para Excel
                        } elseif (in_array($extension, ['jpg', 'jpeg', 'png', 'gif'])) {
                            $icon = 'fa-file-image';
                            $icon_color = '#9C27B0'; // Púrpura para imágenes
                        } elseif (in_array($extension, ['zip', 'rar', 'tar', 'gz'])) {
                            $icon = 'fa-file-archive';
                            $icon_color = '#795548'; // Marrón para comprimidos
                        } elseif (in_array($extension, ['mp4', 'avi', 'mov'])) {
                            $icon = 'fa-file-video';
                            $icon_color = '#FF5722'; // Naranja oscuro para video
                        } elseif (in_array($extension, ['mp3', 'wav'])) {
                            $icon = 'fa-file-audio';
                            $icon_color = '#607D8B'; // Gris azulado para audio
                        }
                        ?>
                        
                        <div class="file-item <?php echo $is_imm_dir ? 'imm-directory' : ''; ?>">
                            <div class="file-icon" style="background: linear-gradient(135deg, <?php echo $icon_color; ?> 0%, <?php echo $icon_color; ?>80 100%);">
                                <i class="fas <?php echo $icon; ?>"></i>
                            </div>
                            <div class="file-info">
                                <div class="file-name">
                                    <?php echo htmlspecialchars($name); ?>
                                    <?php if ($is_imm_dir): ?>
                                        <span class="imm-badge">CARPETA ESPECIAL</span>
                                    <?php elseif ($is_dir): ?>
                                        <span style="color: #666; font-size: 12px; margin-left: 8px;">(Carpeta)</span>
                                    <?php endif; ?>
                                </div>
                                <div class="file-meta">
                                    <?php if ($is_dir): ?>
                                        <span><i class="fas fa-folder" style="color: <?php echo $icon_color; ?>;"></i> CARPETA</span>
                                    <?php else: ?>
                                        <span><i class="fas fa-file-signature" style="color: <?php echo $icon_color; ?>;"></i> .<?php echo strtoupper($extension ?: '---'); ?></span>
                                    <?php endif; ?>
                                    <span><i class="fas fa-calendar-alt" style="color: <?php echo $icon_color; ?>;"></i> <?php echo $update; ?></span>
                                    <?php if (!$is_dir): ?>
                                        <span><i class="fas fa-weight-hanging" style="color: <?php echo $icon_color; ?>;"></i> <?php echo $sizeFormatted; ?></span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="file-action">
                                <?php if ($is_imm_dir): ?>
                                    <!-- Enlace especial para la carpeta IMM -->
                                    <a href="./<?php echo urlencode($filename); ?>" class="btn-ingresa">
                                        <i class="fas fa-sign-in-alt"></i> 📁 INGRESA <?php echo $name; ?>
                                    </a>
                                <?php elseif ($is_dir): ?>
                                    <!-- Enlace normal para otras carpetas -->
                                    <a href="./<?php echo urlencode($filename); ?>" class="btn-download">
                                        <i class="fas fa-folder-open"></i> Abrir Carpeta
                                    </a>
                                <?php else: ?>
                                    <!-- Enlace para archivos -->
                                    <a href="./<?php echo urlencode($filename); ?>" class="btn-download" download>
                                        <i class="fas fa-download"></i> Descargar
                                    </a>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="empty-state">
                        <i class="fas fa-folder-open"></i>
                        <h3>No hay archivos disponibles</h3>
                        <p>No se encontraron archivos en el directorio principal.</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        
        <div class="footer">
            <p>
                <i class="fas fa-shield-alt"></i> Sistema seguro | 
                Último acceso: <?php echo $_SESSION['hora_login'] ?? 'N/A'; ?> | 
                Dirección IP: <?php echo $_SERVER['REMOTE_ADDR']; ?>
            </p>
            <p>© <?php echo date('Y'); ?> GEOFISCA - Todos los derechos reservados</p>
        </div>
    </div>
</body>
</html>
