#!/bin/bash
set -uo pipefail
PASS=0
FAIL=0

check() {
  if [ "$1" = "$2" ]; then PASS=$((PASS+1)); echo "PASS: $3 (got: $1)";
  else FAIL=$((FAIL+1)); echo "FAIL: $3 -- expected [$2] got [$1]"; fi
}
contains() {
  if echo "$1" | grep -q "$2"; then PASS=$((PASS+1)); echo "PASS: $3";
  else FAIL=$((FAIL+1)); echo "FAIL: $3 -- did not find '$2'"; fi
}

echo "=== Setup: fresh schema + seed a host/event ==="
service mariadb start 2>&1 | tail -1
sleep 2
mysql -u root -e "DROP DATABASE IF EXISTS fete; CREATE DATABASE fete;"
mysql -u root fete < /home/claude/fete/database/schema.sql
mysql -u root -e "CREATE USER IF NOT EXISTS 'fete_user'@'127.0.0.1' IDENTIFIED BY 'testpass123'; GRANT ALL PRIVILEGES ON fete.* TO 'fete_user'@'127.0.0.1'; FLUSH PRIVILEGES;"
mysql -u root fete -e "INSERT INTO users (id, role, full_name, email, password_hash) VALUES (1, 'host', 'Test Host', 'th@example.com', 'x');"
mysql -u root fete -e "INSERT INTO events (id, host_id, name, event_type, event_date, slug, status) VALUES (1, 1, 'Test Wedding', 'wedding', '2026-12-01', 'test-wedding', 'live');"
mysql -u root fete -e "INSERT INTO sub_funds (id, event_id, name) VALUES (1, 1, 'Honeymoon Fund');"

cd /home/claude/fete/public
php -S 127.0.0.1:8000 > /tmp/php-server-p3.log 2>&1 &
SERVER_PID=$!
sleep 2
BASE="http://127.0.0.1:8000"

echo "=== 1. Donation form loads with currency + sub-fund options ==="
FORM=$(curl -s -c /tmp/cj_donor.txt "$BASE/donate.php?slug=test-wedding")
STATUS=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/donate.php?slug=test-wedding")
check "$STATUS" "200" "donation form loads"
contains "$FORM" "Honeymoon Fund" "sub-fund appears as a giving option"
contains "$FORM" "guessed GHS" "currency auto-detect fallback shown (GHS, since geo lookup can't reach the network here)"
CSRF=$(echo "$FORM" | grep -o 'name="csrf_token" value="[^"]*"' | head -1 | sed 's/.*value="//;s/"//')

echo "=== 2. Missing event returns 404 ==="
STATUS404=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/donate.php?slug=does-not-exist")
check "$STATUS404" "404" "donation page for unknown event returns 404"

echo "=== 3. Submitting a donation creates a pending row, then fails gracefully (no route to Flutterwave here) ==="
DONATE_RESP=$(curl -s -b /tmp/cj_donor.txt \
  --data-urlencode "csrf_token=$CSRF" \
  --data-urlencode "slug=test-wedding" \
  --data-urlencode "amount=250" \
  --data-urlencode "currency=GHS" \
  --data-urlencode "sub_fund_id=1" \
  --data-urlencode "donor_email=guest@example.com" \
  --data-urlencode "donor_name=Efua" \
  "$BASE/donate.php")
contains "$DONATE_RESP" "couldn&#039;t reach the payment processor" "friendly error shown when Flutterwave is unreachable (apostrophe HTML-entity-encoded by htmlspecialchars, as expected)"

DONATION_ROW=$(mysql -u root fete -N -e "SELECT status, amount, currency, sub_fund_id FROM donations WHERE flutterwave_tx_ref LIKE 'FETE-1-%' ORDER BY id DESC LIMIT 1;")
echo "donation row: $DONATION_ROW"
contains "$DONATION_ROW" "failed" "donation correctly ends in 'failed' status (not stuck pending) when initiation fails"
contains "$DONATION_ROW" "250.00" "correct amount recorded despite the failure"

echo "=== 4. Validation: zero amount rejected ==="
BAD_RESP=$(curl -s -b /tmp/cj_donor.txt \
  --data-urlencode "csrf_token=$CSRF" \
  --data-urlencode "slug=test-wedding" \
  --data-urlencode "amount=0" \
  --data-urlencode "currency=GHS" \
  --data-urlencode "donor_email=guest@example.com" \
  --data-urlencode "donor_name=Efua" \
  "$BASE/donate.php")
contains "$BAD_RESP" "greater than zero" "zero-amount donation rejected with a clear message"

echo "=== 5. Validation: invalid email rejected ==="
BAD_EMAIL=$(curl -s -b /tmp/cj_donor.txt \
  --data-urlencode "csrf_token=$CSRF" \
  --data-urlencode "slug=test-wedding" \
  --data-urlencode "amount=50" \
  --data-urlencode "currency=GHS" \
  --data-urlencode "donor_email=not-an-email" \
  --data-urlencode "donor_name=Efua" \
  "$BASE/donate.php")
