#!/usr/bin/env bash
# InLynq — first-time install on cPanel (Namecheap). Run from cPanel Terminal:
#   cd ~/inlynq && bash install.sh
# Safe to re-run: migrations and plan seeding are idempotent.
set -euo pipefail
cd "$(dirname "$0")"
APP="$(pwd)"
PHP="${PHP_BIN:-$(command -v php)}"
ok() { printf '  \033[32m✓\033[0m %s\n' "$1"; }
fail() { printf '  \033[31m✗ %s\033[0m\n' "$1"; exit 1; }

echo "1. Checking PHP ($PHP)"
"$PHP" -r 'exit(version_compare(PHP_VERSION, "8.3.0", ">=") ? 0 : 1);' \
  || fail "PHP $("$PHP" -r 'echo PHP_VERSION;') found. Choose PHP 8.3 or 8.4 in cPanel → Select PHP Version, then reopen Terminal."
ok "PHP $("$PHP" -r 'echo PHP_VERSION;')"
missing=""
for ext in pdo_mysql mbstring openssl fileinfo gd tokenizer ctype curl dom xml; do
  "$PHP" -r "exit(extension_loaded('$ext') ? 0 : 1);" || missing="$missing $ext"
done
[ -z "$missing" ] || fail "Missing PHP extensions:$missing. Tick them in cPanel → Select PHP Version → Extensions."
ok "Required extensions loaded"

echo "2. Checking .env"
if [ ! -f .env ]; then
  cp .env.cpanel .env
  fail "Created .env from the template. Edit it (File Manager or: nano .env), replace every CHANGE_ME, then run this script again."
fi
for key in APP_URL DB_DATABASE DB_USERNAME DB_PASSWORD SEED_ADMIN_EMAIL SEED_ADMIN_PASSWORD; do
  grep -qE "^${key}=.+" .env || fail "Set ${key} in .env (or use the browser installer instead: open your site and follow the steps)."
done
ok ".env filled in"

echo "3. Preparing folders"
mkdir -p storage/logs storage/app/private storage/app/public storage/framework/{cache/data,sessions,views} bootstrap/cache public/uploads
chmod -R u+rwX,go+rX storage bootstrap/cache public/uploads
ok "storage, bootstrap/cache and public/uploads are writable"

echo "4. Database"
"$PHP" artisan config:clear >/dev/null
"$PHP" artisan migrate --force
"$PHP" artisan db:seed --class=PlanSeeder --force >/dev/null && ok "Plans seeded"
"$PHP" artisan db:seed --class=AdminSeeder --force && ok "Admin account ready"

echo "5. Locking the browser installer"
sed -i.bak 's/^INSTALLER_ENABLED=.*/INSTALLER_ENABLED=false/; s/^SESSION_DRIVER=file/SESSION_DRIVER=database/; s/^CACHE_STORE=file/CACHE_STORE=database/' .env && rm -f .env.bak
printf '{"installed_at":"%s","via":"install.sh"}' "$(date -u +%FT%TZ)" > storage/app/installed.json
rm -f storage/app/setup-key.txt
ok "Installer disabled"

echo "6. Caching for speed"
"$PHP" artisan optimize >/dev/null && ok "Config, routes and views cached"

echo
echo "Done. Now add this cron job (cPanel → Cron Jobs → Once Per Minute):"
echo
echo "  cd $APP && $PHP artisan schedule:run >> /dev/null 2>&1"
echo
if [ -L "$HOME/public_html" ] && [ "$(readlink "$HOME/public_html")" = "$APP/public" ]; then
  ok "public_html already points to $APP/public"
else
  echo "Your domain isn't pointing at the app yet. See step 4 of DEPLOY_NAMECHEAP.md."
fi
