#!/bin/bash
# Phase 6: withdrawals, admin approval (weekday-gated), and sub-fund transfers.
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
}
not_contains() {
  if echo "$1" | grep -q "$2"; then FAIL=$((FAIL+1)); echo "FAIL: $3 -- unexpectedly found '$2'";
  else PASS=$((PASS+1)); echo "PASS: $3"; fi
}

echo "=== Setup: fresh schema + two hosts, an affiliate, an admin, two events ==="
service mariadb start 2>&1 | tail -1
sleep 2
mysql -u root -e "DROP DATABASE IF EXISTS wishpot_test; CREATE DATABASE wishpot_test;"
mysql -u root wishpot_test < /home/claude/wishpot/database/schema.sql
mysql -u root -e "CREATE USER IF NOT EXISTS 'wishpot_test_user'@'127.0.0.1' IDENTIFIED BY 'testpass123'; GRANT ALL PRIVILEGES ON wishpot_test.* TO 'wishpot_test_user'@'127.0.0.1'; FLUSH PRIVILEGES;"

PWHASH=$(php -r "echo password_hash('password123', PASSWORD_DEFAULT);")
mysql -u root wishpot_test -e "INSERT INTO users (id, role, full_name, email, password_hash) VALUES (1, 'host', 'Host A', 'hosta@example.com', '$PWHASH');"
mysql -u root wishpot_test -e "INSERT INTO users (id, role, full_name, email, password_hash) VALUES (2, 'host', 'Host B', 'hostb@example.com', '$PWHASH');"
mysql -u root wishpot_test -e "INSERT INTO users (id, role, full_name, email, password_hash, referral_code) VALUES (3, 'affiliate', 'Planner P', 'planner@example.com', '$PWHASH', 'PLANP1');"
mysql -u root wishpot_test -e "INSERT INTO users (id, role, full_name, email, password_hash) VALUES (4, 'admin', 'Admin', 'admin@example.com', '$PWHASH');"

YESTERDAY=$(date -d "-1 day" +%Y-%m-%d)
TOMORROW=$(date -d "+1 day" +%Y-%m-%d)

# Event 1: host A, dated in the past -> funds unlocked. Raised GHS 1000.
mysql -u root wishpot_test -e "INSERT INTO events (id, host_id, referring_affiliate_id, name, event_type, event_date, slug, status) VALUES (1, 1, 3, 'Unlocked Wedding', 'wedding', '$YESTERDAY', 'unlocked-wedding', 'live');"
mysql -u root wishpot_test -e "INSERT INTO donations (event_id, donor_name, amount, currency, amount_in_base, flutterwave_tx_ref, status) VALUES (1, 'Donor', 1000.00, 'GHS', 1000.00, 'WISHPOT-P6-1', 'successful');"
mysql -u root wishpot_test -e "INSERT INTO affiliate_commissions (affiliate_id, event_id, donation_id, commission_amount, currency, commission_model, commission_rate, status) VALUES (3, 1, (SELECT id FROM donations WHERE flutterwave_tx_ref='WISHPOT-P6-1'), 80.00, 'GHS', 'percentage', 8, 'accrued');"

# Event 2: host A again, dated in the future -> funds still locked.
mysql -u root wishpot_test -e "INSERT INTO events (id, host_id, name, event_type, event_date, slug, status) VALUES (2, 1, 'Locked Wedding', 'wedding', '$TOMORROW', 'locked-wedding', 'live');"
mysql -u root wishpot_test -e "INSERT INTO donations (event_id, donor_name, amount, currency, amount_in_base, flutterwave_tx_ref, status) VALUES (2, 'Donor', 500.00, 'GHS', 500.00, 'WISHPOT-P6-2', 'successful');"

# Event 3: host B's own event, for cross-user protection checks.
mysql -u root wishpot_test -e "INSERT INTO events (id, host_id, name, event_type, event_date, slug, status) VALUES (3, 2, 'Host B Wedding', 'wedding', '$YESTERDAY', 'hostb-wedding', 'live');"
mysql -u root wishpot_test -e "INSERT INTO sub_funds (id, event_id, name) VALUES (1, 3, 'Host B Fund');"

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

login() {
  local email=$1 jar=$2
  local GET_RESP=$(curl -s -c "$jar" "$BASE/login.php")
  local CSRF=$(echo "$GET_RESP" | grep -o 'name="csrf_token" value="[^"]*"' | head -1 | sed 's/.*value="//;s/"//')
  curl -s -b "$jar" -c "$jar" --data-urlencode "csrf_token=$CSRF" --data-urlencode "email=$email" --data-urlencode "password=password123" "$BASE/login.php" > /dev/null
}

