#!/bin/bash
# =========================================================
# Laravel Setup Script
# =========================================================

# Load environment variables
if [ -f .env ]; then
    export $(grep -v '^#' .env | sed 's/#.*//' | grep -E '^[A-Z0-9_]+=')
else
    echo "❌ .env file not found. Exiting."
    exit 1
fi

# Get project name from .env or default to 'app'
PROJECT_NAME=${PROJECT_NAME:-app}
APP_PATH="./laravel/$PROJECT_NAME"

# Create Laravel project if it doesn't exist
if [ ! -d "$APP_PATH" ]; then
    echo "📦 Creating Laravel project in $APP_PATH..."
    docker exec -it php bash -c "composer create-project --prefer-dist laravel/laravel $APP_PATH"
else
    echo "✅ Laravel project already exists at $APP_PATH"
fi

# Copy .env.example if .env is missing
if [ ! -f "$APP_PATH/.env" ]; then
    echo "📄 Copying .env.example to .env..."
    docker exec -it php bash -c "cp $APP_PATH/.env.example $APP_PATH/.env"
else
    echo "✅ .env already exists in $APP_PATH"
fi

# Generate APP_KEY if not set
APP_KEY_VALUE=$(docker exec -it php bash -c "cd $APP_PATH && php artisan key:generate --show")
if ! grep -q "^APP_KEY=" "$APP_PATH/.env"; then
    echo "🔑 Setting APP_KEY in .env..."
    sed -i "s|^APP_KEY=.*|APP_KEY=$APP_KEY_VALUE|" "$APP_PATH/.env"
else
    echo "✅ APP_KEY already set"
fi

# Install Composer dependencies
echo "📦 Installing Composer dependencies..."
docker exec -it php bash -c "cd $APP_PATH && composer install"

# Set correct permissions
echo "🔧 Fixing permissions..."
docker exec -it php bash -c "chown -R www-data:www-data $APP_PATH"

echo "🎉 Laravel setup complete for project '$PROJECT_NAME'"
