#!/bin/bash

#-------------------------------------MODO DEBUG-----------------------------------------------------------------------
# Habilitar para ver todos los comandos ejecutados
DEBUG_MODE=false

# Si se pasa --debug como argumento, activar modo debug
if [[ "$1" == "--debug" ]]; then
    DEBUG_MODE=true
    set -x  # Mostrar todos los comandos ejecutados
    echo "[DEBUG] Modo debug activado"
fi

#-------------------------------------COLORES PARA MENSAJES------------------------------------------------------------
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
MAGENTA='\033[0;35m'
NC='\033[0m' # No Color
BOLD='\033[1m'

#-------------------------------------FUNCIONES DE MENSAJES------------------------------------------------------------
print_header() {
    echo ""
    echo -e "${CYAN}╔═══════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${CYAN}║                                                               ║${NC}"
    echo -e "${CYAN}║  ${BOLD}${MAGENTA}     APIDIAN - Instalación LAMP (Linux + Apache)${NC}${CYAN}             ║${NC}"
    echo -e "${CYAN}║  ${BLUE}     Laravel 8 + MySQL + Apache + PHP 8.0${NC}${CYAN}                    ║${NC}"
    echo -e "${CYAN}║                                                               ║${NC}"
    echo -e "${CYAN}╚═══════════════════════════════════════════════════════════════╝${NC}"
    echo ""
}

print_success() {
    echo -e "${GREEN}✓ $1${NC}"
}

print_error() {
    echo -e "${RED}✗ $1${NC}"
}

print_debug() {
    if [ "$DEBUG_MODE" = true ]; then
        echo -e "${MAGENTA}[DEBUG]${NC} $1"
    fi
}

print_warning() {
    echo -e "${YELLOW}⚠ $1${NC}"
}

print_info() {
    echo -e "${BLUE}ℹ $1${NC}"
}

print_step() {
    echo ""
    echo -e "${CYAN}${BOLD}▶ $1${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
}

# Función para ejecutar comandos con spinner y timeout
run_with_spinner() {
    local cmd="$1"
    local msg="$2"
    local timeout="${3:-300}"

    print_info "$msg"

    eval "$cmd" > /tmp/install_output.log 2>&1 &
    local pid=$!

    local spin='-\|/'
    local i=0
    local elapsed=0

    while kill -0 $pid 2>/dev/null; do
        i=$(( (i+1) %4 ))
        printf "\r${CYAN}   Procesando... ${spin:$i:1} (${elapsed}s)${NC}"
        sleep 1
        elapsed=$((elapsed + 1))

        if [ $elapsed -ge $timeout ]; then
            kill -9 $pid 2>/dev/null
            printf "\r"
            print_error "Tiempo de espera agotado después de ${timeout}s"
            print_info "Revisa los logs en /tmp/install_output.log"
            cat /tmp/install_output.log
            return 1
        fi
    done

    wait $pid
    local exit_code=$?
    printf "\r"

    if [ $exit_code -eq 0 ]; then
        return 0
    else
        print_error "Comando falló con código $exit_code"
        print_info "Últimas líneas del log:"
        tail -20 /tmp/install_output.log
        return $exit_code
    fi
}

# Habilitar modo debug si se pasa como argumento
if [[ "$*" == *"--debug"* ]]; then
    set -x
    print_warning "Modo DEBUG activado"
fi

# Mostrar header
print_header

#-------------------------------------VERIFICAR ROOT------------------------------------------------------------
if [ "$EUID" -ne 0 ]; then
    print_error "Este script debe ejecutarse como root"
    echo -e "${YELLOW}Usa: sudo bash $0${NC}"
    exit 1
fi

print_success "Ejecutando como root"

# Información del sistema
UBUNTU_VERSION=$(lsb_release -rs)
print_info "Sistema: Ubuntu $UBUNTU_VERSION"
print_info "Conectividad: $(ping -c 1 8.8.8.8 > /dev/null 2>&1 && echo 'OK' || echo 'SIN INTERNET')"

# Verificar versión de Ubuntu soportada
# Extraer versión mayor (ej: 20.04 → 20)
UBUNTU_MAJOR=$(echo "$UBUNTU_VERSION" | cut -d. -f1)

if [[ "$UBUNTU_MAJOR" -lt 20 ]]; then
    print_error "APIDIAN 2026 no es compatible con Ubuntu versiones menores a 20.04"
    print_warning "Tu versión: Ubuntu $UBUNTU_VERSION"
    print_info "Se requiere mínimo Ubuntu 20.04 LTS"
    exit 1
elif [[ ! "$UBUNTU_VERSION" =~ ^(20.04|22.04|24.04) ]]; then
    print_warning "Ubuntu $UBUNTU_VERSION no ha sido testeada oficialmente"
    print_info "Se procederá con instalación (compatibilidad parcial)"
fi

print_success "Versión de Ubuntu soportada"

# Mostrar tiempos estimados
echo ""
echo -e "${BLUE}⏱️  Tiempo estimado total: ${BOLD}20-30 minutos${NC}"
echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${CYAN}   • Instalación de LAMP Stack: ~5-8 min${NC}"
echo -e "${CYAN}   • Instalación de PHP 8.0 y extensiones: ~3-5 min${NC}"
echo -e "${CYAN}   • Clonación del repositorio: ~1-3 min${NC}"
echo -e "${CYAN}   • Instalación de dependencias Composer: ~5-8 min${NC}"
echo -e "${CYAN}   • Configuración de la aplicación: ~3-5 min${NC}"
echo -e "${CYAN}   • Configuración SSL (opcional): ~2-5 min${NC}"
echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""

#-------------------------------------PARAMETROS DE CONFIGURACION------------------------------------------------------
print_step "Configuración inicial"

# Puerto de Apache
DEFAULT_APACHE_PORT='80'
echo ""
echo -e "${BLUE}Configuración de Apache:${NC}"
read -p "$(echo -e ${CYAN}Puerto para Apache [${BOLD}$DEFAULT_APACHE_PORT${NC}${CYAN}]: ${NC})" APACHE_PORT
APACHE_PORT=${APACHE_PORT:-$DEFAULT_APACHE_PORT}
print_success "Puerto Apache: $APACHE_PORT"