csrf_from() {
  local jar=$1 url=$2
  curl -s -b "$jar" "$url" | grep -o 'name="csrf_token" value="[^"]*"' | head -1 | sed 's/.*value="//;s/"//'
}

login "hosta@example.com" /tmp/cj_hosta.txt
login "hostb@example.com" /tmp/cj_hostb.txt
login "planner@example.com" /tmp/cj_planner.txt
login "admin@example.com" /tmp/cj_admin.txt

echo "=== 1. Host withdrawal page shows the correct available balance ==="
WITHDRAW_PAGE=$(curl -s -b /tmp/cj_hosta.txt "$BASE/host/withdraw.php")
check "$(curl -s -o /dev/null -w '%{http_code}' -b /tmp/cj_hosta.txt "$BASE/host/withdraw.php")" "200" "host withdraw page loads"
CSRF_W=$(echo "$WITHDRAW_PAGE" | grep -o 'name="csrf_token" value="[^"]*"' | head -1 | sed 's/.*value="//;s/"//')

echo "=== 2. Zero-amount withdrawal rejected ==="
curl -s -b /tmp/cj_hosta.txt -c /tmp/cj_hosta.txt \
  --data-urlencode "csrf_token=$CSRF_W" --data-urlencode "event_id=1" --data-urlencode "currency=GHS" --data-urlencode "amount=0" \
  "$BASE/host/withdraw.php" > /dev/null
ZERO_RESP=$(curl -s -b /tmp/cj_hosta.txt "$BASE/host/withdraw.php")
contains "$ZERO_RESP" "greater than zero" "zero-amount withdrawal rejected with a clear message"

echo "=== 3. Withdrawal exceeding available balance rejected ==="
curl -s -b /tmp/cj_hosta.txt -c /tmp/cj_hosta.txt \
  --data-urlencode "csrf_token=$CSRF_W" --data-urlencode "event_id=1" --data-urlencode "currency=GHS" --data-urlencode "amount=5000" \
  "$BASE/host/withdraw.php" > /dev/null
OVER_RESP=$(curl -s -b /tmp/cj_hosta.txt "$BASE/host/withdraw.php")
contains "$OVER_RESP" "is available to withdraw for this event" "over-balance withdrawal rejected with a clear message"

echo "=== 4. Withdrawal on a still-locked event (funds not yet unlocked) rejected ==="
curl -s -b /tmp/cj_hosta.txt -c /tmp/cj_hosta.txt \
  --data-urlencode "csrf_token=$CSRF_W" --data-urlencode "event_id=2" --data-urlencode "currency=GHS" --data-urlencode "amount=50" \
  "$BASE/host/withdraw.php" > /dev/null
LOCKED_RESP=$(curl -s -b /tmp/cj_hosta.txt "$BASE/host/withdraw.php")
contains "$LOCKED_RESP" "unlock 24 hours after the event date" "withdrawal on a locked (future-dated) event's funds rejected"

echo "=== 5. Host B cannot submit a withdrawal against host A's event (cross-user protection) ==="
CSRF_HB=$(csrf_from /tmp/cj_hostb.txt "$BASE/host/withdraw.php")
CROSS_WD_STATUS=$(curl -s -o /dev/null -w "%{http_code}" -b /tmp/cj_hostb.txt \
  --data-urlencode "csrf_token=$CSRF_HB" --data-urlencode "event_id=1" --data-urlencode "currency=GHS" --data-urlencode "amount=10" \
  "$BASE/host/withdraw.php")
check "$CROSS_WD_STATUS" "403" "host B's withdrawal request against host A's event is rejected with 403"

echo "=== 6. Valid host withdrawal request succeeds and shows up pending ==="
curl -s -b /tmp/cj_hosta.txt -c /tmp/cj_hosta.txt \
  --data-urlencode "csrf_token=$CSRF_W" --data-urlencode "event_id=1" --data-urlencode "currency=GHS" --data-urlencode "amount=300" \
  "$BASE/host/withdraw.php" > /dev/null
VALID_RESP=$(curl -s -b /tmp/cj_hosta.txt "$BASE/host/withdraw.php")
contains "$VALID_RESP" "Withdrawal request submitted" "valid withdrawal request confirms success"
contains "$VALID_RESP" "GHS 300.00" "pending request appears in the host's own request history"
WD_ID=$(mysql -u root wishpot_test -N -e "SELECT id FROM withdrawal_requests WHERE requester_id=1 AND requester_role='host' AND amount=300.00;")
check "$(mysql -u root wishpot_test -N -e "SELECT status FROM withdrawal_requests WHERE id=$WD_ID;")" "pending" "withdrawal request row starts pending"

