#!/usr/bin/env bash
# Build a self-contained release zip for cPanel (no Composer/npm on the server).
#
# Before uploading:
#   - In cPanel, set the site document root to the Laravel "public" folder (not the project root),
#     or use a subdomain whose document root points at .../your-app/public.
#   - PHP 8.3+ (matches composer.json).
#   - chmod 775 (or 755) storage and bootstrap/cache; ensure the web user can write there.
#   - If you use user uploads / storage:link: from cPanel Terminal (once): php artisan storage:link
#
# Run from your Mac/Linux dev machine (with PHP, Composer, Node):
#   ./scripts/build-cpanel-zip.sh
#   composer cpanel-zip

set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"

if [[ ! -f .env ]]; then
  echo "ERROR: .env not found in project root. Copy .env.example to .env and configure it first."
  exit 1
fi

echo ">> composer install (production, no dev dependencies)..."
composer install --no-dev --optimize-autoloader --no-interaction

echo ">> npm ci + vite build..."
npm ci
npm run build

echo ">> clear Laravel caches (configure .env on the server after upload)..."
php artisan optimize:clear

TIMESTAMP="$(date +%Y%m%d-%H%M%S)"
ZIP_NAME="budgets-laravel-cpanel-${TIMESTAMP}.zip"
OUT="$(cd "${ROOT}/.." && pwd)/${ZIP_NAME}"

echo ">> writing ${OUT} ..."

# Create zip from project root; exclude dev artifacts and paths not needed in production.
zip -rq "$OUT" . \
  -x ".git/*" \
  -x ".git/**/*" \
  -x "node_modules/*" \
  -x "node_modules/**/*" \
  -x ".cursor/*" \
  -x ".cursor/**/*" \
  -x ".idea/*" \
  -x ".idea/**/*" \
  -x ".vscode/*" \
  -x ".vscode/**/*" \
  -x "tests/*" \
  -x "tests/**/*" \
  -x "public/hot" \
  -x "storage/logs/*.log" \
  -x ".DS_Store" \
  -x "*/*/.DS_Store" \
  -x "*/*/*/.DS_Store" \
  -x "*/*/*/*/.DS_Store" \
  -x "database/database.sqlite" \
  -x ".env" \
  -x ".env.backup" \
  -x ".env.production" \
  -x "*.zip"

echo ""
echo ">> restoring Composer dev dependencies for local development..."
composer install --no-interaction

echo ""
echo "Done. Upload and unzip on the server, then point the domain document root to the \"public\" folder."
echo "Archive: ${OUT}"
echo "Reminder: .env is not in the zip. On the server, copy .env.example to .env and set production values (DB, APP_KEY, etc.)."