contains "$BAD_EMAIL" "valid email" "invalid email rejected"

echo "=== 6. Manually mark a donation successful (simulating a real confirmed payment) and check totals display ==="
mysql -u root fete -e "INSERT INTO donations (event_id, sub_fund_id, donor_name, amount, currency, amount_in_base, flutterwave_tx_ref, status) VALUES (1, 1, 'Efua', 500.00, 'GHS', 500.00, 'FETE-TEST-SUCCESS-1', 'successful');"
mysql -u root fete -e "INSERT INTO donations (event_id, donor_name, amount, currency, amount_in_base, flutterwave_tx_ref, status) VALUES (1, 'Diaspora Kofi', 100.00, 'USD', 100.00, 'FETE-TEST-SUCCESS-2', 'successful');"

PUBLIC_PAGE=$(curl -s "$BASE/e.php?slug=test-wedding")
contains "$PUBLIC_PAGE" "GHS 500.00" "public event page shows correct GHS total"
contains "$PUBLIC_PAGE" "USD 100.00" "public event page shows USD total SEPARATELY (no fake combined total)"
contains "$PUBLIC_PAGE" "Give a gift" "public event page shows the donate button now that giving is live"

HOST_LOGIN=$(curl -s -c /tmp/cj_host3.txt "$BASE/register.php")
CSRF_H=$(echo "$HOST_LOGIN" | grep -o 'name="csrf_token" value="[^"]*"' | head -1 | sed 's/.*value="//;s/"//')
mysql -u root fete -e "UPDATE users SET email='th2@example.com' WHERE id=1;" > /dev/null 2>&1
curl -s -b /tmp/cj_host3.txt -c /tmp/cj_host3.txt \
  --data-urlencode "csrf_token=$CSRF_H" --data-urlencode "role=host" --data-urlencode "full_name=Test Host2" \
  --data-urlencode "email=viewhost@example.com" --data-urlencode "password=password123" --data-urlencode "ref=" \
  "$BASE/register.php" > /dev/null
mysql -u root fete -e "UPDATE events SET host_id=(SELECT id FROM users WHERE email='viewhost@example.com') WHERE id=1;"
HOST_VIEW=$(curl -s -b /tmp/cj_host3.txt "$BASE/host/event-view.php?id=1")
contains "$HOST_VIEW" "GHS 500.00" "host event-view shows GHS total"
contains "$HOST_VIEW" "USD 100.00" "host event-view shows USD total"
contains "$HOST_VIEW" "1 gift" "host event-view shows per-currency gift counts (1 gift each for GHS and USD, not combined)"

echo "=== 7. Webhook: bad signature rejected with 401 ==="
WEBHOOK_BAD=$(curl -s -o /dev/null -w "%{http_code}" -X POST \
  -H "verif-hash: wrong-hash" \
  -H "Content-Type: application/json" \
  -d '{"event":"charge.completed","data":{"id":"123","tx_ref":"FETE-TEST-SUCCESS-1","amount":500,"currency":"GHS","status":"successful"}}' \
  "$BASE/webhook-flutterwave.php")
check "$WEBHOOK_BAD" "401" "webhook with wrong verif-hash rejected"

echo "=== 8. Webhook: correct signature accepted (200), and idempotency confirmed via unit tests already ==="
SECRET_HASH=$(grep FLW_WEBHOOK_SECRET_HASH /home/claude/fete/app/config/config.php | sed "s/.*'FLW_WEBHOOK_SECRET_HASH', '//;s/'.*//")
echo "using test secret hash: $SECRET_HASH"
WEBHOOK_OK=$(curl -s -o /dev/null -w "%{http_code}" -X POST \
  -H "verif-hash: $SECRET_HASH" \
  -H "Content-Type: application/json" \
  -d '{"event":"charge.completed","data":{"id":"123","tx_ref":"FETE-TEST-SUCCESS-1","amount":500,"currency":"GHS","status":"successful"}}' \
  "$BASE/webhook-flutterwave.php")
check "$WEBHOOK_OK" "200" "webhook with correct verif-hash accepted with 200 (re-verify against live API then fails harmlessly in this sandbox -- expected, see README)"

echo "=== 9. Callback page: unknown tx_ref handled gracefully ==="
CB_UNKNOWN=$(curl -s "$BASE/donate-callback.php?tx_ref=DOES-NOT-EXIST&status=successful")
contains "$CB_UNKNOWN" "couldn't find that payment" "callback page handles unknown tx_ref without crashing"

echo "=== 10. Callback page: already-successful donation shows thank-you without re-verifying ==="
CB_SUCCESS=$(curl -s "$BASE/donate-callback.php?tx_ref=FETE-TEST-SUCCESS-1&status=successful&transaction_id=999")
contains "$CB_SUCCESS" "Thank you" "callback shows thank-you for an already-successful donation"

echo ""
echo "=================================="
echo "RESULTS: $PASS passed, $FAIL failed"
echo "=================================="
kill $SERVER_PID 2>/dev/null
