#!/usr/bin/env bash
set -euo pipefail
APP="/var/www/html/favo"
PKG="$(cd "$(dirname "$0")/.." && pwd)"
TS="$(date +%Y%m%d_%H%M%S)"
BACKUP="$APP/storage/backups/phase2a_$TS"
mkdir -p "$BACKUP"

echo "[1/8] Backup target files"
for f in app/Controllers/MerchantWorkspaceController.php app/Controllers/CRMController.php app/Services/MerchantWorkspaceService.php app/Services/CRMService.php resources/views/merchant/workspace.php resources/views/crm/index.php resources/views/crm/customer.php database/migrations/010_merchant_workspace_crm.sql public/index.php; do
  if [ -f "$APP/$f" ]; then mkdir -p "$BACKUP/$(dirname "$f")"; cp -a "$APP/$f" "$BACKUP/$f"; fi
done

echo "[2/8] Copy Phase 2A files"
cp -a "$PKG/app/Controllers/MerchantWorkspaceController.php" "$APP/app/Controllers/"
cp -a "$PKG/app/Controllers/CRMController.php" "$APP/app/Controllers/"
cp -a "$PKG/app/Services/MerchantWorkspaceService.php" "$APP/app/Services/"
cp -a "$PKG/app/Services/CRMService.php" "$APP/app/Services/"
cp -a "$PKG/resources/views/merchant/workspace.php" "$APP/resources/views/merchant/"
cp -a "$PKG/resources/views/crm/index.php" "$APP/resources/views/crm/"
cp -a "$PKG/resources/views/crm/customer.php" "$APP/resources/views/crm/"
cp -a "$PKG/database/migrations/010_merchant_workspace_crm.sql" "$APP/database/migrations/"

echo "[3/8] Add routes idempotently"
python3 - "$APP/public/index.php" <<'PY'
from pathlib import Path
p=Path(__import__('sys').argv[1]); s=p.read_text()
routes=[
" 'merchant_workspace'=>[Favo\\Controllers\\MerchantWorkspaceController::class,'index'],",
" 'merchant_workspace_save'=>[Favo\\Controllers\\MerchantWorkspaceController::class,'save'],",
" 'merchant_branch_save'=>[Favo\\Controllers\\MerchantWorkspaceController::class,'branchSave'],",
" 'merchant_staff_create'=>[Favo\\Controllers\\MerchantWorkspaceController::class,'staffCreate'],",
" 'crm'=>[Favo\\Controllers\\CRMController::class,'index'],",
" 'crm_customer'=>[Favo\\Controllers\\CRMController::class,'customer'],",
]
anchor=" 'merchant_programs'=>[Favo\\Controllers\\MerchantController::class,'programs'],"
for r in routes:
    if r not in s:
        s=s.replace(anchor, anchor+"\n"+r,1)
p.write_text(s)
PY

echo "[4/8] Register migration"
php -r '
$e=getenv("FAVO_DB_NAME"); if(!$e) { $env=file_exists("/var/www/html/favo/.env")?parse_ini_file("/var/www/html/favo/.env"):[]; $e=$env["DB_NAME"]??"favo_test"; }
require "/var/www/html/favo/bootstrap/app.php";
$db=database_connection();
$path="/var/www/html/favo/database/migrations/010_merchant_workspace_crm.sql";
$sql=file_get_contents($path);
foreach(preg_split("/;\\s*(?:\\r?\\n|$)/",$sql) as $stmt){$stmt=trim($stmt); if($stmt===""||str_starts_with($stmt,"--")) continue; try{$db->exec($stmt);}catch(Throwable $x){if(str_contains($stmt,"schema_migrations")) throw $x; echo "WARN: ".$x->getMessage().PHP_EOL;}}
'

echo "[5/8] Permissions"
chown -R www-data:www-data "$APP/app/Controllers" "$APP/app/Services" "$APP/resources/views" "$APP/database/migrations"
chmod 644 "$APP"/app/Controllers/{MerchantWorkspaceController.php,CRMController.php}
chmod 644 "$APP"/app/Services/{MerchantWorkspaceService.php,CRMService.php}
chmod 644 "$APP"/resources/views/merchant/workspace.php "$APP"/resources/views/crm/index.php "$APP"/resources/views/crm/customer.php
chmod 644 "$APP/database/migrations/010_merchant_workspace_crm.sql"

echo "[6/8] PHP syntax"
find "$APP/app" "$APP/public" -type f -name '*.php' -print0 | xargs -0 -n1 php -l >/dev/null
echo "PHP syntax: PASS"

echo "[7/8] Health"
curl -fsS "http://127.0.0.1:8080/favo/public/?page=api/health" | head -c 1000 || true
echo

echo "[8/8] Done"
echo "Backup: $BACKUP"
echo "Workspace: http://thrdc.webredirect.org:8080/favo/public/?page=merchant_workspace"
echo "CRM:       http://thrdc.webredirect.org:8080/favo/public/?page=crm"
