#!/bin/bash

# Vision Videoke Apache Subdirectory Installer
# Installs Vision Videoke in a subdirectory without affecting existing Apache sites

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m'

# ASCII Art Banner
show_banner() {
    echo -e "${PURPLE}"
    cat << "EOF"
╦  ╦┬┌─┐┬┌─┐┌┐┌  ╦  ╦┬┌┬┐┌─┐┌─┐┬┌─┌─┐
╚╗╔╝│└─┐││ ││││  ╚╗╔╝│ ││ ├┤ │ │├┴┐├┤ 
 ╚╝ ┴└─┘┴└─┘┘└┘   ╚╝ ┴─┴┘ └─┘└─┘┴ ┴└─┘
                                        
    Apache Subdirectory Installer
       Professional Music Video Creator
EOF
    echo -e "${NC}"
}

log() {
    echo -e "${GREEN}[$(date +'%H:%M:%S')] ✓ $1${NC}"
}

error() {
    echo -e "${RED}[ERROR] ✗ $1${NC}"
    exit 1
}

warn() {
    echo -e "${YELLOW}[WARNING] ⚠ $1${NC}"
}

info() {
    echo -e "${BLUE}[INFO] ℹ $1${NC}"
}

step() {
    echo -e "${CYAN}[STEP] ➤ $1${NC}"
}

# Check if running on supported system
check_system() {
    if [[ $EUID -eq 0 ]]; then
        error "Please run this installer as a regular user, not as root"
    fi
    
    # Check for supported OS
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        if [[ "$ID" != "amzn" && "$ID" != "centos" && "$ID" != "rhel" && "$ID" != "ubuntu" && "$ID" != "debian" ]]; then
            warn "This installer is optimized for Amazon Linux, CentOS, RHEL, Ubuntu, or Debian"
        fi
    fi
    
    log "System check passed"
}

# Welcome message and configuration
welcome_and_configure() {
    clear
    show_banner
    
    echo -e "${CYAN}Welcome to the Vision Videoke Apache Installer!${NC}"
    echo ""
    echo "This installer will set up Vision Videoke in a subdirectory of your existing Apache website."
    echo ""
    echo -e "${YELLOW}What will be installed:${NC}"
    echo "• Node.js 18 (LTS) and npm (if not already installed)"
    echo "• PM2 process manager"
    echo "• Vision Videoke application in subdirectory"
    echo "• Apache configuration for subdirectory routing"
    echo "• Security configurations and monitoring"
    echo "• Automated backup system"
    echo ""
    echo -e "${YELLOW}Requirements:${NC}"
    echo "• Existing Apache web server"
    echo "• Domain name already configured"
    echo "• API keys for OpenAI, Udio, and ElevenLabs"
    echo "• Sudo privileges for Apache configuration"
    echo ""
    
    read -p "Do you want to continue with the installation? (y/N): " -n 1 -r
    echo ""
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "Installation cancelled."
        exit 0
    fi
    
    echo ""
    step "Collecting configuration information"
    
    # Domain name (should already be configured)
    while true; do
        read -p "Enter your domain name (e.g., mysite.com): " DOMAIN_NAME
        if [[ $DOMAIN_NAME =~ ^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$ ]]; then
            break
        else
            warn "Please enter a valid domain name"
        fi
    done
    
    # Subdirectory name
    while true; do
        read -p "Enter subdirectory name [music]: " SUBDIRECTORY
        SUBDIRECTORY=${SUBDIRECTORY:-music}
        if [[ $SUBDIRECTORY =~ ^[a-zA-Z0-9_-]+$ ]]; then
            break
        else
            warn "Subdirectory name can only contain letters, numbers, hyphens, and underscores"
        fi
    done
    
    # Check if subdirectory already exists
    if [ -d "/var/www/html/$SUBDIRECTORY" ]; then
        warn "Directory /var/www/html/$SUBDIRECTORY already exists"
        read -p "Do you want to continue and overwrite? (y/N): " -n 1 -r
        echo ""
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            error "Installation cancelled to avoid overwriting existing directory"
        fi
    fi
    
    # API Keys
    echo ""
    info "API Keys (required for full functionality):"
    echo "You can update these later in the configuration file."
    echo ""
    
    read -p "OpenAI API Key: " -s OPENAI_KEY
    echo ""
    read -p "Udio API Key: " -s UDIO_KEY
    echo ""
    read -p "ElevenLabs API Key: " -s ELEVENLABS_KEY
    echo ""
    
    # Optional: Stripe keys
    echo ""
    read -p "Stripe Publishable Key (optional): " STRIPE_PUB_KEY
    read -p "Stripe Secret Key (optional): " -s STRIPE_SECRET_KEY
    echo ""
    
    # Set global variables
    APP_DIR="/var/www/html/$SUBDIRECTORY"
    BACKEND_PORT=3001
    
    log "Configuration collected successfully"
}

