#!/usr/bin/env bash
set -euo pipefail

ROOT="$(cd "$(dirname "$0")" && pwd)"
cd "$ROOT"

echo "=== Vantage Finance House installer ==="
echo

if [[ ! -f artisan ]]; then
  echo "Error: run this from the project root (artisan not found)."
  exit 1
fi

read -r -p "Live APP_URL (e.g. https://example.com): " APP_URL
APP_URL="${APP_URL%/}"
read -r -p "DB host [127.0.0.1]: " DB_HOST
DB_HOST="${DB_HOST:-127.0.0.1}"
read -r -p "DB name [vantage_finance]: " DB_DATABASE
DB_DATABASE="${DB_DATABASE:-vantage_finance}"
read -r -p "DB username: " DB_USERNAME
read -r -s -p "DB password: " DB_PASSWORD
echo
read -r -p "Import database/sql/vantage_finance_house.sql now? [y/N]: " DO_IMPORT

cp -n .env.example .env || true

php -r '
$path = ".env";
$env = file_get_contents($path);
$map = [
  "APP_URL" => getenv("APP_URL") ?: "",
  "ASSET_URL" => getenv("APP_URL") ?: "",
  "DB_HOST" => getenv("DB_HOST") ?: "127.0.0.1",
  "DB_DATABASE" => getenv("DB_DATABASE") ?: "vantage_finance",
  "DB_USERNAME" => getenv("DB_USERNAME") ?: "",
  "DB_PASSWORD" => getenv("DB_PASSWORD") ?: "",
  "APP_ENV" => "production",
  "APP_DEBUG" => "false",
  "SESSION_PATH" => "/",
];
foreach ($map as $k => $v) {
  if ($v === "" && in_array($k, ["DB_USERNAME","DB_PASSWORD"], true)) continue;
  if (preg_match("/^{$k}=.*/m", $env)) {
    $env = preg_replace("/^{$k}=.*/m", $k."=".$v, $env, 1);
  } else {
    $env .= "\n{$k}={$v}\n";
  }
}
file_put_contents($path, $env);
echo "Wrote .env\n";
' 

# Export for php -r above via env
export APP_URL DB_HOST DB_DATABASE DB_USERNAME DB_PASSWORD
# Re-run replace properly with env available
python3 - <<'PY'
import os, re
path = ".env"
env = open(path).read()
vals = {
  "APP_NAME": '"Vantage Finance House"',
  "APP_URL": os.environ.get("APP_URL",""),
  "ASSET_URL": os.environ.get("APP_URL",""),
  "DB_HOST": os.environ.get("DB_HOST","127.0.0.1"),
  "DB_DATABASE": os.environ.get("DB_DATABASE","vantage_finance"),
  "DB_USERNAME": os.environ.get("DB_USERNAME",""),
  "DB_PASSWORD": os.environ.get("DB_PASSWORD",""),
  "APP_ENV": "production",
  "APP_DEBUG": "false",
  "SESSION_PATH": "/",
}
for k,v in vals.items():
  if re.search(rf"^{k}=.*$", env, re.M):
    env = re.sub(rf"^{k}=.*$", f"{k}={v}", env, count=1, flags=re.M)
  else:
    env += f"\n{k}={v}\n"
open(path,"w").write(env)
print("Updated .env with live settings")
PY

if [[ "${DO_IMPORT,,}" == "y" || "${DO_IMPORT,,}" == "yes" ]]; then
  echo "Importing SQL..."
  mysql -h "$DB_HOST" -u "$DB_USERNAME" -p"$DB_PASSWORD" "$DB_DATABASE" < database/sql/vantage_finance_house.sql
  echo "Database imported."
fi

php artisan key:generate --force
mkdir -p storage/framework/{cache,sessions,views} storage/logs bootstrap/cache
chmod -R ug+rwx storage bootstrap/cache || true
php artisan config:clear
php artisan cache:clear || true
php artisan config:cache || true
php artisan route:cache || true
php artisan view:cache || true

echo
echo "Installation steps complete."
echo "Point your domain document root to: $ROOT/public"
echo "Then open: $APP_URL"
