#!/usr/bin/env bash
#
# Engineers Hub — one-command deploy / upgrade.
# Deploys the system, runs migrations, seeds roles + reference data + admin,
# optionally seeds demo data, imports integration settings (Maps, Firebase/FCM,
# Paystack, PayPal, Africa's Talking, M-PESA) from .env, builds the JSON mirror,
# and caches config/routes/views.
#
# Usage:
#   ./deploy.sh                 # standard deploy/upgrade
#   ./deploy.sh --demo          # also seed illustrative demo data
#   ./deploy.sh --fresh         # DROP all tables and rebuild (DANGEROUS — dev only)
#   PHP=/usr/local/bin/php ./deploy.sh    # pin a PHP binary (common on cPanel)
#
set -euo pipefail

PHP="${PHP:-php}"
COMPOSER="${COMPOSER:-composer}"
DEMO=0
FRESH=0
for arg in "$@"; do
  case "$arg" in
    --demo)  DEMO=1 ;;
    --fresh) FRESH=1 ;;
    *) echo "Unknown option: $arg"; exit 1 ;;
  esac
done

log()  { printf '\n\033[1;34m▶ %s\033[0m\n' "$1"; }
ok()   { printf '\033[1;32m  ✓ %s\033[0m\n' "$1"; }
warn() { printf '\033[1;33m  ! %s\033[0m\n' "$1"; }

cd "$(dirname "$0")"
log "Engineers Hub deploy — $($PHP -r 'echo PHP_VERSION;')"

# 1. Dependencies (skip if vendor/ already shipped, e.g. the cpanel-full package)
if [ ! -d vendor ]; then
  log "Installing PHP dependencies"
  $COMPOSER install --no-dev --optimize-autoloader --no-interaction
  ok "Dependencies installed"
else
  ok "vendor/ present — skipping composer install"
fi

# 2. Environment
if [ ! -f .env ]; then
  log "Creating .env from .env.example"
  cp .env.example .env
  warn ".env created — edit DB_*, APP_URL and integration keys, then re-run ./deploy.sh"
  exit 1
fi
grep -q '^APP_KEY=base64' .env || { log "Generating APP_KEY"; $PHP artisan key:generate --force; }

# 3. Database schema
if [ "$FRESH" = "1" ]; then
  warn "FRESH deploy: dropping and recreating ALL tables"
  $PHP artisan migrate:fresh --force
else
  log "Running migrations"
  $PHP artisan migrate --force
fi
ok "Schema up to date"

# 4. Core seed data (idempotent): roles, disciplines/regions, plans, CMS blocks, first super admin
log "Seeding roles, reference data, plans, CMS and admin"
$PHP artisan db:seed --force
ok "Core data seeded"

# 5. Optional demo data
if [ "$DEMO" = "1" ]; then
  log "Seeding demo data (professionals, transactions, orders, etc.)"
  $PHP artisan db:seed --class=DemoSeeder --force
  ok "Demo data seeded (accounts use password Demo12345!)"
fi

# 6. Integration settings from .env (encrypted at rest): Maps, FCM, Paystack, PayPal, Africa's Talking, M-PESA
log "Importing integration settings from .env"
$PHP artisan settings:seed
ok "Settings imported (finish any missing keys in Admin > Settings)"

# 7. Storage, JSON mirror, caches
log "Linking storage and building the JSON fallback mirror"
$PHP artisan storage:link 2>/dev/null || true
$PHP artisan hybrid:mirror
ok "JSON mirror built"

log "Caching config, routes and views"
$PHP artisan config:cache
$PHP artisan route:cache
$PHP artisan view:cache
ok "Caches primed"

chmod -R ug+rwX storage bootstrap/cache 2>/dev/null || true

log "Deploy complete"
cat <<EOF

  Next steps:
    • Add the scheduler cron (once per minute):
        * * * * * cd "$(pwd)" && $PHP artisan schedule:run >> /dev/null 2>&1
    • Log in at:  ${APP_URL:-your-domain}/admin/login
    • Set the PayPal & Paystack webhook URLs in their dashboards:
        Paystack : {APP_URL}/api/v1/payments/paystack/webhook
        PayPal   : {APP_URL}/api/v1/payments/paypal/webhook
    • Confirm integrations under Admin > Settings (Payments, SMS & Notifications, Maps).
    • Remove ADMIN_PASSWORD from .env after the first successful login.

EOF