# Check Apache installation and status
check_apache() {
    step "Checking Apache installation"
    
    # Detect Apache service name
    if systemctl list-units --type=service | grep -q "httpd.service"; then
        APACHE_SERVICE="httpd"
        APACHE_CONF_DIR="/etc/httpd/conf.d"
        APACHE_USER="apache"
    elif systemctl list-units --type=service | grep -q "apache2.service"; then
        APACHE_SERVICE="apache2"
        APACHE_CONF_DIR="/etc/apache2/sites-available"
        APACHE_USER="www-data"
    else
        error "Apache is not installed or not running. Please install and configure Apache first."
    fi
    
    log "Detected Apache service: $APACHE_SERVICE"
    
    # Check if Apache is running
    if ! systemctl is-active --quiet $APACHE_SERVICE; then
        warn "Apache is not running. Attempting to start..."
        sudo systemctl start $APACHE_SERVICE || error "Failed to start Apache"
    fi
    
    # Check if domain is accessible
    if curl -f -s "http://$DOMAIN_NAME" > /dev/null; then
        log "Domain $DOMAIN_NAME is accessible"
    else
        warn "Domain $DOMAIN_NAME may not be properly configured"
    fi
}

# Install Node.js and PM2 if not already installed
install_nodejs() {
    step "Checking Node.js installation"
    
    if command -v node &> /dev/null; then
        NODE_VERSION=$(node --version)
        log "Node.js is already installed: $NODE_VERSION"
        
        # Check if version is 16 or higher
        NODE_MAJOR=$(echo $NODE_VERSION | cut -d'.' -f1 | sed 's/v//')
        if [ "$NODE_MAJOR" -lt 16 ]; then
            warn "Node.js version is too old. Installing Node.js 18..."
            install_node_18
        fi
    else
        info "Installing Node.js 18..."
        install_node_18
    fi
    
    # Install PM2 if not already installed
    if ! command -v pm2 &> /dev/null; then
        info "Installing PM2..."
        sudo npm install -g pm2 > /dev/null 2>&1
    fi
    
    log "Node.js and PM2 are ready"
}

install_node_18() {
    # Detect OS and install Node.js accordingly
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        case $ID in
            "amzn"|"centos"|"rhel")
                curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash - > /dev/null 2>&1
                sudo yum install -y nodejs > /dev/null 2>&1
                ;;
            "ubuntu"|"debian")
                curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash - > /dev/null 2>&1
                sudo apt-get install -y nodejs > /dev/null 2>&1
                ;;
            *)
                error "Unsupported operating system for automatic Node.js installation"
                ;;
        esac
    fi
}