# Puerto de MySQL
DEFAULT_MYSQL_PORT='3306'
echo ""
echo -e "${BLUE}Configuración de MySQL:${NC}"
read -p "$(echo -e ${CYAN}Puerto para MySQL [${BOLD}$DEFAULT_MYSQL_PORT${NC}${CYAN}]: ${NC})" MYSQL_PORT
MYSQL_PORT=${MYSQL_PORT:-$DEFAULT_MYSQL_PORT}
print_success "Puerto MySQL: $MYSQL_PORT"

# Dominio (opcional)
echo ""
echo -e "${BLUE}Configuración de dominio:${NC}"
echo -e "${YELLOW}Deja vacío si deseas acceder por IP${NC}"
read -p "$(echo -e ${CYAN}'Dominio [ejemplo: miempresa.com]: '${NC})" HOST

USE_DOMAIN=false
INSTALL_SSL=false
SERVER_IP=""

if [ -z "$HOST" ]; then
    print_warning "No se proporcionó dominio - configurando acceso por IP"

    # Detectar IP del servidor
    SERVER_IP=$(curl -4 -s ifconfig.me 2>/dev/null || curl -4 -s icanhazip.com 2>/dev/null || curl -4 -s ipinfo.io/ip 2>/dev/null)

    if [ -z "$SERVER_IP" ]; then
        SERVER_IP=$(hostname -I | grep -oE '\b([0-9]{1,3}\.){3}[0-9]{1,3}\b' | head -n1)
        if [ -z "$SERVER_IP" ]; then
            SERVER_IP=$(ip -4 addr show | grep -oP '(?<=inet\s)\d+(\.\d+){3}' | grep -v '127.0.0.1' | head -n1)
        fi
    fi

    print_success "IP detectada: ${BOLD}$SERVER_IP${NC}"
    read -p "$(echo -e ${YELLOW}¿Es correcta esta IP? [s/n]: ${NC})" confirm_ip
    if [ "$confirm_ip" != "s" ]; then
        read -p "$(echo -e ${CYAN}Ingresa la IP correcta: ${NC})" SERVER_IP
    fi

    APP_URL="http://$SERVER_IP"
    if [ "$APACHE_PORT" != "80" ]; then
        APP_URL="http://$SERVER_IP:$APACHE_PORT"
    fi
    SERVER_NAME="$SERVER_IP"

else
    USE_DOMAIN=true
    print_success "Dominio configurado: ${BOLD}$HOST${NC}"

    # Subdominio
    DEFAULT_SUBDOMAIN='api'
    echo ""
    read -p "$(echo -e ${CYAN}Subdominio para la API [${BOLD}$DEFAULT_SUBDOMAIN${NC}${CYAN}]: ${NC})" API_SUBDOMAIN
    API_SUBDOMAIN=${API_SUBDOMAIN:-$DEFAULT_SUBDOMAIN}
    print_success "Subdominio: ${BOLD}$API_SUBDOMAIN.$HOST${NC}"

    APP_URL="http://$API_SUBDOMAIN.$HOST"
    if [ "$APACHE_PORT" != "80" ]; then
        APP_URL="http://$API_SUBDOMAIN.$HOST:$APACHE_PORT"
    fi
    SERVER_NAME="$API_SUBDOMAIN.$HOST"

    # Preguntar por SSL
    echo ""
    read -p "$(echo -e ${YELLOW}¿Deseas instalar certificado SSL con Let\'s Encrypt? [s/n]: ${NC})" install_ssl
    if [ "$install_ssl" = "s" ]; then
        INSTALL_SSL=true
        print_success "SSL será instalado después de configurar Apache"
    else
        print_info "SSL no será instalado"
    fi
fi

#-------------------------------------URL DE REPOSITORIOS--------------------------------------------------------------
URL_API='https://gitlab.torresoftware.com/TorreSoftware/apidian-laravel-8-s3.git'

#-------------------------------------RUTA DE INSTALACION--------------------------------------------------------------
# Usar /var/www para que Apache tenga acceso
PATH_CURRENT="/var/www"

# Crear directorio si no existe
if [ ! -d "$PATH_CURRENT" ]; then
    mkdir -p "$PATH_CURRENT"
    print_info "Directorio /var/www creado"
fi

#-------------------------------------NOMBRE DE CARPETAS---------------------------------------------------------------
DIR_API='apidian'

#-------------------------------------SET DATA-------------------------------------------------------------------------
generate_password() {
    head /dev/urandom | tr -dc A-Za-z0-9 | head -c "$1" ; echo ''
}

print_step "Generando contraseñas seguras"
MYSQL_ROOT_PASSWORD=$(generate_password 20)
MYSQL_API_PASSWORD=$(generate_password 20)
print_success "Contraseñas generadas correctamente"

#-------------------------------------INSTALACION DE DEPENDENCIAS------------------------------------------------------
print_step "Instalando dependencias del sistema"
print_warning "Este proceso puede tomar 5-8 minutos, por favor espera..."
echo ""

if run_with_spinner "apt-get -y update" "Paso 1/6: Actualizando repositorios de Ubuntu..." 180; then
    print_success "Repositorios actualizados"
else
    print_error "Error actualizando repositorios"
    exit 1
fi

# Instalar paquetes base
print_info "Paso 2/6: Instalando paquetes base..."
if run_with_spinner "DEBIAN_FRONTEND=noninteractive apt-get -y install software-properties-common git-core curl wget zip unzip ca-certificates apt-transport-https gnupg" "Instalando git, curl, zip, etc..." 300; then
    print_success "Paquetes base instalados"
else
    print_error "Error instalando paquetes base"
    exit 1
fi

# Agregar repositorio de PHP 8.0
print_info "Paso 3/6: Agregando repositorio de PHP 8.0..."

# Para Ubuntu 24.04, intentar agregar el repositorio pero no fallar si no funciona
if [[ "$UBUNTU_VERSION" == "24.04" ]]; then
    print_warning "Ubuntu 24.04 detectado - intentando agregar PPA de Ondrej..."
    add-apt-repository ppa:ondrej/php -y 2>/dev/null || {
        print_warning "PPA no disponible para Ubuntu 24.04, usando repositorios oficiales"
        print_info "Se instalará PHP 8.3 (versión nativa de Ubuntu 24.04)"
    }
else
    # Para Ubuntu 20.04 y 22.04
    if add-apt-repository ppa:ondrej/php -y > /dev/null 2>&1; then
        print_success "Repositorio PHP agregado"
    else
        print_error "Error agregando repositorio PHP"
        exit 1
    fi
