#!/bin/bash
set -e

echo "🚀 Starting BuyerKiosk container..."

# Wait for MySQL to be ready
wait_for_mysql() {
    echo "⏳ Waiting for MySQL to be ready..."
    max_attempts=30
    attempt=0
    while [ $attempt -lt $max_attempts ]; do
        if mysqladmin ping -h"$DB_HOST" -u"$DB_USER" -p"$DB_PASS" --silent 2>/dev/null; then
            echo "✅ MySQL is ready!"
            return 0
        fi
        attempt=$((attempt + 1))
        echo "   Attempt $attempt/$max_attempts..."
        sleep 2
    done
    echo "❌ MySQL not ready after $max_attempts attempts"
    return 1
}

# Run on first start or when explicitly requested
run_setup() {
    cd /var/www/html/userfrosting

    # Install Composer dependencies if vendor doesn't exist or is outdated
    if [ ! -d "vendor" ] || [ ! -f "vendor/autoload.php" ]; then
        echo "📦 Installing Composer dependencies..."
        local composer_flags="--no-interaction --prefer-dist"
        if [ "${COMPOSER_IGNORE_PLATFORM:-0}" = "1" ]; then
            composer_flags="$composer_flags --ignore-platform-reqs"
        fi
        composer install $composer_flags
    fi

    # Build CSS if needed
    if [ ! -f "/var/www/html/public_html/css/admin/admin-theme.min.css" ]; then
        echo "🎨 Building CSS..."
        php conductor build-css --minify || true
    fi

    # Run migrations (only if first time or explicitly requested)
    if [ "${RUN_MIGRATIONS:-0}" = "1" ]; then
        echo "🗄️ Running database migrations..."
        php conductor run || true
    fi
}

# Create required directories
mkdir -p /var/www/html/logs
chmod 777 /var/www/html/logs

# Create .env symlink if not exists and source .env exists
if [ -f "/var/www/html/userfrosting/.env.docker" ] && [ ! -f "/var/www/html/userfrosting/.env" ]; then
    echo "📝 Creating .env from .env.docker..."
    cp /var/www/html/userfrosting/.env.docker /var/www/html/userfrosting/.env
fi

# Wait for dependencies
if [ -n "$DB_HOST" ]; then
    wait_for_mysql
fi

# Run setup tasks
run_setup

# Fix permissions
chown -R www-data:www-data /var/www/html/logs 2>/dev/null || true

echo "✅ BuyerKiosk container ready!"
echo "🌐 Application: http://localhost:8080"
echo "📊 Adminer: http://localhost:8081"
echo "📧 Mailhog: http://localhost:8025"

# Execute the main command (apache2-foreground)
exec "$@"