# Configure Apache for subdirectory
configure_apache() {
    step "Configuring Apache for subdirectory deployment"
    
    # Create application directory
    sudo mkdir -p $APP_DIR
    sudo chown $APACHE_USER:$APACHE_USER $APP_DIR
    
    # Enable required Apache modules
    info "Enabling required Apache modules..."
    
    if [ "$APACHE_SERVICE" = "httpd" ]; then
        # RHEL/CentOS/Amazon Linux
        sudo sed -i 's/^#LoadModule rewrite_module/LoadModule rewrite_module/' /etc/httpd/conf/httpd.conf 2>/dev/null || true
        sudo sed -i 's/^#LoadModule headers_module/LoadModule headers_module/' /etc/httpd/conf/httpd.conf 2>/dev/null || true
        sudo sed -i 's/^#LoadModule expires_module/LoadModule expires_module/' /etc/httpd/conf/httpd.conf 2>/dev/null || true
        sudo sed -i 's/^#LoadModule deflate_module/LoadModule deflate_module/' /etc/httpd/conf/httpd.conf 2>/dev/null || true
        sudo sed -i 's/^#LoadModule proxy_module/LoadModule proxy_module/' /etc/httpd/conf/httpd.conf 2>/dev/null || true
        sudo sed -i 's/^#LoadModule proxy_http_module/LoadModule proxy_http_module/' /etc/httpd/conf/httpd.conf 2>/dev/null || true
    else
        # Debian/Ubuntu
        sudo a2enmod rewrite headers expires deflate proxy proxy_http 2>/dev/null || true
    fi
    
    # Create Apache configuration
    VHOST_CONF="$APACHE_CONF_DIR/visionvideoke-$SUBDIRECTORY.conf"
    
    sudo tee $VHOST_CONF > /dev/null <<EOF
# Vision Videoke Apache Configuration
# Subdirectory: /$SUBDIRECTORY
# Generated on $(date)

<Directory "$APP_DIR">
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
    
    RewriteEngine On
    
    # Handle React Router (SPA) routing
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !^/$SUBDIRECTORY/api/
    RewriteCond %{REQUEST_URI} !^/$SUBDIRECTORY/health\$
    RewriteRule ^(.*)$ /$SUBDIRECTORY/index.html [L,QSA]
    
    # Security headers
    Header always set X-Content-Type-Options nosniff
    Header always set X-Frame-Options DENY
    Header always set X-XSS-Protection "1; mode=block"
    Header always set Referrer-Policy "strict-origin-when-cross-origin"
    
    # CORS headers
    Header always set Access-Control-Allow-Origin "*"
    Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
    Header always set Access-Control-Allow-Headers "Content-Type, Authorization, X-Requested-With"
    
    # Handle preflight OPTIONS requests
    RewriteCond %{REQUEST_METHOD} OPTIONS
    RewriteRule ^(.*)$ \$1 [R=200,L]
</Directory>

# API proxy to Node.js backend
<Location "/$SUBDIRECTORY/api">
    ProxyPreserveHost On
    ProxyPass http://127.0.0.1:$BACKEND_PORT/api
    ProxyPassReverse http://127.0.0.1:$BACKEND_PORT/api
</Location>

# Health check endpoint
<Location "/$SUBDIRECTORY/health">
    ProxyPass http://127.0.0.1:$BACKEND_PORT/health
    ProxyPassReverse http://127.0.0.1:$BACKEND_PORT/health
</Location>

# File upload with increased limits
<Location "/$SUBDIRECTORY/api/upload">
    LimitRequestBody 104857600
    ProxyTimeout 300
    ProxyPass http://127.0.0.1:$BACKEND_PORT/api/upload
    ProxyPassReverse http://127.0.0.1:$BACKEND_PORT/api/upload
</Location>

# Static file caching
<LocationMatch "/$SUBDIRECTORY/.*\.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)\$">
    ExpiresActive On
    ExpiresDefault "access plus 1 year"
    Header append Cache-Control "public, immutable"
</LocationMatch>

# Gzip compression
<Location "/$SUBDIRECTORY">
    SetOutputFilter DEFLATE
    SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)\$ no-gzip dont-vary
</Location>

# Block sensitive files
<LocationMatch "/$SUBDIRECTORY/(\.env|package\.json|ecosystem\.config\.js|\.git)">
    Require all denied
</LocationMatch>
EOF
    
    # Enable site (for Debian/Ubuntu)
    if [ "$APACHE_SERVICE" = "apache2" ]; then
        sudo a2ensite visionvideoke-$SUBDIRECTORY 2>/dev/null || true
    fi
    
    # Test and reload Apache
    if sudo $APACHE_SERVICE -t; then
        sudo systemctl reload $APACHE_SERVICE
        log "Apache configuration updated successfully"
    else
        error "Apache configuration test failed"
    fi
}

