#!/bin/bash
# ---------------------------------------------------------------------------
# HomeCareUS cutover — master-list provisioning + referral sources + menu fixes
#
# Everything below has already been run and verified against a full clone of
# the production database in /home/signgwph/homecareus.io/homecare-saas-next.
#
# The database changes are ADDITIVE and backward-compatible: the old code
# ignores the new referral_sources table, and the seeded master lists simply
# show up as data. That means rollback is only the directory rename at the end.
# ---------------------------------------------------------------------------
set -e

PHP=/opt/cpanel/ea-php83/root/usr/bin/php
ROOT=/home/signgwph/homecareus.io
TS=$(date +%Y%m%d-%H%M)

cd "$ROOT/homecare-saas-next"

echo "==> 1/6  Pointing at the live database"
# Set explicitly rather than trusting whatever the sandbox was last tested
# against — this directory gets repointed at a scratch database during testing.
sed -i 's/^DB_DATABASE=.*/DB_DATABASE=signgwph_homecareuss/' .env
$PHP artisan config:clear >/dev/null
$PHP artisan tinker --execute="echo '    database: '.DB::connection()->getDatabaseName().PHP_EOL;"

echo "==> 2/6  Running migrations (referral_sources + care_plan_task_completions)"
$PHP artisan migrate --force

echo "==> 3/6  Seeding master lists for every existing agency"
$PHP artisan agency:seed-master-lists --all

echo "==> 4/6  Final storage sync (picks up anything uploaded in the last few minutes)"
rsync -a "$ROOT/homecare-saas/storage/app/" "$ROOT/homecare-saas-next/storage/app/"

echo "==> 5/6  Switching directories"
cd "$ROOT"
mv homecare-saas "homecare-saas-prev-$TS"
mv homecare-saas-next homecare-saas
echo "    previous version kept at: homecare-saas-prev-$TS"

echo "==> 6/6  Clearing caches"
cd "$ROOT/homecare-saas"
$PHP artisan config:clear >/dev/null
$PHP artisan route:clear >/dev/null
$PHP artisan view:clear  >/dev/null

echo
echo "==> Verifying"
curl -s -o /dev/null -w '    login page  -> %{http_code}\n' -H 'Host: homecareus.io' https://127.0.0.1/login --insecure
$PHP artisan tinker --execute="
echo '    lookup rows -> '.App\Models\Lookup::withoutGlobalScopes()->count().PHP_EOL;
echo '    agencies    -> '.App\Models\Agency::withoutGlobalScopes()->count().PHP_EOL;
"
echo
echo "DONE.  To roll back:"
echo "  cd $ROOT && mv homecare-saas homecare-saas-next && mv homecare-saas-prev-$TS homecare-saas"
