#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
fail=0

pass(){ printf '[PASS] %s\n' "$1"; }
bad(){ printf '[FAIL] %s\n' "$1" >&2; fail=1; }

while IFS= read -r -d '' file; do
  if ! php -l "$file" >/dev/null; then bad "PHP syntax: $file"; exit 1; fi
done < <(find "$ROOT" -type f -name '*.php' -print0)
pass 'all PHP files parse'

if grep -RInE --exclude='ashby-booking-secrets.example.php' --exclude='static-audit.sh' '(sk_live_[A-Za-z0-9]{20,}|sk_test_[A-Za-z0-9]{20,}|whsec_[A-Za-z0-9]{20,})' "$ROOT" >/dev/null; then
  bad 'no live/test Stripe secrets embedded'
else
  pass 'no Stripe secrets embedded'
fi

if grep -nF '\$_POST[\x27discount_value\x27]' "$ROOT/process-checkout.php" >/dev/null 2>&1 || grep -nF '\$_POST["discount_value"]' "$ROOT/process-checkout.php" >/dev/null 2>&1; then
  bad 'checkout does not trust browser discount_value'
else
  pass 'checkout ignores browser discount_value'
fi

if grep -RInE 'DELETE[[:space:]]+FROM[[:space:]]+bookings' "$ROOT" --include='*.php' >/dev/null; then
  bad 'booking records are never hard-deleted by PHP endpoints'
else
  pass 'booking records are not hard-deleted'
fi

if grep -q "paymentStatus !== 'paid'" "$ROOT/includes/booking-core.php" && grep -q "amountTotal !== \$expectedPence" "$ROOT/includes/booking-core.php"; then
  pass 'Stripe paid-state and amount are verified'
else
  bad 'Stripe paid-state and amount verification present'
fi

if grep -q 'FOR UPDATE' "$ROOT/admin/set-pending.php" && grep -q 'booking_lock_all_lanes' "$ROOT/admin/add-booking.php" && grep -q 'booking_lock_all_lanes' "$ROOT/admin/update-booking.php"; then
  pass 'public and staff allocation paths use row-locking flow'
else
  bad 'row-locking allocation flow present'
fi

if (( fail != 0 )); then exit 1; fi
printf '\nStatic audit passed.\n'
