#!/usr/bin/env bash
##############################################################
# GMLM Platform — Docker Quick Start (NO PHP/Node needed)
# Just needs Docker Desktop installed.
# Usage: chmod +x docker-start.sh && ./docker-start.sh
##############################################################

echo ""
echo "╔═══════════════════════════════════════════╗"
echo "║   GMLM Platform — Docker Quick Start      ║"
echo "╚═══════════════════════════════════════════╝"
echo ""

# Check Docker is running
if ! docker info &>/dev/null; then
    echo "✗ Docker is not running. Start Docker Desktop first."
    exit 1
fi

# Generate secrets
APP_KEY="base64:$(openssl rand -base64 32)"
DB_PASS=$(openssl rand -hex 16)
REDIS_PASS=$(openssl rand -hex 12)

# Write .env
cat > .env << ENV
APP_NAME="GMLM Platform"
APP_ENV=production
APP_KEY=${APP_KEY}
APP_DEBUG=false
APP_URL=http://localhost
APP_INSTALLED=false

GMLM_LICENSE_KEY=
GMLM_VERSION=1.0.0

DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=gmlm_db
DB_USERNAME=gmlm_user
DB_PASSWORD=${DB_PASS}
DB_ROOT_PASSWORD=${DB_PASS}root

REDIS_HOST=redis
REDIS_PASSWORD=${REDIS_PASS}
REDIS_PORT=6379

CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_CONNECTION=redis

MAIL_MAILER=log
LOG_CHANNEL=daily
LOG_LEVEL=warning
ENV

echo "▶ Starting containers (this may take 2-3 minutes on first run)..."
docker compose up -d

echo ""
echo "▶ Waiting for MySQL to be ready..."
until docker compose exec -T mysql mysqladmin ping -h localhost --silent 2>/dev/null; do
    printf "."
    sleep 2
done
echo ""
echo "✓ MySQL ready"

echo ""
echo "╔═══════════════════════════════════════════╗"
echo "║   ✓ GMLM Platform is running!             ║"
echo "╚═══════════════════════════════════════════╝"
echo ""
echo "  Open in browser: http://localhost"
echo "  The installer will launch automatically."
echo ""
echo "  Admin panel (after install): http://localhost/admin/dashboard"
echo ""

# Open browser if on macOS
if [[ "$OSTYPE" == "darwin"* ]]; then
    sleep 3
    open "http://localhost"
fi