# Create application structure
create_app_structure() {
    step "Creating application structure"
    
    # Create necessary directories
    sudo mkdir -p $APP_DIR/{uploads,temp,logs}
    sudo mkdir -p /var/log/visionvideoke
    sudo mkdir -p /var/backups/visionvideoke
    
    # Set proper ownership
    sudo chown -R $APACHE_USER:$APACHE_USER $APP_DIR
    sudo chown -R ec2-user:ec2-user /var/log/visionvideoke /var/backups/visionvideoke
    
    # Create environment file
    cat > $APP_DIR/.env <<EOF
# Vision Videoke Environment Configuration
NODE_ENV=production
PORT=$BACKEND_PORT

# Subdirectory Configuration
SUBDIRECTORY_PATH=/$SUBDIRECTORY
API_BASE_PATH=/$SUBDIRECTORY/api
PUBLIC_PATH=/$SUBDIRECTORY

# Domain Configuration
DOMAIN_NAME=$DOMAIN_NAME
APP_URL=https://$DOMAIN_NAME/$SUBDIRECTORY
API_URL=https://$DOMAIN_NAME/$SUBDIRECTORY/api

# API Keys
REACT_APP_OPENAI_API_KEY=$OPENAI_KEY
OPENAI_API_KEY=$OPENAI_KEY
REACT_APP_UDIO_API_KEY=$UDIO_KEY
UDIO_API_KEY=$UDIO_KEY
REACT_APP_ELEVENLABS_API_KEY=$ELEVENLABS_KEY
ELEVENLABS_API_KEY=$ELEVENLABS_KEY

# Payment Processing
REACT_APP_STRIPE_PUBLISHABLE_KEY=$STRIPE_PUB_KEY
STRIPE_SECRET_KEY=$STRIPE_SECRET_KEY

# File Storage
UPLOAD_DIR=$APP_DIR/uploads
TEMP_DIR=$APP_DIR/temp

# Security
JWT_SECRET=$(openssl rand -hex 32)
ENCRYPTION_KEY=$(openssl rand -hex 32)

# CORS Configuration
CORS_ORIGIN=https://$DOMAIN_NAME
CORS_CREDENTIALS=true

# Feature Flags
REACT_APP_ENABLE_VOICE_CLONING=true
REACT_APP_ENABLE_VIDEO_GENERATION=true
REACT_APP_ENABLE_PAYMENTS=true
EOF
    
    chmod 600 $APP_DIR/.env
    sudo chown $APACHE_USER:$APACHE_USER $APP_DIR/.env
    
    log "Application structure created"
}

# Create PM2 ecosystem configuration
create_pm2_config() {
    step "Creating PM2 configuration"
    
    cat > $APP_DIR/ecosystem.config.js <<EOF
module.exports = {
  apps: [{
    name: 'visionvideoke-$SUBDIRECTORY',
    script: 'server.js',
    cwd: '$APP_DIR',
    instances: 'max',
    exec_mode: 'cluster',
    env: {
      NODE_ENV: 'production',
      PORT: $BACKEND_PORT,
      SUBDIRECTORY_PATH: '/$SUBDIRECTORY'
    },
    error_file: '/var/log/visionvideoke/error.log',
    out_file: '/var/log/visionvideoke/out.log',
    log_file: '/var/log/visionvideoke/combined.log',
    time: true,
    max_memory_restart: '1G',
    restart_delay: 4000,
    max_restarts: 10,
    min_uptime: '10s'
  }]
};
EOF
    
    sudo chown $APACHE_USER:$APACHE_USER $APP_DIR/ecosystem.config.js
    
    log "PM2 configuration created"
}

# Create placeholder application
create_placeholder_app() {
    step "Creating placeholder application"
    
    # Create basic package.json
    cat > $APP_DIR/package.json <<EOF
{
  "name": "visionvideoke-$SUBDIRECTORY",
  "version": "1.0.0",
  "description": "Vision Videoke - Transform vision boards into music videos",
  "main": "server.js",
  "scripts": {
    "start": "node server.js",
    "dev": "node server.js"
  },
  "dependencies": {
    "express": "^4.18.0",
    "cors": "^2.8.5",
    "dotenv": "^16.0.0"
  }
}
EOF
    
    # Create basic server.js
    cat > $APP_DIR/server.js <<'EOF'
const express = require('express');
const cors = require('cors');
const path = require('path');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 3001;
const SUBDIRECTORY_PATH = process.env.SUBDIRECTORY_PATH || '/music';

// Middleware
app.use(cors({
  origin: process.env.CORS_ORIGIN || '*',
  credentials: process.env.CORS_CREDENTIALS === 'true'
}));
app.use(express.json({ limit: '100mb' }));
app.use(express.urlencoded({ extended: true, limit: '100mb' }));

// Health check endpoint
app.get('/health', (req, res) => {
  res.status(200).send('healthy');
});

// API routes placeholder
app.get('/api/status', (req, res) => {
  res.json({
    status: 'running',
    subdirectory: SUBDIRECTORY_PATH,
    timestamp: new Date().toISOString(),
    message: 'Vision Videoke API is ready for deployment'
  });
});

// Serve static files (when React app is built)
app.use(express.static(path.join(__dirname, 'dist')));

// Handle React Router (catch all)
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});

