#!/usr/bin/env bash
##############################################################
# GMLM Platform — Automated Setup Script (Linux / macOS)
# Usage: chmod +x setup.sh && ./setup.sh
##############################################################

set -e

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

echo ""
echo -e "${BLUE}╔═══════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║   GMLM Platform — Setup                   ║${NC}"
echo -e "${BLUE}║   Global MLM Software v1.0.0              ║${NC}"
echo -e "${BLUE}╚═══════════════════════════════════════════╝${NC}"
echo ""

step() { echo -e "${BLUE}▶ $1${NC}"; }
ok()   { echo -e "${GREEN}✓ $1${NC}"; }
warn() { echo -e "${YELLOW}⚠ $1${NC}"; }
fail() { echo -e "${RED}✗ $1${NC}"; exit 1; }

# ── Check PHP ─────────────────────────────────────────────────
step "Checking PHP..."
if ! command -v php &>/dev/null; then
    fail "PHP not found. Install PHP 8.3+ first:
  Ubuntu:  sudo apt install php8.3 php8.3-{cli,pdo,mysql,bcmath,mbstring,openssl,gd,zip,sodium,redis}
  macOS:   brew install php
  Windows: Use setup.bat or download from https://windows.php.net"
fi
PHP_VER=$(php -r 'echo PHP_MAJOR_VERSION.".".PHP_MINOR_VERSION;')
if php -r 'exit(version_compare(PHP_VERSION, "8.3.0", "<") ? 1 : 0);'; then
    ok "PHP $PHP_VER"
else
    fail "PHP 8.3+ required. Found: $PHP_VER"
fi

# ── Check Composer ────────────────────────────────────────────
step "Checking Composer..."
if ! command -v composer &>/dev/null; then
    step "Composer not found — installing automatically..."
    php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
    php composer-setup.php --quiet
    rm composer-setup.php
    sudo mv composer.phar /usr/local/bin/composer 2>/dev/null || mv composer.phar composer
    COMPOSER="php composer"
    ok "Composer installed"
else
    COMPOSER="composer"
    ok "Composer found"
fi

# ── Check Node ────────────────────────────────────────────────
step "Checking Node.js..."
if ! command -v node &>/dev/null; then
    fail "Node.js not found. Install Node 20+ from https://nodejs.org"
fi
NODE_VER=$(node -v)
ok "Node $NODE_VER"

# ── Install PHP dependencies ──────────────────────────────────
step "Installing PHP dependencies (composer install)..."
$COMPOSER install --no-dev --optimize-autoloader --no-interaction --ansi
ok "PHP packages installed"

# ── Install & build frontend ──────────────────────────────────
step "Installing frontend packages..."
npm install --silent
ok "npm packages installed"

step "Building frontend assets..."
npm run build
ok "Frontend built (public/build/)"

# ── Set up .env ───────────────────────────────────────────────
step "Configuring environment..."
if [ ! -f .env ]; then
    cp .env.example .env
    php artisan key:generate --ansi
    php artisan jwt:secret --force --ansi
    ok ".env created with secure keys"
else
    warn ".env already exists — keeping existing configuration"
fi

# ── Storage permissions ───────────────────────────────────────
step "Setting permissions..."
chmod -R 755 storage bootstrap/cache
ok "Permissions set"

# ── Done ──────────────────────────────────────────────────────
echo ""
echo -e "${GREEN}╔═══════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║   ✓ GMLM Setup Complete!                  ║${NC}"
echo -e "${GREEN}╚═══════════════════════════════════════════╝${NC}"
echo ""
echo "  Next step: Set up a MySQL 8 database, then visit:"
echo ""
echo -e "  ${BLUE}http://localhost${NC}  (via your web server)"
echo -e "  ${BLUE}http://127.0.0.1:8000${NC}  (via: php artisan serve)"
echo ""
echo "  The installer will open automatically and guide you through:"
echo "  1. Database configuration"
echo "  2. Admin account creation"
echo "  3. Company setup"
echo ""

# Offer to start built-in PHP server for quick local testing
read -p "  Start PHP development server now? (y/n) " -n 1 -r
echo ""
if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo -e "  ${YELLOW}Starting PHP server at http://127.0.0.1:8000${NC}"
    echo -e "  ${YELLOW}Press Ctrl+C to stop${NC}"
    echo ""
    php artisan serve
fi