fi

if run_with_spinner "apt-get -y update" "Actualizando índice de paquetes..." 180; then
    print_success "Índice actualizado"
else
    print_warning "Actualización con advertencias, continuando..."
fi

# Instalar Apache
print_info "Paso 4/6: Instalando Apache 2..."
if run_with_spinner "DEBIAN_FRONTEND=noninteractive apt-get -y install apache2" "Instalando servidor web Apache..." 300; then
    systemctl enable apache2 > /dev/null 2>&1
    print_success "Apache instalado y habilitado"
else
    print_error "Error instalando Apache"
    exit 1
fi

# Instalar MariaDB
print_info "Paso 5/6: Instalando MariaDB Server..."

if run_with_spinner "DEBIAN_FRONTEND=noninteractive apt-get -y install mariadb-server mariadb-client" "Instalando MariaDB Server..." 300; then
    systemctl enable mariadb > /dev/null 2>&1
    systemctl start mariadb > /dev/null 2>&1
    print_success "MariaDB instalado y habilitado"

    # Configurar contraseña de root MariaDB
    print_info "Configurando contraseña de root MariaDB..."

    # Esperar a que MariaDB esté completamente iniciado
    sleep 3

    # MariaDB en instalación fresca no tiene contraseña
    if mysql -uroot -e "SELECT 1;" > /dev/null 2>&1; then
        print_debug "Configurando contraseña de root..."

        # Configurar contraseña usando mysql_secure_installation automático
        mysql -uroot << MARIADB_SECURE
-- Establecer contraseña de root
ALTER USER 'root'@'localhost' IDENTIFIED BY '$MYSQL_ROOT_PASSWORD';
-- Eliminar usuarios anónimos
DELETE FROM mysql.user WHERE User='';
-- Deshabilitar login remoto de root
DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');
-- Eliminar base de datos de prueba
DROP DATABASE IF EXISTS test;
DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%';
-- Refrescar privilegios
FLUSH PRIVILEGES;
MARIADB_SECURE

        # Verificar que la contraseña funciona
        if mysql -uroot -p$MYSQL_ROOT_PASSWORD -e "SELECT 1;" > /dev/null 2>&1; then
            print_success "MariaDB configurado y asegurado correctamente"
        else
            print_error "Error al verificar la contraseña de root"
            exit 1
        fi
    elif mysql -uroot -p$MYSQL_ROOT_PASSWORD -e "SELECT 1;" > /dev/null 2>&1; then
        print_success "MariaDB ya tiene contraseña configurada"
    else
        print_error "No se puede acceder a MariaDB"
        echo ""
        echo -e "${YELLOW}Ejecuta el script de limpieza primero:${NC}"
        echo -e "  ${GREEN}./LimpiarInstalacionLAMP.sh${NC}"
        exit 1
    fi
else
    print_error "Error instalando MariaDB"
    exit 1
fi

# Instalar PHP y extensiones
print_info "Paso 6/6: Instalando PHP y extensiones necesarias..."

# Detectar versión de PHP disponible según Ubuntu
# Estrategia: usar versiones nativas de cada Ubuntu para evitar problemas de repositorios
if [[ "$UBUNTU_VERSION" == "24.04" ]]; then
    # Ubuntu 24.04 viene con PHP 8.3 por defecto
    PHP_VERSION="8.3"
    print_info "Ubuntu 24.04: Se instalará PHP 8.3 (nativa)"
elif [[ "$UBUNTU_VERSION" == "22.04" ]]; then
    # Ubuntu 22.04 viene con PHP 8.1 nativo (NO 8.0)
    PHP_VERSION="8.1"
    print_info "Ubuntu 22.04: Se instalará PHP 8.1 (nativa)"
elif [[ "$UBUNTU_VERSION" == "20.04" ]]; then
    # Ubuntu 20.04 viene con PHP 7.4 por defecto
    PHP_VERSION="7.4"
    print_info "Ubuntu 20.04: Se instalará PHP 7.4 (nativa)"
    print_warning "Nota: Laravel 8 requiere PHP >= 7.4"
else
    # Versiones de Ubuntu no testeadas formalmente
    # Intentar con versión moderna
    print_warning "Ubuntu $UBUNTU_VERSION - Intentando con PHP 8.1"
    PHP_VERSION="8.1"
fi

PHP_PACKAGES="php${PHP_VERSION} php${PHP_VERSION}-fpm php${PHP_VERSION}-mysql php${PHP_VERSION}-mbstring php${PHP_VERSION}-xml php${PHP_VERSION}-bcmath php${PHP_VERSION}-curl php${PHP_VERSION}-gd php${PHP_VERSION}-zip php${PHP_VERSION}-soap php${PHP_VERSION}-intl php${PHP_VERSION}-readline php${PHP_VERSION}-imap libapache2-mod-php${PHP_VERSION}"

# Intentar instalar php-redis (puede no estar disponible en todas las versiones)
if run_with_spinner "DEBIAN_FRONTEND=noninteractive apt-get -y install $PHP_PACKAGES" "Instalando PHP ${PHP_VERSION} y extensiones (gd, soap, intl, etc.)..." 400; then
    print_success "PHP ${PHP_VERSION} y extensiones instaladas"

    # Intentar instalar php-redis (opcional)
    print_info "Intentando instalar extensión Redis..."
    apt-get -y install php${PHP_VERSION}-redis 2>/dev/null && print_success "Extensión Redis instalada" || print_warning "Extensión Redis no disponible (opcional)"
else
    print_error "Error instalando PHP"
    exit 1
fi

# Verificar versión de PHP
PHP_VERSION=$(php -v | head -n 1)
print_success "Versión instalada: $PHP_VERSION"

# Instalar Composer
print_step "Instalando Composer"
print_info "Descargando e instalando Composer..."

