#!/bin/bash

echo "🚀 Ensuring .env file exists before building Docker..."

# Check if .env already exists to prevent overwriting
if [ -f ".env" ]; then
    echo "⚠️ .env file already exists. Skipping copy to prevent overwriting."
else
    # Check if .env.local exists in .docker/config
    if [ -f ".docker/config/.env.local" ]; then
        echo "✅ Copying .env.local to project root..."
        cp .docker/config/.env.local .env
    else
        echo "❌ ERROR: .env.local not found in .docker/config! Please create it."
        exit 1
    fi
fi

echo "🚀 Overwrite .htaccess file to prevent https redirects..."

# Check if .env.local exists in .docker/config
if [ -f ".docker/config/.htaccess.local" ]; then
    echo "✅ Copying .htaccess.local to project root..."
    cp .docker/config/.htaccess.local .htaccess
else
    echo "❌ ERROR: .htaccess.local not found in .docker/config! Please create it."
    exit 1
fi

# Proceed with Docker Compose
echo "🐳 Build Docker containers..."
docker compose build --no-cache

echo "🐳 starting Docker containers..."
docker compose up -d

# Load environment variables from .env file
if [ -f ".env" ]; then
    export $(grep -v '^#' .env | xargs)
fi

# Ensure environment variables are set
if [ -z "$DB_USERNAME" ] || [ -z "$DB_PASSWORD" ]; then
    echo "❌ ERROR: DB_USERNAME or DB_PASSWORD is not set. Exiting..."
    exit 1
fi

echo "⏳ Waiting for the MariaDB container to be ready..."

# Run the check until the database is accessible
while true; do
    if docker exec mariadb mariadb -h mariadb -u"$DB_USERNAME" -p"$DB_PASSWORD" --ssl-verify-server-cert=OFF -e "SELECT 1;" >/dev/null 2>&1; then
        echo "✅ Database is ready!"
        break
    else
        echo "🔄 Still waiting for the database..."
        sleep 2
    fi
done

# Wait for the PHP container to be fully running
echo "⏳ Waiting for PHP container to be ready..."
until docker ps | grep -q "mtc-pharmacy-web"; do
    sleep 2
done
echo "✅ PHP container is running!"

# Execute setup script inside the PHP container
echo "🔧 Running setup script inside PHP container..."
docker exec -it mtc-pharmacy-web sh .docker/config/setup.sh

echo "✅ Setup script completed!"