echo "=== 7. Funds page reflects the committed amount (available drops by 300) ==="
FUNDS_PAGE=$(curl -s -b /tmp/cj_hosta.txt "$BASE/host/funds.php?id=1")
contains "$FUNDS_PAGE" "GHS 700.00" "funds page shows available balance reduced by the pending withdrawal (1000 - 300 = 700)"

echo "=== 8. Affiliate withdrawal: over-balance rejected, valid one succeeds ==="
CSRF_AW=$(csrf_from /tmp/cj_planner.txt "$BASE/affiliate/withdraw.php")
curl -s -b /tmp/cj_planner.txt -c /tmp/cj_planner.txt \
  --data-urlencode "csrf_token=$CSRF_AW" --data-urlencode "currency=GHS" --data-urlencode "amount=500" \
  "$BASE/affiliate/withdraw.php" > /dev/null
AFF_OVER=$(curl -s -b /tmp/cj_planner.txt "$BASE/affiliate/withdraw.php")
contains "$AFF_OVER" "is available to withdraw" "affiliate over-balance withdrawal rejected"

curl -s -b /tmp/cj_planner.txt -c /tmp/cj_planner.txt \
  --data-urlencode "csrf_token=$CSRF_AW" --data-urlencode "currency=GHS" --data-urlencode "amount=30" \
  "$BASE/affiliate/withdraw.php" > /dev/null
AFF_OK=$(curl -s -b /tmp/cj_planner.txt "$BASE/affiliate/withdraw.php")
contains "$AFF_OK" "Withdrawal request submitted" "valid affiliate withdrawal request confirms success"
AFF_WD_ID=$(mysql -u root wishpot_test -N -e "SELECT id FROM withdrawal_requests WHERE requester_id=3 AND requester_role='affiliate' AND amount=30.00;")
check "$(mysql -u root wishpot_test -N -e "SELECT event_id FROM withdrawal_requests WHERE id=$AFF_WD_ID;")" "NULL" "affiliate withdrawal request has no event_id (commission withdrawals aren't tied to one event)"

echo "=== 9. Admin withdrawal queue lists both pending requests ==="
ADMIN_QUEUE=$(curl -s -b /tmp/cj_admin.txt "$BASE/admin/withdrawals.php")
contains "$ADMIN_QUEUE" "Pending (2)" "admin queue shows 2 pending requests"
contains "$ADMIN_QUEUE" "Host A" "admin queue lists the host's request"
contains "$ADMIN_QUEUE" "Planner P" "admin queue lists the affiliate's request"
CSRF_ADM=$(echo "$ADMIN_QUEUE" | grep -o 'name="csrf_token" value="[^"]*"' | head -1 | sed 's/.*value="//;s/"//')

echo "=== 10. Non-admin cannot reach the admin withdrawal-review endpoint ==="
HOST_REVIEW_STATUS=$(curl -s -o /dev/null -w "%{http_code}" -b /tmp/cj_hosta.txt \
  --data-urlencode "csrf_token=$CSRF_W" --data-urlencode "withdrawal_id=$WD_ID" --data-urlencode "action=approve" \
  "$BASE/admin/withdrawal-review.php")
check "$HOST_REVIEW_STATUS" "403" "a host posting directly to the admin review endpoint is rejected with 403"

echo "=== 11. Rejecting a request without a note is refused; status stays pending ==="
curl -s -b /tmp/cj_admin.txt \
  --data-urlencode "csrf_token=$CSRF_ADM" --data-urlencode "withdrawal_id=$AFF_WD_ID" --data-urlencode "action=reject" --data-urlencode "admin_notes=" \
  "$BASE/admin/withdrawal-review.php" > /dev/null
AFTER_BLANK_REJECT=$(curl -s -b /tmp/cj_admin.txt "$BASE/admin/withdrawals.php")
contains "$AFTER_BLANK_REJECT" "A note is required when rejecting" "rejecting without a note shows the required-note error"
check "$(mysql -u root wishpot_test -N -e "SELECT status FROM withdrawal_requests WHERE id=$AFF_WD_ID;")" "pending" "request status is unchanged after the refused blank-note rejection"

echo "=== 12. Rejecting with a note succeeds and frees up the affiliate's balance ==="
curl -s -b /tmp/cj_admin.txt \
  --data-urlencode "csrf_token=$CSRF_ADM" --data-urlencode "withdrawal_id=$AFF_WD_ID" --data-urlencode "action=reject" --data-urlencode "admin_notes=Bank details needed" \
  "$BASE/admin/withdrawal-review.php" > /dev/null