# Método directo y confiable
if curl -sS https://getcomposer.org/installer | php; then
    print_success "Composer descargado"

    print_info "Moviendo Composer a /usr/local/bin..."

    # Buscar composer.phar en ubicaciones comunes
    if [ -f "composer.phar" ]; then
        COMPOSER_PATH="composer.phar"
    elif [ -f "/root/composer.phar" ]; then
        COMPOSER_PATH="/root/composer.phar"
    elif [ -f "$HOME/composer.phar" ]; then
        COMPOSER_PATH="$HOME/composer.phar"
    else
        print_error "No se encontró composer.phar"
        exit 1
    fi

    print_debug "Moviendo $COMPOSER_PATH a /usr/local/bin/composer"
    if mv "$COMPOSER_PATH" /usr/local/bin/composer 2>&1; then
        print_debug "Archivo movido exitosamente"

        chmod +x /usr/local/bin/composer
        print_debug "Permisos de ejecución aplicados"

        # Verificar que el archivo existe (sin ejecutarlo)
        if [ -f "/usr/local/bin/composer" ]; then
            print_success "Composer instalado en /usr/local/bin/composer"
            print_debug "Tamaño: $(ls -lh /usr/local/bin/composer | awk '{print $5}')"
        else
            print_error "El archivo no se encuentra en /usr/local/bin/composer"
            exit 1
        fi
    else
        print_error "Error al mover Composer a /usr/local/bin"
        exit 1
    fi
else
    print_error "Error al descargar/instalar Composer"
    exit 1
fi

# Instalar certbot si se requiere SSL
if [ "$INSTALL_SSL" = true ]; then
    print_step "Instalando Certbot para SSL"
    if run_with_spinner "DEBIAN_FRONTEND=noninteractive apt-get -y install certbot" "Instalando Certbot..." 180; then
        print_success "Certbot instalado"
    else
        print_warning "Error instalando Certbot, SSL no estará disponible"
        INSTALL_SSL=false
    fi
fi

#-------------------------------------CONFIGURAR MYSQL-----------------------------------------------------------------
print_step "Configurando MySQL"

# Verificar que podemos conectarnos a MySQL con la contraseña de root
print_info "Verificando conexión MySQL root..."
if ! mysql -uroot -p$MYSQL_ROOT_PASSWORD -e "SELECT 1;" > /dev/null 2>&1; then
    print_error "No se pudo conectar a MySQL con la contraseña de root"
    echo ""
    echo -e "${YELLOW}La contraseña de root configurada no funciona.${NC}"
    echo -e "${CYAN}Intentando conectar sin contraseña...${NC}"

    if mysql -uroot -e "SELECT 1;" > /dev/null 2>&1; then
        print_warning "MySQL root no tiene contraseña configurada"
        print_info "Configurando contraseña ahora..."

        mysql -uroot << MYSQL_ROOT_FIX
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '$MYSQL_ROOT_PASSWORD';
FLUSH PRIVILEGES;
MYSQL_ROOT_FIX

        if mysql -uroot -p$MYSQL_ROOT_PASSWORD -e "SELECT 1;" > /dev/null 2>&1; then
            print_success "Contraseña de root configurada correctamente"
        else
            print_error "No se pudo configurar la contraseña de root"
            exit 1
        fi
    else
        print_error "No se puede acceder a MySQL"
        echo ""
        echo -e "${YELLOW}Opciones:${NC}"
        echo -e "  1. Resetear contraseña manualmente"
        echo -e "  2. Reinstalar MySQL: ${GREEN}apt-get purge mysql-server && apt-get install mysql-server${NC}"
        exit 1
    fi
else
    print_success "Conexión MySQL root verificada"
fi

# Configurar puerto de MariaDB si no es el default
if [ "$MYSQL_PORT" != "3306" ]; then
    print_info "Configurando MariaDB en puerto $MYSQL_PORT..."
    sed -i "/\[mysqld\]/a port = $MYSQL_PORT" /etc/mysql/mariadb.conf.d/50-server.cnf
    systemctl restart mariadb
    sleep 3  # Esperar a que MariaDB reinicie
    print_success "Puerto MariaDB configurado"
fi

# Crear base de datos y usuario
print_info "Creando base de datos y usuario..."

# Eliminar usuario existente si hay alguno corrupto
mysql -uroot -p$MYSQL_ROOT_PASSWORD -e "DROP USER IF EXISTS '$DIR_API'@'localhost';" 2>/dev/null
print_debug "Usuario existente eliminado (si existía)"

# Crear base de datos y usuario
mysql -uroot -p$MYSQL_ROOT_PASSWORD << MYSQL_SCRIPT
CREATE DATABASE IF NOT EXISTS $DIR_API CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER '$DIR_API'@'localhost' IDENTIFIED BY '$MYSQL_API_PASSWORD';
GRANT ALL PRIVILEGES ON $DIR_API.* TO '$DIR_API'@'localhost';
FLUSH PRIVILEGES;
MYSQL_SCRIPT

if [ $? -eq 0 ]; then
    print_success "Base de datos '$DIR_API' creada"
    print_success "Usuario '$DIR_API' creado con permisos"

    # Verificar que el usuario puede conectarse
    print_debug "Verificando conexión MySQL..."
    if mysql -u$DIR_API -p$MYSQL_API_PASSWORD -e "USE $DIR_API;" 2>/dev/null; then
        print_success "Conexión MySQL verificada correctamente"
    else
        print_error "No se pudo verificar la conexión MySQL"
        echo ""
        echo -e "${YELLOW}Intentando diagnosticar el problema...${NC}"

        # Mostrar información del usuario
        mysql -uroot -p$MYSQL_ROOT_PASSWORD -e "SELECT User, Host FROM mysql.user WHERE User='$DIR_API';" 2>/dev/null

        # Intentar recrear el usuario con método alternativo
        print_warning "Recreando usuario con autenticación nativa..."
        mysql -uroot -p$MYSQL_ROOT_PASSWORD << MYSQL_FIX
DROP USER IF EXISTS '$DIR_API'@'localhost';
CREATE USER '$DIR_API'@'localhost' IDENTIFIED WITH mysql_native_password BY '$MYSQL_API_PASSWORD';
GRANT ALL PRIVILEGES ON $DIR_API.* TO '$DIR_API'@'localhost';
FLUSH PRIVILEGES;
MYSQL_FIX

        # Verificar nuevamente
        if mysql -u$DIR_API -p$MYSQL_API_PASSWORD -e "USE $DIR_API;" 2>/dev/null; then
            print_success "Conexión MySQL corregida"
        else
            print_error "Aún hay problemas con MySQL"
            echo ""
            echo -e "${CYAN}Credenciales MySQL:${NC}"
            echo -e "  Usuario: ${YELLOW}$DIR_API${NC}"
            echo -e "  Base de datos: ${YELLOW}$DIR_API${NC}"
            echo -e "  Puerto: ${YELLOW}$MYSQL_PORT${NC}"
            echo ""
            echo -e "${YELLOW}Puedes verificar manualmente con:${NC}"
            echo -e "  ${GREEN}mysql -u$DIR_API -p$MYSQL_API_PASSWORD -e 'SHOW DATABASES;'${NC}"
            echo ""
            read -p "¿Deseas continuar de todos modos? [s/N]: " CONTINUE_ANYWAY
            if [[ ! "$CONTINUE_ANYWAY" =~ ^[sS]$ ]]; then
                exit 1
            fi
        fi
    fi
