#!/bin/bash

# Environment Management Script for PS25
# Usage: ./env-manager.sh [development|staging|production|local]

if [ $# -eq 0 ]; then
    echo "Usage: $0 [development|staging|production|production.local|local]"
    echo "Current environment: $(grep APP_ENV .env 2>/dev/null | cut -d'=' -f2 || echo 'No .env file found')"
    echo ""
    echo "Available environments:"
    ls -1 .env.* 2>/dev/null | sed 's/.env./- /' || echo "No environment files found"
    exit 1
fi

ENVIRONMENT=$1
ENV_FILE=".env.$ENVIRONMENT"

# Check if environment file exists
if [ ! -f "$ENV_FILE" ]; then
    echo "Environment file $ENV_FILE does not exist!"
    echo "Available environments:"
    ls -1 .env.* 2>/dev/null | sed 's/.env./- /' || echo "No environment files found"
    exit 1
fi

# Backup current .env if it exists
if [ -f ".env" ]; then
    cp .env .env.backup
    echo "✅ Backed up current .env to .env.backup"
fi

# Copy environment file to .env
cp "$ENV_FILE" ".env"
echo "✅ Switched to $ENVIRONMENT environment"

# Clear Laravel caches
if command -v php &> /dev/null && [ -f "artisan" ]; then
    echo "🔄 Clearing Laravel caches..."
    php artisan config:clear
    php artisan cache:clear
    php artisan route:clear
    php artisan view:clear
    echo "✅ Caches cleared"
fi

echo ""
echo "Environment Details:"
echo "==================="
echo "APP_ENV: $(grep APP_ENV .env | cut -d'=' -f2)"
echo "APP_DEBUG: $(grep APP_DEBUG .env | cut -d'=' -f2)"
echo "APP_URL: $(grep APP_URL .env | cut -d'=' -f2)"
echo "DB_CONNECTION: $(grep DB_CONNECTION .env | cut -d'=' -f2)"
echo "DB_DATABASE: $(grep DB_DATABASE .env | cut -d'=' -f2)"
echo ""
echo "🚀 Environment switch complete!"