app.listen(PORT, '127.0.0.1', () => {
  console.log(`Vision Videoke server running on port ${PORT}`);
  console.log(`Subdirectory: ${SUBDIRECTORY_PATH}`);
  console.log(`Health check: http://127.0.0.1:${PORT}/health`);
});
EOF
    
    # Create basic index.html
    cat > $APP_DIR/index.html <<EOF
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vision Videoke - Ready for Deployment</title>
    <style>
        body { 
            font-family: Arial, sans-serif; 
            text-align: center; 
            padding: 50px; 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            margin: 0;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;
        }
        .container {
            max-width: 600px;
            padding: 40px;
            background: rgba(255,255,255,0.1);
            border-radius: 20px;
            backdrop-filter: blur(10px);
        }
        h1 { font-size: 3em; margin-bottom: 20px; }
        .status { 
            background: rgba(0,255,0,0.2); 
            padding: 10px 20px; 
            border-radius: 10px; 
            margin: 20px 0;
            border: 1px solid rgba(0,255,0,0.3);
        }
        .info {
            background: rgba(255,255,255,0.1);
            padding: 20px;
            border-radius: 10px;
            margin: 20px 0;
            text-align: left;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🎬 Vision Videoke</h1>
        <div class="status">✅ Apache Subdirectory Setup Complete!</div>
        <p>Your Vision Videoke platform is ready for deployment in the <strong>/$SUBDIRECTORY</strong> subdirectory.</p>
        
        <div class="info">
            <h3>Installation Details:</h3>
            <ul>
                <li><strong>Domain:</strong> $DOMAIN_NAME</li>
                <li><strong>Subdirectory:</strong> /$SUBDIRECTORY</li>
                <li><strong>Backend Port:</strong> $BACKEND_PORT</li>
                <li><strong>Document Root:</strong> $APP_DIR</li>
                <li><strong>API Endpoint:</strong> /$SUBDIRECTORY/api</li>
                <li><strong>Health Check:</strong> /$SUBDIRECTORY/health</li>
            </ul>
        </div>
        
        <p><strong>Next Steps:</strong></p>
        <ul style="text-align: left; display: inline-block;">
            <li>Upload your Vision Videoke application files</li>
            <li>Install dependencies: <code>npm install</code></li>
            <li>Build the application: <code>npm run build</code></li>
            <li>Start the backend: <code>pm2 start ecosystem.config.js</code></li>
        </ul>
        
        <p style="margin-top: 30px; font-size: 0.9em; opacity: 0.8;">
            Server: $DOMAIN_NAME | Path: /$SUBDIRECTORY | Status: Ready for Deployment
        </p>
    </div>
</body>
</html>
EOF
    
    # Set proper ownership
    sudo chown -R $APACHE_USER:$APACHE_USER $APP_DIR
    
    log "Placeholder application created"
}

# Install dependencies and start services
install_and_start() {
    step "Installing dependencies and starting services"
    
    # Install Node.js dependencies
    cd $APP_DIR
    sudo -u $APACHE_USER npm install > /dev/null 2>&1
    
    # Start the application with PM2
    sudo -u $APACHE_USER pm2 start ecosystem.config.js
    sudo -u $APACHE_USER pm2 save
    
    # Setup PM2 startup script
    sudo env PATH=$PATH:/usr/bin pm2 startup systemd -u $APACHE_USER --hp /home/$APACHE_USER > /dev/null 2>&1 || true
    
    log "Services started successfully"
}