else
    print_error "Error al crear base de datos o usuario"
    exit 1
fi

#-------------------------------------CLONAR REPOSITORIO---------------------------------------------------------------
print_step "Clonando repositorio de la aplicación"
print_info "Repositorio: $URL_API"

# Verificar si el repositorio requiere autenticación
if [[ "$URL_API" == *"@"* ]]; then
    print_info "Repositorio privado detectado, clonando directamente..."
else
    echo ""
    echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${CYAN}   El repositorio requiere autenticación${NC}"
    echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo ""
    echo -e "${CYAN}Opciones de autenticación:${NC}"
    echo -e "  ${GREEN}1)${NC} Usuario y contraseña de GitLab"
    echo -e "  ${GREEN}2)${NC} Token de acceso personal (recomendado)"
    echo ""
    read -p "Selecciona opción [1/2]: " AUTH_METHOD

    if [[ "$AUTH_METHOD" == "2" ]]; then
        echo ""
        read -p "Ingresa tu token de acceso personal de GitLab: " -s GITLAB_TOKEN
        echo ""

        # Extraer dominio y ruta del repositorio
        REPO_URL=$(echo "$URL_API" | sed 's|https://||')
        URL_API="https://oauth2:${GITLAB_TOKEN}@${REPO_URL}"

        print_info "Usando autenticación por token..."
    else
        print_warning "Se solicitarán credenciales durante el clone..."
        print_info "Ingresa tu usuario y contraseña de GitLab cuando se soliciten"
        echo ""
    fi
fi

print_warning "Clonando repositorio... esto puede tardar 1-3 minutos"

# Forzar prompt de credenciales si es necesario
export GIT_TERMINAL_PROMPT=1

if git clone $URL_API $PATH_CURRENT/$DIR_API; then
    print_success "Repositorio clonado exitosamente"
else
    print_error "Error al clonar el repositorio"
    echo ""
    echo -e "${YELLOW}Posibles soluciones:${NC}"
    echo -e "  • Verifica tus credenciales de GitLab"
    echo -e "  • Asegúrate de tener acceso al repositorio"
    echo -e "  • Genera un token de acceso: ${CYAN}https://gitlab.com/-/profile/personal_access_tokens${NC}"
    echo -e "  • Clona manualmente: ${GREEN}git clone $URL_API $PATH_CURRENT/$DIR_API${NC}"
    echo ""
    exit 1
fi

cd "$PATH_CURRENT/$DIR_API"

#-------------------------------------DESCOMPRIMIR STORAGE-------------------------------------------------------------
print_step "Preparando directorio storage"
if [ -f "storage.zip" ]; then
    print_info "Descomprimiendo directorio storage..."
    unzip -o storage.zip > /dev/null 2>&1
    print_success "Directorio storage configurado"
else
    print_warning "storage.zip no encontrado, creando directorios manualmente..."
    mkdir -p storage/{app,framework,logs}
    mkdir -p storage/framework/{cache,sessions,views}
    print_success "Directorios storage creados"
fi

#-------------------------------------INSTALAR DEPENDENCIAS COMPOSER---------------------------------------------------
print_step "Instalando dependencias PHP con Composer"
echo -e "${YELLOW}⏳ Este proceso puede tomar 5-8 minutos...${NC}"
print_info "Descargando paquetes de Laravel, Guzzle, PHPUnit, etc..."

if composer install --no-interaction --optimize-autoloader; then
    print_success "Dependencias instaladas"
else
    print_error "Error instalando dependencias de Composer"
    exit 1
fi

#-------------------------------------CONFIGURAR .env------------------------------------------------------------------
print_step "Configurando variables de entorno"

cat > .env << ENVEOF
APP_NAME=Laravel
APP_ENV=production
APP_KEY=
APP_DEBUG=false
APP_URL=$APP_URL

LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=$MYSQL_PORT
DB_DATABASE=$DIR_API
DB_USERNAME=$DIR_API
DB_PASSWORD=$MYSQL_API_PASSWORD

BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DRIVER=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

MEMCACHED_HOST=127.0.0.1

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_MAILER=smtp
MAIL_HOST=mailhog
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="\${APP_NAME}"

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="\${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="\${PUSHER_APP_CLUSTER}"

FORCE_HTTPS=false
ENVEOF

print_success "Archivo .env creado"

#-------------------------------------COPIAR ARCHIVOS URN--------------------------------------------------------------
print_info "Copiando archivos URN y plantillas XML..."

