#!/bin/bash
# On the live server:
#   bash /var/www/miniappeasypaisa/scripts/run-recursive-cron.sh
#   bash /var/www/miniappeasypaisa/scripts/run-recursive-cron.sh charge
#
# close  expires subscriptions whose package date has passed and stops those pending rows.
#        It does not call Easypaisa.
# charge does that close, then runs today's insurance, vet and agri recursive crons.
#        Those crons collect payment from subscriptions that are still active and due today.
set -euo pipefail

APP=/var/www/miniappeasypaisa
MODE="${1:-close}"
PHP_BIN="${PHP_BIN:-php}"

cd "$APP"

if ! "$PHP_BIN" -m 2>/dev/null | grep -qi sqlsrv; then
  echo "php cli cannot see sqlsrv: $PHP_BIN"
  echo "Use the PHP binary that serves the site, then run:"
  echo "  PHP_BIN=/usr/bin/php8.2 bash $APP/scripts/run-recursive-cron.sh"
  exit 1
fi

echo "Recursive jobs already scheduled for root:"
crontab -l 2>/dev/null | grep -E 'cron-recursive|recursive' || echo "(none in root crontab)"
echo

"$PHP_BIN" "$APP/scripts/close-expired-recursive.php"

if [[ "$MODE" != "charge" ]]; then
  echo
  echo "Close finished. No customer was charged."
  echo "Today's real charge, only when you want it:"
  echo "  bash $APP/scripts/run-recursive-cron.sh charge"
  exit 0
fi

echo
echo "Charging today's still-active due subscriptions."
echo "Each cron also closes leftover expired rows before it collects payment."
BASE="${CRON_BASE:-https://miniappeasypaisa.webddocsystems.com/public/api/v1}"
failed=0
for path in cron-recursive-payment vet-cron-recursive-payment agri-cron-recursive-payment; do
  echo "---- $(date '+%F %T') $BASE/$path ----"
  bodyfile=$(mktemp)
  code=$(curl -sS --max-time 3600 -o "$bodyfile" -w "%{http_code}" "$BASE/$path" || true)
  cat "$bodyfile"
  rm -f "$bodyfile"
  echo
  echo "http_code=${code:-000}"
  if [[ "${code:-000}" != "200" ]]; then
    echo "FAILED $path"
    failed=1
  fi
  echo
done
exit "$failed"
