#!/bin/bash
# ==============================================================================
# TAXIDO — cPanel App Setup (shared hosting)
# ==============================================================================
# Runs ONLY the Laravel app-level steps. No root, no apt, no nginx/mysql-server,
# no supervisor, no ufw. cPanel already provides PHP, MySQL and the web server.
#
# Before running:
#   1. In cPanel > MySQL Databases: create a database + user, add user to DB
#      with ALL PRIVILEGES. Note the names (they are usually prefixed, e.g.
#      cpaneluser_taxido).
#   2. In cPanel > MultiPHP Manager (or Select PHP Version): set this domain to
#      PHP 8.2 or 8.3, and enable extensions: mbstring, xml, curl, zip, bcmath,
#      intl, gd, pdo_mysql, fileinfo, openssl.
#   3. Point the domain/subdomain Document Root to  <this folder>/public
#      (Domains > manage > Document Root). Do NOT expose the project root.
#
# Run from the project root:   bash cpanel-install.sh
# ==============================================================================

set -e
GREEN='\033[0;32m'; RED='\033[0;31m'; YEL='\033[1;33m'; NC='\033[0m'
info(){ echo -e "${GREEN}➜${NC} $1"; }
warn(){ echo -e "${YEL}!${NC} $1"; }
err(){ echo -e "${RED}✖${NC} $1"; }

# --- Sanity: must be project root ---
if [ ! -f "artisan" ]; then
  err "artisan not found. Run this from the Laravel project root."; exit 1
fi

# --- Pick PHP binary (cPanel often ships ea-php83 / ea-php82) ---
PHP_BIN=""
for c in php ea-php83 ea-php82 /usr/local/bin/php /opt/cpanel/ea-php83/root/usr/bin/php /opt/cpanel/ea-php82/root/usr/bin/php; do
  if command -v "$c" >/dev/null 2>&1; then PHP_BIN="$c"; break; fi
done
[ -z "$PHP_BIN" ] && { err "No PHP binary found on PATH. Set PHP version in cPanel first."; exit 1; }
info "Using PHP: $($PHP_BIN -v | head -n1)"

# --- Pick Composer (do NOT install one) ---
COMPOSER_CMD=""
if command -v composer >/dev/null 2>&1; then
  COMPOSER_CMD="composer"
elif [ -f "composer.phar" ]; then
  COMPOSER_CMD="$PHP_BIN composer.phar"
fi

# --- Collect DB details (created beforehand in cPanel) ---
read -p "DB name (as shown in cPanel): " DB_NAME
read -p "DB user: " DB_USER
read -s -p "DB password: " DB_PASS; echo ""
read -p "DB host [127.0.0.1]: " DB_HOST; DB_HOST=${DB_HOST:-127.0.0.1}
read -p "Site URL (e.g. https://app.example.com): " APP_URL

# --- .env ---
if [ ! -f .env ]; then
  cp .env.example .env
  info "Created .env from .env.example"
else
  warn ".env already exists — updating values in place."
fi

set_env(){ # key value
  if grep -q "^$1=" .env; then
    sed -i "s|^$1=.*|$1=$2|" .env
  else
    echo "$1=$2" >> .env
  fi
}
set_env APP_ENV production
set_env APP_DEBUG false
set_env APP_URL "$APP_URL"
set_env DB_CONNECTION mysql
set_env DB_HOST "$DB_HOST"
set_env DB_PORT 3306
set_env DB_DATABASE "$DB_NAME"
set_env DB_USERNAME "$DB_USER"
set_env DB_PASSWORD "\"$DB_PASS\""
# Shared hosting has no Redis/Supervisor daemon — keep everything on the DB
set_env QUEUE_CONNECTION database
set_env CACHE_STORE database
set_env SESSION_DRIVER database
set_env BROADCAST_CONNECTION log
info "Wrote database + environment settings to .env"

# --- Dependencies (only if missing; uses cPanel's composer) ---
if [ ! -f "vendor/autoload.php" ]; then
  if [ -n "$COMPOSER_CMD" ]; then
    info "Installing PHP dependencies (composer install)..."
    $COMPOSER_CMD install --no-dev --optimize-autoloader --no-interaction
  else
    warn "vendor/ is missing and no composer found."
    warn "Run 'composer install --no-dev --optimize-autoloader' via cPanel Terminal,"
    warn "or upload the vendor/ folder over FTP, then re-run this script."
    exit 1
  fi
else
  info "vendor/ present — skipping composer install."
fi

# --- Frontend build (Vite) ---
if [ -f "package.json" ]; then
  if command -v npm >/dev/null 2>&1; then
    if [ ! -d "public/build" ]; then
      info "Installing Node packages (npm install)..."
      npm install --no-audit --no-fund
      info "Building frontend assets (npm run build)..."
      npm run build
    else
      info "public/build present — skipping npm build."
    fi
  else
    warn "npm not found on PATH. Enable Node.js in cPanel (Setup Node.js App) or add it to PATH,"
    warn "then run 'npm install && npm run build' in the project root."
  fi
fi

# --- App key ---
if grep -q "^APP_KEY=$" .env || ! grep -q "^APP_KEY=base64" .env; then
  $PHP_BIN artisan key:generate --force
  info "Generated APP_KEY"
fi

# --- Migrate ---
read -p "Run database migrations now? (y/n): " DOMIG
if [[ "$DOMIG" =~ ^[Yy]$ ]]; then
  $PHP_BIN artisan migrate --force
fi

# --- Storage symlink + permissions ---
$PHP_BIN artisan storage:link || warn "storage:link skipped (may already exist)"
chmod -R 775 storage bootstrap/cache 2>/dev/null || true

# --- Cache config for production ---
$PHP_BIN artisan config:cache
$PHP_BIN artisan route:cache || true
$PHP_BIN artisan view:cache || true

echo ""
info "App-level setup complete."
echo -e "${YEL}Finish these in the cPanel UI:${NC}"
echo "  1. Document Root of your domain -> $(pwd)/public"
echo "  2. cPanel > Cron Jobs, add (every minute) the scheduler:"
echo "     * * * * * $PHP_BIN $(pwd)/artisan schedule:run >> /dev/null 2>&1"
echo "  3. For the queue (no Supervisor on cPanel), add a cron every minute:"
echo "     * * * * * $PHP_BIN $(pwd)/artisan queue:work --stop-when-empty >> /dev/null 2>&1"
echo "  4. Reverb/websockets need a long-running process; shared cPanel usually can't run it."
echo "     Use a VPS or a hosted Pusher-compatible service if you need realtime."