# Create management scripts
create_management_scripts() {
    step "Creating management scripts"
    
    # Create status check script
    cat > /home/ec2-user/visionvideoke-status.sh <<EOF
#!/bin/bash
echo "=== Vision Videoke Status ($SUBDIRECTORY) ==="
echo ""
echo "Apache Status:"
sudo systemctl status $APACHE_SERVICE --no-pager -l | head -10
echo ""
echo "Application Status:"
pm2 list | grep visionvideoke-$SUBDIRECTORY
echo ""
echo "Backend Health Check:"
curl -s http://127.0.0.1:$BACKEND_PORT/health || echo "Backend not responding"
echo ""
echo "Frontend Access Test:"
curl -s -o /dev/null -w "%{http_code}" http://$DOMAIN_NAME/$SUBDIRECTORY || echo "Frontend not accessible"
echo ""
echo "Directory Status:"
ls -la $APP_DIR | head -10
EOF
    chmod +x /home/ec2-user/visionvideoke-status.sh
    
    # Create restart script
    cat > /home/ec2-user/visionvideoke-restart.sh <<EOF
#!/bin/bash
echo "Restarting Vision Videoke ($SUBDIRECTORY)..."
pm2 restart visionvideoke-$SUBDIRECTORY
sudo systemctl reload $APACHE_SERVICE
echo "Restart completed"
EOF
    chmod +x /home/ec2-user/visionvideoke-restart.sh
    
    # Create backup script
    cat > /home/ec2-user/visionvideoke-backup.sh <<EOF
#!/bin/bash
BACKUP_DIR="/var/backups/visionvideoke"
BACKUP_NAME="backup-$SUBDIRECTORY-\$(date +%Y%m%d-%H%M%S).tar.gz"

echo "Creating backup..."
tar -czf "\$BACKUP_DIR/\$BACKUP_NAME" -C "$APP_DIR" . --exclude=node_modules --exclude=temp --exclude=logs

# Keep only last 10 backups
cd \$BACKUP_DIR
ls -t backup-$SUBDIRECTORY-*.tar.gz | tail -n +11 | xargs rm -f 2>/dev/null || true

echo "Backup created: \$BACKUP_NAME"
EOF
    chmod +x /home/ec2-user/visionvideoke-backup.sh
    
    log "Management scripts created"
}

# Final testing and verification
test_installation() {
    step "Testing installation"
    
    # Wait for services to start
    sleep 5
    
    # Test backend health
    if curl -f -s http://127.0.0.1:$BACKEND_PORT/health > /dev/null; then
        log "Backend health check passed"
    else
        warn "Backend health check failed"
    fi
    
    # Test Apache configuration
    if sudo $APACHE_SERVICE -t > /dev/null 2>&1; then
        log "Apache configuration is valid"
    else
        warn "Apache configuration has issues"
    fi
    
    # Test frontend access
    if curl -f -s http://$DOMAIN_NAME/$SUBDIRECTORY > /dev/null; then
        log "Frontend is accessible"
    else
        warn "Frontend may not be accessible yet (DNS propagation or configuration issue)"
    fi
    
    log "Installation testing completed"
}

# Show success message and next steps
show_success() {
    clear
    show_banner
    
    echo -e "${GREEN}🎉 Installation Completed Successfully! 🎉${NC}"
    echo ""
    echo -e "${CYAN}Your Vision Videoke platform is now running in a subdirectory!${NC}"
    echo ""
    echo -e "${YELLOW}Access Information:${NC}"
    echo "• Application URL: http://$DOMAIN_NAME/$SUBDIRECTORY"
    echo "• API Endpoint: http://$DOMAIN_NAME/$SUBDIRECTORY/api"
    echo "• Health Check: http://$DOMAIN_NAME/$SUBDIRECTORY/health"
    echo "• Backend Port: $BACKEND_PORT (internal)"
    echo ""
    echo -e "${YELLOW}File Locations:${NC}"
    echo "• Application Directory: $APP_DIR"
    echo "• Environment File: $APP_DIR/.env"
    echo "• Apache Configuration: $VHOST_CONF"
    echo "• Logs: /var/log/visionvideoke/"
    echo "• Backups: /var/backups/visionvideoke/"
    echo ""
    echo -e "${YELLOW}Management Commands:${NC}"
    echo "• ./visionvideoke-status.sh     - Check system status"
    echo "• ./visionvideoke-restart.sh    - Restart application"
    echo "• ./visionvideoke-backup.sh     - Create backup"
    echo "• pm2 logs visionvideoke-$SUBDIRECTORY - View application logs"
    echo ""
    echo -e "${YELLOW}Next Steps:${NC}"
    echo "1. 📁 Upload your Vision Videoke application files to $APP_DIR"
    echo "2. 🔧 Run 'npm install && npm run build' in the application directory"
    echo "3. 🔑 Update API keys in $APP_DIR/.env"
    echo "4. 🔄 Restart the application: pm2 restart visionvideoke-$SUBDIRECTORY"
    echo "5. 🧪 Test your platform at http://$DOMAIN_NAME/$SUBDIRECTORY"
    echo ""
    echo -e "${GREEN}Your existing Apache site remains completely unaffected! 🎵🎬${NC}"
}

# Main installation flow
main() {
    check_system
    welcome_and_configure
    check_apache
    install_nodejs
    configure_apache
    create_app_structure
    create_pm2_config
    create_placeholder_app
    install_and_start
    create_management_scripts
    test_installation
    show_success
}

# Run main installation
main "$@"