check "$(mysql -u root wishpot_test -N -e "SELECT status FROM withdrawal_requests WHERE id=$AFF_WD_ID;")" "rejected" "request correctly marked rejected"
AFF_DASH_AFTER=$(curl -s -b /tmp/cj_planner.txt "$BASE/affiliate/dashboard.php")
contains "$AFF_DASH_AFTER" "GHS 80.00" "rejected request frees the full GHS 80 commission balance back up for the affiliate"

echo "=== 13. Approval is gated to weekdays (server-side, not just the disabled button) ==="
TODAY_DOW=$(date +%u)  # 1=Mon .. 7=Sun
curl -s -b /tmp/cj_admin.txt \
  --data-urlencode "csrf_token=$CSRF_ADM" --data-urlencode "withdrawal_id=$WD_ID" --data-urlencode "action=approve" --data-urlencode "admin_notes=" \
  "$BASE/admin/withdrawal-review.php" > /dev/null
WD_STATUS_AFTER_APPROVE=$(mysql -u root wishpot_test -N -e "SELECT status FROM withdrawal_requests WHERE id=$WD_ID;")
if [ "$TODAY_DOW" -le 5 ]; then
  echo "(today is a weekday in this environment's clock — approval should succeed)"
  check "$WD_STATUS_AFTER_APPROVE" "paid" "weekday approval marks the request paid"
else
  echo "(today is a weekend in this environment's clock — approval should be refused)"
  check "$WD_STATUS_AFTER_APPROVE" "pending" "weekend approval attempt is refused server-side, status stays pending"
  ADMIN_QUEUE_WEEKEND=$(curl -s -b /tmp/cj_admin.txt "$BASE/admin/withdrawals.php")
  contains "$ADMIN_QUEUE_WEEKEND" "Payouts only process on weekdays" "weekend approval attempt shows the payout-gate error"
  contains "$ADMIN_QUEUE_WEEKEND" "approvals (which trigger payout) are blocked" "withdrawal queue shows the weekend warning banner"
fi

echo "=== 14. Sub-fund transfer: within balance succeeds, over balance rejected, cross-event sub-fund blocked ==="
SF_FORM=$(curl -s -b /tmp/cj_hosta.txt "$BASE/host/funds.php?id=1")
curl -s -b /tmp/cj_hosta.txt \
  --data-urlencode "csrf_token=$CSRF_W" --data-urlencode "action=create" --data-urlencode "event_id=1" --data-urlencode "name=Gift Fund" \
  "$BASE/host/subfund-save.php" > /dev/null
SUBFUND_ID=$(mysql -u root wishpot_test -N -e "SELECT id FROM sub_funds WHERE event_id=1 AND name='Gift Fund';")

TRANSFER_OK=$(curl -s -i -b /tmp/cj_hosta.txt \
  --data-urlencode "csrf_token=$CSRF_W" --data-urlencode "event_id=1" --data-urlencode "from_fund=general" --data-urlencode "to_fund=$SUBFUND_ID" \
  --data-urlencode "currency=GHS" --data-urlencode "amount=200" \
  "$BASE/host/fund-transfer.php")
contains "$TRANSFER_OK" "funds.php?id=1" "valid transfer redirects back to the funds page"
FUNDS_AFTER_TRANSFER=$(curl -s -b /tmp/cj_hosta.txt "$BASE/host/funds.php?id=1")
contains "$FUNDS_AFTER_TRANSFER" "GHS 200.00" "destination sub-fund shows the transferred balance"

TRANSFER_OVER=$(curl -s -b /tmp/cj_hosta.txt \
  --data-urlencode "csrf_token=$CSRF_W" --data-urlencode "event_id=1" --data-urlencode "from_fund=general" --data-urlencode "to_fund=$SUBFUND_ID" \
  --data-urlencode "currency=GHS" --data-urlencode "amount=99999" \
  "$BASE/host/fund-transfer.php")
FUNDS_AFTER_OVER=$(curl -s -b /tmp/cj_hosta.txt "$BASE/host/funds.php?id=1")
contains "$FUNDS_AFTER_OVER" "only has" "transferring more than a fund's balance is rejected with a clear message"

CROSS_TRANSFER_STATUS=$(curl -s -o /dev/null -w "%{http_code}" -b /tmp/cj_hosta.txt \
  --data-urlencode "csrf_token=$CSRF_W" --data-urlencode "event_id=1" --data-urlencode "from_fund=general" --data-urlencode "to_fund=1" \
  --data-urlencode "currency=GHS" --data-urlencode "amount=10" \
  "$BASE/host/fund-transfer.php")
check "$CROSS_TRANSFER_STATUS" "403" "transferring into a sub-fund id that belongs to a DIFFERENT host's event is blocked with 403"

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