if [ -d "resources/templates/xml/urn" ]; then
    cp resources/templates/xml/urn/*.* resources/templates/xml 2>/dev/null || true
    print_success "Plantillas XML copiadas"
fi

if [ -d "vendor/ubl21dian/torresoftware/src/XAdES/urn" ]; then
    cp vendor/ubl21dian/torresoftware/src/XAdES/urn/*.* vendor/ubl21dian/torresoftware/src/XAdES 2>/dev/null || true
    print_success "Archivos XAdES copiados"
fi

if [ -f "resources/templates/xml/urn/Request.php" ]; then
    cp resources/templates/xml/urn/Request.php vendor/laravel/framework/src/Illuminate/Http/Request.php
    print_success "Request.php personalizado copiado"
fi

#-------------------------------------PERMISOS---------------------------------------------------------------------
print_step "Configurando permisos"

chown -R www-data:www-data $PATH_CURRENT/$DIR_API
chmod -R 755 $PATH_CURRENT/$DIR_API
chmod -R 775 $PATH_CURRENT/$DIR_API/storage
chmod -R 775 $PATH_CURRENT/$DIR_API/bootstrap/cache

print_success "Permisos configurados para www-data"

#-------------------------------------CONFIGURAR OPENSSL LEGACY--------------------------------------------------------
print_step "Verificando version de OpenSSL"

# Detectar version de OpenSSL
OPENSSL_VERSION=$(openssl version | grep -oP '\d+\.\d+\.\d+' | head -n1)
OPENSSL_MAJOR=$(echo "$OPENSSL_VERSION" | cut -d. -f1)

print_info "OpenSSL version detectada: $OPENSSL_VERSION"

if [ "$OPENSSL_MAJOR" -ge 3 ]; then
    print_info "OpenSSL 3+ detectado - Configurando legacy provider..."

    OPENSSL_CNF="/etc/ssl/openssl.cnf"

    if [ ! -f "$OPENSSL_CNF" ]; then
        print_error "No se encontro $OPENSSL_CNF"
        exit 1
    fi

    # Crear backup
    if [ ! -f "${OPENSSL_CNF}.backup" ]; then
        cp $OPENSSL_CNF ${OPENSSL_CNF}.backup
        print_success "Backup creado: ${OPENSSL_CNF}.backup"
    fi

    # Verificar si ya esta configurado
    if grep -q "^\[legacy_sect\]" $OPENSSL_CNF && grep -q "legacy = legacy_sect" $OPENSSL_CNF; then
        print_success "OpenSSL legacy ya configurado"
    else
        print_info "Configurando providers en $OPENSSL_CNF..."

    # Agregar configuración al inicio del archivo si no existe
    if ! grep -q "^openssl_conf = openssl_init" $OPENSSL_CNF; then
        sed -i '1i openssl_conf = openssl_init\n' $OPENSSL_CNF
    fi

    # Agregar sección [openssl_init] si no existe
    if ! grep -q "^\[openssl_init\]" $OPENSSL_CNF; then
        sed -i '/^openssl_conf = openssl_init/a \\n[openssl_init]\nproviders = provider_sect\n' $OPENSSL_CNF
    fi

    # Agregar o reemplazar [provider_sect]
    if grep -q "^\[provider_sect\]" $OPENSSL_CNF; then
        # Si existe, reemplazar su contenido
        sed -i '/^\[provider_sect\]/,/^\[/ { /^\[provider_sect\]/!{ /^\[/!d } }' $OPENSSL_CNF
        sed -i '/^\[provider_sect\]/a default = default_sect\nlegacy = legacy_sect\n' $OPENSSL_CNF
    else
        # Si no existe, agregarla después de [openssl_init]
        sed -i '/^\[openssl_init\]/,/^\[/ { /^\[/a \\n[provider_sect]\ndefault = default_sect\nlegacy = legacy_sect\n
}' $OPENSSL_CNF
    fi

    # Agregar o reemplazar [default_sect]
    if grep -q "^\[default_sect\]" $OPENSSL_CNF; then
        sed -i '/^\[default_sect\]/,/^\[/ { /^\[default_sect\]/!{ /^\[/!d } }' $OPENSSL_CNF
        sed -i '/^\[default_sect\]/a activate = 1\n' $OPENSSL_CNF
    else
        echo -e "\n[default_sect]\nactivate = 1" >> $OPENSSL_CNF
    fi

    # Agregar [legacy_sect] si no existe
    if ! grep -q "^\[legacy_sect\]" $OPENSSL_CNF; then
        echo -e "\n[legacy_sect]\nactivate = 1" >> $OPENSSL_CNF
    fi

        print_success "OpenSSL legacy configurado"
    fi

    # Verificar providers
    print_info "Verificando providers de OpenSSL..."
    if openssl list -providers 2>/dev/null | grep -q "legacy"; then
        print_success "Provider legacy activado correctamente"
    else
        print_warning "Provider legacy configurado (se cargara al usar OpenSSL)"
    fi
else
    print_success "OpenSSL $OPENSSL_VERSION no requiere legacy provider"
    print_info "Los algoritmos legacy estan disponibles por defecto en OpenSSL 1.x"
fi

#-------------------------------------CONFIGURACION LARAVEL------------------------------------------------------------
print_step "Configurando aplicación Laravel"

print_info "Generando clave de aplicación..."
php artisan key:generate --force
print_success "Clave de aplicación generada"

print_info "Limpiando cache..."
php artisan config:clear
php artisan cache:clear
print_success "Cache limpiado"

print_info "Ejecutando migraciones y seeders de base de datos (1-2 minutos)..."
if php artisan migrate:refresh --seed --force; then
    print_success "Base de datos inicializada correctamente"
else
    print_warning "Error en seeders, intentando solo migraciones..."
    if php artisan migrate:fresh --force; then
        print_success "Migraciones ejecutadas (sin seeders)"
    else
        print_error "Error en migraciones"
        print_info "Verifica la conexión a MySQL y las credenciales"
        exit 1
    fi
fi

print_info "Creando enlaces simbólicos de storage..."
php artisan storage:link
print_success "Storage enlazado"

print_info "Optimizando configuración..."
php artisan config:cache
php artisan route:cache
print_success "Configuración optimizada"

#-------------------------------------CONFIGURAR APACHE----------------------------------------------------------------
print_step "Configurando Apache"

# Habilitar módulos necesarios
print_info "Habilitando módulos de Apache..."
a2enmod rewrite ssl headers > /dev/null 2>&1
print_success "Módulos habilitados: rewrite, ssl, headers"

# Cambiar puerto de Apache si no es 80
if [ "$APACHE_PORT" != "80" ]; then
    print_info "Configurando Apache en puerto $APACHE_PORT..."

    # Actualizar ports.conf
    if grep -q "^Listen 80" /etc/apache2/ports.conf; then
        sed -i "s/^Listen 80/Listen $APACHE_PORT/g" /etc/apache2/ports.conf
    else
        # Si no existe Listen 80, agregarlo
        echo "Listen $APACHE_PORT" >> /etc/apache2/ports.conf
    fi

    # Asegurar que no haya configuraciones conflictivas
    sed -i "s/<VirtualHost \*:80>/<VirtualHost *:$APACHE_PORT>/g" /etc/apache2/sites-available/*.conf 2>/dev/null

    print_success "Puerto Apache configurado en $APACHE_PORT"
fi

# Configurar seguridad global de Apache
print_info "Configurando seguridad de Apache..."
if ! grep -q "^ServerTokens" /etc/apache2/apache2.conf; then
    echo -e "\n# Configuración de seguridad\nServerTokens Prod\nServerSignature Off" >> /etc/apache2/apache2.conf
    print_success "Configuración de seguridad agregada"
fi

# Crear VirtualHost
print_info "Creando VirtualHost..."

VHOST_CONF="/etc/apache2/sites-available/$DIR_API.conf"

cat > $VHOST_CONF << VHOSTEOF
<VirtualHost *:$APACHE_PORT>
    ServerName $SERVER_NAME
    DocumentRoot $PATH_CURRENT/$DIR_API/public

    <Directory $PATH_CURRENT/$DIR_API/public>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog \${APACHE_LOG_DIR}/${DIR_API}_error.log
    CustomLog \${APACHE_LOG_DIR}/${DIR_API}_access.log combined

    # Configuración PHP
    <FilesMatch \.php$>
        SetHandler application/x-httpd-php
    </FilesMatch>

    # Headers de seguridad
    <IfModule mod_headers.c>
        Header always set X-Content-Type-Options "nosniff"
        Header always set X-Frame-Options "SAMEORIGIN"
        Header always set X-XSS-Protection "1; mode=block"
    </IfModule>
</VirtualHost>
VHOSTEOF

print_success "VirtualHost creado: $VHOST_CONF"

# Deshabilitar sitio por defecto y habilitar el nuevo
a2dissite 000-default > /dev/null 2>&1
a2ensite $DIR_API > /dev/null 2>&1
print_success "Sitio '$DIR_API' habilitado"

# Verificar configuración de Apache
print_info "Verificando configuración de Apache..."
if apache2ctl configtest 2>&1 | tee /tmp/apache_test.log; then
    print_success "Configuración de Apache válida"
else
    print_error "Error en configuración de Apache"
    echo ""
    echo -e "${YELLOW}Diagnóstico:${NC}"
    cat /tmp/apache_test.log
    echo ""

    # Intentar corregir errores comunes
    print_warning "Intentando corregir errores..."

    # Error común: ServerName no definido
    if ! grep -q "^ServerName" /etc/apache2/apache2.conf; then
        echo "ServerName localhost" >> /etc/apache2/apache2.conf
        print_info "ServerName agregado a apache2.conf"
    fi

    # Verificar nuevamente
    if apache2ctl configtest > /dev/null 2>&1; then
        print_success "Errores corregidos"
    else
        print_error "No se pudieron corregir todos los errores"
        echo -e "${CYAN}Continuar de todos modos? [s/N]:${NC} "
        read -p "" CONTINUE_APACHE
        if [[ ! "$CONTINUE_APACHE" =~ ^[sS]$ ]]; then
            exit 1
        fi
    fi
fi

# Reiniciar Apache
print_info "Reiniciando Apache..."
if systemctl restart apache2 2>&1 | tee /tmp/apache_restart.log; then
    sleep 2
    if systemctl is-active --quiet apache2; then
        print_success "Apache reiniciado y funcionando correctamente"
    else
        print_error "Apache reinició pero no está activo"
        echo ""
        echo -e "${YELLOW}Diagnóstico:${NC}"
        systemctl status apache2 --no-pager -l
        echo ""
        journalctl -xeu apache2.service --no-pager | tail -20
    fi
else
    print_error "Error al reiniciar Apache"
    echo ""
    echo -e "${YELLOW}Diagnóstico:${NC}"
    cat /tmp/apache_restart.log
    echo ""
    systemctl status apache2 --no-pager -l
fi

#-------------------------------------INSTALAR SSL (OPCIONAL)----------------------------------------------------------
if [ "$INSTALL_SSL" = true ]; then
    print_step "Instalando certificado SSL"
    print_warning "IMPORTANTE: Asegúrate de que el DNS apunte correctamente al servidor"
    echo ""
    echo -e "${YELLOW}┌───────────────────────────────────────────────────────┐${NC}"
    echo -e "${YELLOW}│ ${BOLD}INSTRUCCIONES IMPORTANTES:${NC}${YELLOW}                            │${NC}"
    echo -e "${YELLOW}├───────────────────────────────────────────────────────┤${NC}"
    echo -e "${YELLOW}│ 1. Copiar los registros TXT que aparezcan             │${NC}"
    echo -e "${RED}${BOLD}│ 2. NO usar [Ctrl+C] ya que cancelará el proceso       │${NC}"
    echo -e "${YELLOW}│ 3. Ingresar tu correo electrónico                     │${NC}"
    echo -e "${YELLOW}│ 4. Aceptar los términos y condiciones                 │${NC}"
    echo -e "${YELLOW}│ 5. Este método requiere renovación MANUAL cada 90 días│${NC}"
    echo -e "${YELLOW}└───────────────────────────────────────────────────────┘${NC}"
    echo ""

    certbot certonly --manual -d *.$HOST -d $HOST --agree-tos --no-bootstrap --manual-public-ip-logging-ok --preferred-challenges dns-01 --server https://acme-v02.api.letsencrypt.org/directory

    if [ -f "/etc/letsencrypt/live/$HOST/privkey.pem" ]; then
        print_success "Certificado SSL generado exitosamente"

        # Actualizar VirtualHost para SSL
        print_info "Configurando VirtualHost para HTTPS..."

        VHOST_SSL_CONF="/etc/apache2/sites-available/$DIR_API-ssl.conf"

        cat > $VHOST_SSL_CONF << VHOSTSSLEOF
<VirtualHost *:443>
    ServerName $SERVER_NAME
    DocumentRoot $PATH_CURRENT/$DIR_API/public

    SSLEngine on
    SSLCertificateFile /etc/letsencrypt/live/$HOST/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/$HOST/privkey.pem

    <Directory $PATH_CURRENT/$DIR_API/public>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog \${APACHE_LOG_DIR}/${DIR_API}_ssl_error.log
    CustomLog \${APACHE_LOG_DIR}/${DIR_API}_ssl_access.log combined

    <FilesMatch \.php$>
        SetHandler application/x-httpd-php
    </FilesMatch>

    # Headers de seguridad
    <IfModule mod_headers.c>
        Header always set X-Content-Type-Options "nosniff"
        Header always set X-Frame-Options "SAMEORIGIN"
        Header always set X-XSS-Protection "1; mode=block"
        Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
    </IfModule>
</VirtualHost>

# Redirección HTTP a HTTPS
<VirtualHost *:$APACHE_PORT>
    ServerName $SERVER_NAME
    Redirect permanent / https://$SERVER_NAME/
</VirtualHost>
VHOSTSSLEOF

        # Habilitar puerto 443 en Apache
        if ! grep -q "Listen 443" /etc/apache2/ports.conf; then
            echo "Listen 443" >> /etc/apache2/ports.conf
        fi

        # Habilitar sitio SSL
        a2ensite $DIR_API-ssl > /dev/null 2>&1
        print_success "VirtualHost SSL configurado"

        # Actualizar .env para HTTPS
        cd "$PATH_CURRENT/$DIR_API"
        sed -i "s|APP_URL=http://|APP_URL=https://|g" .env
        sed -i "/FORCE_HTTPS=/c\FORCE_HTTPS=true" .env

        php artisan config:cache
        php artisan cache:clear
        print_success "Configuración HTTPS aplicada"

        # Reiniciar Apache
        systemctl restart apache2
        print_success "Apache reiniciado con SSL"

        APP_URL="https://$SERVER_NAME"
    else
        print_error "No se pudo generar el certificado SSL"
        print_warning "La aplicación funcionará solo con HTTP"
    fi
fi

#-------------------------------------GENERAR ARCHIVO DE CREDENCIALES-------------------------------------------------
print_step "Finalizando instalación"

mkdir -p $PATH_CURRENT/setup
cat > $PATH_CURRENT/setup/private.txt << CREDSEOF
MYSQL
----------------------------------
Host        = localhost
Port        = $MYSQL_PORT
DB_USERNAME = root
DB_PASSWORD = $MYSQL_ROOT_PASSWORD

API Database
----------------------------------
DB_NAME     = $DIR_API
DB_USERNAME = $DIR_API
DB_PASSWORD = $MYSQL_API_PASSWORD

API
----------------------------------
PATH = $PATH_CURRENT/$DIR_API
URL  = $APP_URL

Apache
----------------------------------
Port = $APACHE_PORT
VirtualHost = /etc/apache2/sites-available/$DIR_API.conf
Logs = /var/log/apache2/${DIR_API}_*.log

CREDSEOF

print_success "Archivo de credenciales creado en: $PATH_CURRENT/setup/private.txt"

#-------------------------------------RESUMEN FINAL--------------------------------------------------------------------
echo ""
echo -e "${GREEN}${BOLD}╔═══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}${BOLD}║                                                               ║${NC}"
echo -e "${GREEN}${BOLD}║  ✓  INSTALACIÓN COMPLETADA EXITOSAMENTE                       ║${NC}"
echo -e "${GREEN}${BOLD}║                                                               ║${NC}"
echo -e "${GREEN}${BOLD}╚═══════════════════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "${CYAN}${BOLD}📋 RESUMEN DE LA INSTALACIÓN:${NC}"
echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${GREEN}✓ Stack:${NC} LAMP (Linux + Apache + MySQL + PHP 8.0)"
echo -e "${GREEN}✓ PHP:${NC} $(php -v | head -n1 | grep -oP 'PHP \d+\.\d+\.\d+')"
echo -e "${GREEN}✓ MySQL:${NC} Puerto $MYSQL_PORT"
echo -e "${GREEN}✓ Apache:${NC} Puerto $APACHE_PORT"
if [ "$USE_DOMAIN" = true ]; then
    echo -e "${GREEN}✓ Dominio:${NC} $SERVER_NAME"
else
    echo -e "${GREEN}✓ Acceso por IP:${NC} $SERVER_IP"
fi
if [ "$INSTALL_SSL" = true ] && [ -f "/etc/letsencrypt/live/$HOST/privkey.pem" ]; then
    echo -e "${GREEN}✓ SSL:${NC} Instalado (HTTPS)"
else
    echo -e "${YELLOW}⚠ SSL:${NC} No instalado (solo HTTP)"
fi
echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
echo -e "${BLUE}🌐 URL de acceso:${NC}"
echo -e "   ${BOLD}$APP_URL${NC}"
echo ""
echo -e "${BLUE}📁 Rutas importantes:${NC}"
echo -e "   • Aplicación: ${CYAN}$PATH_CURRENT/$DIR_API${NC}"
echo -e "   • VirtualHost: ${CYAN}/etc/apache2/sites-available/$DIR_API.conf${NC}"
echo -e "   • Logs Apache: ${CYAN}/var/log/apache2/${DIR_API}_*.log${NC}"
echo -e "   • Logs Laravel: ${CYAN}$PATH_CURRENT/$DIR_API/storage/logs/laravel.log${NC}"
echo ""
echo -e "${BLUE}🔑 Credenciales guardadas en:${NC}"
echo -e "   ${BOLD}$PATH_CURRENT/setup/private.txt${NC}"
echo ""
echo -e "${YELLOW}⚠️  IMPORTANTE:${NC}"
echo -e "   ${YELLOW}• Guarda las credenciales en un lugar seguro${NC}"
echo -e "   ${YELLOW}• Los logs de Apache están en /var/log/apache2/${NC}"
if [ "$INSTALL_SSL" = true ] && [ -f "/etc/letsencrypt/live/$HOST/privkey.pem" ]; then
    echo -e "   ${YELLOW}• Recuerda renovar el SSL manualmente cada 90 días${NC}"
    echo -e "   ${YELLOW}• Comando de renovación: certbot renew${NC}"
fi
echo ""

# Verificar que Apache esté corriendo
if systemctl is-active --quiet apache2; then
    echo -e "${GREEN}✓ Apache está ejecutándose correctamente${NC}"
else
    echo -e "${RED}✗ Apache no está ejecutándose${NC}"
    print_info "Intentando iniciar Apache..."
    systemctl start apache2
fi

# Verificar que MySQL esté corriendo
if systemctl is-active --quiet mariadb; then
    echo -e "${GREEN}✓ MariaDB está ejecutándose correctamente${NC}"
else
    echo -e "${RED}✗ MariaDB no está ejecutándose${NC}"
    print_info "Intentando iniciar MariaDB..."
    systemctl start mariadb
fi

echo ""
echo -e "${GREEN}✓ Instalación finalizada correctamente${NC}"
echo -e "${CYAN}Puedes acceder a tu aplicación en: ${BOLD}$APP_URL${NC}"
echo ""
