#!/usr/bin/env bash
# ============================================================================
# Mr Bismarck Super Platform — cPanel Deployment Script
#
# Run this via SSH from inside the project root after uploading & extracting
# the project (see DEPLOYMENT_GUIDE.md for upload instructions).
#
# Usage:
#   cd ~/mrbismarck
#   chmod +x deploy.sh
#   ./deploy.sh
# ============================================================================

set -e

echo "============================================================"
echo " Mr Bismarck Super Platform — Deployment"
echo "============================================================"

# ── 1. Check PHP version ───────────────────────────────────────
PHP_VERSION=$(php -r 'echo PHP_VERSION;')
echo "→ PHP version detected: ${PHP_VERSION}"

if [[ "$(php -r 'echo PHP_MAJOR_VERSION;')" -lt 8 ]]; then
  echo "⚠️  Warning: This app requires PHP 8.3+. Set the correct PHP"
  echo "   version in cPanel → MultiPHP Manager, then re-run this script."
fi

# ── 2. Check / locate Composer ─────────────────────────────────
if command -v composer &> /dev/null; then
  COMPOSER_BIN="composer"
elif [ -f "$HOME/composer.phar" ]; then
  COMPOSER_BIN="php $HOME/composer.phar"
elif command -v php8.3 &> /dev/null && [ -f /usr/local/bin/composer ]; then
  COMPOSER_BIN="php8.3 /usr/local/bin/composer"
else
  echo "❌ Composer not found."
  echo "   Try: curl -sS https://getcomposer.org/installer | php"
  echo "   Then re-run this script, or see DEPLOYMENT_GUIDE.md Section 8."
  exit 1
fi
echo "→ Using composer: ${COMPOSER_BIN}"

# ── 3. Install dependencies ────────────────────────────────────
echo ""
echo "→ Installing PHP dependencies (this may take a few minutes)..."
${COMPOSER_BIN} install --no-dev --optimize-autoloader --no-interaction

# ── 4. .env setup ───────────────────────────────────────────────
if [ ! -f .env ]; then
  echo ""
  echo "→ Creating .env from .env.example..."
  cp .env.example .env
  echo "⚠️  IMPORTANT: Edit .env now and set your DB_* credentials,"
  echo "   APP_URL, and other settings before continuing."
  echo ""
  read -p "Press Enter once you've configured .env to continue, or Ctrl+C to stop and edit now... "
else
  echo "→ .env already exists, skipping."
fi

# ── 5. App key ──────────────────────────────────────────────────
if ! grep -q "^APP_KEY=base64:" .env 2>/dev/null; then
  echo ""
  echo "→ Generating application key..."
  php artisan key:generate --force
else
  echo "→ APP_KEY already set, skipping."
fi

# ── 6. Database setup ────────────────────────────────────────────
echo ""
echo "============================================================"
echo " Database Setup"
echo "============================================================"
echo "Choose an option:"
echo "  1) Fresh migrate + seed full demo data (RECOMMENDED for testing)"
echo "  2) Migrate only (no demo data)"
echo "  3) Skip (I already imported database/sql/mrbismarck_schema.sql manually)"
read -p "Enter choice [1/2/3]: " DB_CHOICE

case "$DB_CHOICE" in
  1)
    echo "→ Running migrations + seeders..."
    php artisan migrate --force
    php artisan db:seed --force
    ;;
  2)
    echo "→ Running migrations only..."
    php artisan migrate --force
    ;;
  3)
    echo "→ Skipping migrations (assuming SQL file was already imported)."
    ;;
  *)
    echo "Invalid choice, skipping database setup. Run manually later with:"
    echo "  php artisan migrate --seed"
    ;;
esac

# ── 7. Storage link & permissions ────────────────────────────────
echo ""
echo "→ Linking storage and setting permissions..."
php artisan storage:link 2>/dev/null || echo "  (storage link already exists, skipping)"
chmod -R 775 storage bootstrap/cache 2>/dev/null || true

# ── 8. Cache config & routes for production ─────────────────────
echo ""
echo "→ Caching configuration and routes..."
php artisan config:cache
php artisan route:cache

# ── 9. Done ───────────────────────────────────────────────────────
echo ""
echo "============================================================"
echo " ✅ Deployment complete!"
echo "============================================================"
echo ""
echo "Next steps:"
echo "  1. Make sure your domain's Document Root points to:"
echo "     $(pwd)/public"
echo "     (see DEPLOYMENT_GUIDE.md Section 2 if you can't change it)"
echo ""
echo "  2. Set up cron jobs for queue processing (DEPLOYMENT_GUIDE.md Section 6):"
echo "     * * * * * cd $(pwd) && php artisan schedule:run >> /dev/null 2>&1"
echo "     * * * * * cd $(pwd) && timeout 50 php artisan queue:work --stop-when-empty >> /dev/null 2>&1"
echo ""
echo "  3. Test login (if you seeded demo data):"
echo "     POST /api/v1/auth/login"
echo "     { \"phone\": \"254700000001\", \"password\": \"Password@123\" }"
echo ""
echo "  4. If you see a 500 error, set APP_DEBUG=true in .env temporarily"
echo "     and check storage/logs/laravel.log"
echo "============================================================"
