<?php
/**
 * REVENDA — Rampex Webhook Receiver
 * /htdocs/pages/api/rampex-webhook.php
 * v2.2.0 — Tour-aware. Property vendor email block preserved in fallback.
 *
 * Route: /?page=api-rampex-webhook
 */

require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../database.php';
require_once __DIR__ . '/../../functions.php';
require_once __DIR__ . '/../../includes/rampex.php';
require_once __DIR__ . '/../../includes/payment_service.php';

http_response_code(200);
header('Content-Type: application/json');

$rawBody = file_get_contents('php://input');

// ── Signature header ──
$signature = '';
foreach (['HTTP_X_RAMPEX_SIGNATURE', 'HTTP_X_SIGNATURE', 'HTTP_X_WEBHOOK_SIGNATURE'] as $k) {
    if (!empty($_SERVER[$k])) { $signature = (string)$_SERVER[$k]; break; }
}

// ── Signature verification ──
$verified = false;
if (RAMPEX_WEBHOOK_SECRET !== '' && $signature !== '') {
    $verified = rampexVerifyWebhook($rawBody, $signature);
}

// ── Reject unverified requests when a secret is configured ──
if (RAMPEX_WEBHOOK_SECRET !== '' && !$verified) {
    rampexLogWebhook('rejected', [
        'reason'    => 'invalid_signature',
        'signature' => $signature !== '' ? '[present]' : '[absent]',
    ]);
    echo json_encode(['ok' => false, 'reason' => 'invalid_signature']);
    exit;
}

// ── Parse JSON ──
$payload = json_decode($rawBody, true);
if (!is_array($payload)) {
    rampexLogWebhook('invalid_json', ['raw' => substr($rawBody, 0, 500)]);
    echo json_encode(['ok' => false, 'reason' => 'invalid_json']);
    exit;
}

$parsed = rampexParseWebhook($payload);

rampexLogWebhook($verified ? 'verified' : 'unverified', [
    'signature_present' => $signature !== '',
    'parsed'            => $parsed,
]);

// ══════════════════════════════════════════════════════════
// STEP 1 — Try payment_attempts first (authoritative match)
// ══════════════════════════════════════════════════════════
$attempt        = null;
$booking        = null;
$tourBooking    = null;
$bookingType    = 'property';
$attemptRef     = (string)($parsed['order_id'] ?? $parsed['link_id'] ?? '');

try {
    if ($attemptRef !== '') {
        $attempt = db()->fetchOne(
            "SELECT * FROM payment_attempts WHERE reference = ? OR external_ref = ? ORDER BY id DESC LIMIT 1",
            [$attemptRef, $attemptRef]
        );
    }

    if ($attempt) {
        $bookingType = strtolower((string)($attempt['booking_type'] ?? 'property'));
        if (!in_array($bookingType, ['property', 'tour', 'event'], true)) $bookingType = 'property';
        $attemptBookingId = (int)($attempt['booking_id'] ?? 0);

        if ($bookingType === 'tour') {
            $tourBooking = db()->fetchOne("SELECT * FROM tour_bookings WHERE id = ? LIMIT 1", [$attemptBookingId]);
            if ($tourBooking) $tourBooking['_attempt_ref'] = (string)$attempt['reference'];
        } elseif ($bookingType === 'event') {
            $booking = db()->fetchOne("SELECT * FROM event_registrations WHERE id = ? LIMIT 1", [$attemptBookingId]);
        } else {
            $booking = db()->fetchOne("SELECT * FROM bookings WHERE id = ? LIMIT 1", [$attemptBookingId]);
        }
    }
} catch (Throwable $e) {
    rampexLogWebhook('attempt_lookup_error', ['error' => $e->getMessage()]);
    // Continue to legacy fallback
}

// ══════════════════════════════════════════════════════════
// STEP 2 — Fallback: legacy lookup by booking_reference
//           (exact same logic as v2.0.0, extended for tours)
// ══════════════════════════════════════════════════════════
if (!$booking && !$tourBooking) {
    try {
        if (!empty($parsed['order_id'])) {
            $booking = db()->fetchOne(
                "SELECT * FROM bookings WHERE booking_reference = ? LIMIT 1",
                [$parsed['order_id']]
            );
            if (!$booking) {
                $tourBooking = db()->fetchOne(
                    "SELECT * FROM tour_bookings WHERE booking_ref = ? LIMIT 1",
                    [$parsed['order_id']]
                );
                if ($tourBooking) $bookingType = 'tour';
            }
        }
        if (!$booking && !$tourBooking && !empty($parsed['link_id'])) {
            $booking = db()->fetchOne(
                "SELECT * FROM bookings WHERE bank_transfer_reference = ? LIMIT 1",
                [$parsed['link_id']]
            );
            if (!$booking) {
                $tourBooking = db()->fetchOne(
                    "SELECT * FROM tour_bookings WHERE bank_transfer_reference = ? LIMIT 1",
                    [$parsed['link_id']]
                );
                if ($tourBooking) $bookingType = 'tour';
            }
        }
        if (!$booking && !$tourBooking && !empty($payload['metadata']['booking_id'])) {
            $metaType = strtolower((string)($payload['metadata']['booking_type'] ?? 'property'));
            $metaId   = (int)$payload['metadata']['booking_id'];
            if ($metaType === 'tour') {
                $tourBooking = db()->fetchOne("SELECT * FROM tour_bookings WHERE id = ? LIMIT 1", [$metaId]);
                if ($tourBooking) $bookingType = 'tour';
            } else {
                $booking = db()->fetchOne("SELECT * FROM bookings WHERE id = ? LIMIT 1", [$metaId]);
            }
        }
    } catch (Throwable $e) {
        rampexLogWebhook('db_error', ['error' => $e->getMessage()]);
        echo json_encode(['ok' => false, 'reason' => 'db_error']);
        exit;
    }
}

$activeBooking = $bookingType === 'tour' ? $tourBooking : $booking;

if (!$activeBooking) {
    rampexLogWebhook('booking_not_found', ['parsed' => $parsed, 'type' => $bookingType]);
    echo json_encode(['ok' => false, 'reason' => 'booking_not_found']);
    exit;
}

$activeBookingId = (int)$activeBooking['id'];
$bookingRef      = $bookingType === 'tour'
    ? (string)($activeBooking['booking_ref'] ?? '')
    : (string)($activeBooking['booking_reference'] ?? '');

// ── Idempotency ──
if (strtolower((string)($activeBooking['payment_status'] ?? '')) === 'paid') {
    rampexLogWebhook('already_paid', ['booking_id' => $activeBookingId, 'type' => $bookingType]);
    echo json_encode(['ok' => true, 'note' => 'already_paid']);
    exit;
}

$status     = $parsed['status'];
$paidStates = ['paid', 'success', 'succeeded', 'completed', 'confirmed', 'settled'];
$failStates = ['failed', 'cancelled', 'canceled', 'expired', 'declined', 'error'];

// ══════════════════════════════════════════════════════════
// PAID
// ══════════════════════════════════════════════════════════
if (in_array($status, $paidStates, true)) {

    // Amount sanity check
    $expected = (float)($activeBooking['total_amount'] ?? $activeBooking['total'] ?? 0);
    $received = (float)$parsed['amount'];
    if ($expected > 0 && $received > 0 && abs($expected - $received) > 0.50) {
        rampexLogWebhook('amount_mismatch', [
            'booking_id' => $activeBookingId,
            'type'       => $bookingType,
            'expected'   => $expected,
            'received'   => $received,
        ]);
    }

    // ────────────────────────────────────────────────────
    // PRIMARY PATH — delegate to PaymentService::markPaid()
    //   which updates the correct table AND sends both emails.
    // ────────────────────────────────────────────────────
    $attemptRefForUpdate = '';
    if ($attempt && !empty($attempt['reference'])) {
        $attemptRefForUpdate = (string)$attempt['reference'];
    } elseif (!empty($activeBooking['_attempt_ref'])) {
        $attemptRefForUpdate = (string)$activeBooking['_attempt_ref'];
    }

    if ($attemptRefForUpdate !== '') {
        $att = payment_service()->getAttemptByReference($attemptRefForUpdate);
        if ($att) {
            try {
                payment_service()->markPaid($attemptRefForUpdate, $parsed);
                rampexLogWebhook('paid_ok', [
                    'booking_id' => $activeBookingId,
                    'type'       => $bookingType,
                    'via'        => 'payment_service',
                    'txid'       => $parsed['txid'],
                ]);
                echo json_encode(['ok' => true]);
                exit;
            } catch (Throwable $e) {
                rampexLogWebhook('mark_paid_exception', [
                    'booking_id' => $activeBookingId,
                    'error'      => $e->getMessage(),
                ]);
                // Fall through to direct update
            }
        }
    }

    // ────────────────────────────────────────────────────
    // FALLBACK PATH — direct update + manual email send
    //   Preserves ALL v2.0.0 behavior for property bookings.
    // ────────────────────────────────────────────────────
    try {
        if ($bookingType === 'tour') {
            db()->query(
                "UPDATE tour_bookings SET
                    payment_status        = 'paid',
                    status                = CASE WHEN status IN ('inquiry','pending') THEN 'confirmed' ELSE status END,
                    deposit_paid          = CASE WHEN deposit_paid = 0 OR deposit_paid IS NULL THEN total ELSE deposit_paid END,
                    balance_due           = 0,
                    payment_txn_id        = ?,
                    payment_method_chosen = COALESCE(NULLIF(payment_method_chosen,''), 'card')
                 WHERE id = ?",
                [(string)$parsed['txid'], $activeBookingId]
            );
        } else {
            db()->query(
                "UPDATE bookings SET
                    payment_status        = 'paid',
                    status                = CASE WHEN status = 'pending' THEN 'confirmed' ELSE status END,
                    paid_at               = COALESCE(paid_at, NOW()),
                    payment_txn_id        = ?,
                    payment_method_chosen = COALESCE(NULLIF(payment_method_chosen,''), 'card')
                 WHERE id = ?",
                [(string)$parsed['txid'], $activeBookingId]
            );
        }
    } catch (Throwable $e) {
        rampexLogWebhook('update_paid_failed', ['booking_id' => $activeBookingId, 'error' => $e->getMessage()]);
        echo json_encode(['ok' => false, 'reason' => 'update_failed']);
        exit;
    }

    // In-app notification to guest
    try {
        if (function_exists('createNotification')) {
            $notifyUserId = (int)($activeBooking['user_id'] ?? 0);
            if ($notifyUserId > 0) {
                createNotification(
                    $notifyUserId,
                    'payment',
                    'Payment confirmed — #' . $bookingRef,
                    'Your payment of '
                        . strtoupper((string)($activeBooking['currency'] ?? 'USD')) . ' '
                        . number_format((float)($activeBooking['total_amount'] ?? $activeBooking['total'] ?? 0), 2)
                        . ' has been received.',
                    $bookingType === 'tour'
                        ? '/?page=tour-booking-confirm&ref=' . urlencode($bookingRef)
                        : '/?page=booking&id=' . $activeBookingId,
                    'fa-check-circle'
                );
            }
        }
    } catch (Throwable $e) {}

    // ─── GUEST CONFIRMATION EMAIL ───
    if (function_exists('miceSendMail') && filter_var($activeBooking['guest_email'] ?? '', FILTER_VALIDATE_EMAIL)) {
        try {
            $base     = defined('SITE_URL') ? rtrim(SITE_URL, '/') : 'https://revenda.tanzaquest.com';
            $replyTo  = defined('SITE_EMAIL') ? SITE_EMAIL : 'info@tanzaquest.com';
            $guest    = htmlspecialchars((string)($activeBooking['guest_name'] ?? 'Guest'), ENT_QUOTES, 'UTF-8');
            $cur      = htmlspecialchars((string)($activeBooking['currency'] ?? 'USD'), ENT_QUOTES, 'UTF-8');
            $safeRef  = htmlspecialchars($bookingRef, ENT_QUOTES, 'UTF-8');

            if ($bookingType === 'tour') {
                $pkgName = htmlspecialchars((string)($activeBooking['package_name'] ?? 'your tour'), ENT_QUOTES, 'UTF-8');
                $sd      = htmlspecialchars((string)($activeBooking['start_date'] ?? ''), ENT_QUOTES, 'UTF-8');
                $ed      = htmlspecialchars((string)($activeBooking['end_date'] ?? ''), ENT_QUOTES, 'UTF-8');
                $total   = number_format((float)($activeBooking['total'] ?? 0), 2);
                $viewUrl = $base . '/?page=tour-booking-confirm&ref=' . urlencode($bookingRef);

                $body  = '<div style="font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;max-width:600px;margin:0 auto;color:#2d3748;">';
                $body .= '<h2 style="color:#00b894;margin:0 0 16px;">Payment received — tour confirmed</h2>';
                $body .= '<p>Hi ' . $guest . ',</p>';
                $body .= '<p>Thank you for your payment. Your tour booking <strong>' . $pkgName . '</strong> is fully confirmed.</p>';
                $body .= '<table style="border-collapse:collapse;margin:20px 0;width:100%;font-size:14px;">';
                $body .= '<tr><td style="padding:8px 12px 8px 0;color:#718096;">Reference</td><td style="padding:8px 0;font-family:monospace;font-weight:800;text-align:right;">' . $safeRef . '</td></tr>';
                $body .= '<tr><td style="padding:8px 12px 8px 0;color:#718096;">Departure</td><td style="padding:8px 0;font-weight:700;text-align:right;">' . $sd . '</td></tr>';
                $body .= '<tr><td style="padding:8px 12px 8px 0;color:#718096;">Return</td><td style="padding:8px 0;font-weight:700;text-align:right;">' . $ed . '</td></tr>';
                $body .= '<tr style="border-top:2px solid #00b894;"><td style="padding:12px 12px 12px 0;font-weight:800;font-size:16px;">Amount paid</td><td style="padding:12px 0;font-weight:900;font-size:18px;text-align:right;color:#00b894;">' . $cur . ' ' . $total . '</td></tr>';
                $body .= '</table>';
                $body .= '<p><a href="' . htmlspecialchars($viewUrl, ENT_QUOTES, 'UTF-8') . '" style="display:inline-block;padding:12px 24px;background:#00b894;color:#fff;text-decoration:none;border-radius:10px;font-weight:800;">View booking &amp; voucher</a></p>';
                $body .= '<p style="color:#a0aec0;font-size:13px;margin-top:24px;">The operator has been notified and is expecting you.</p>';
                $body .= '</div>';

                $ok = miceSendMail(
                    $activeBooking['guest_email'],
                    'Payment received — tour confirmed #' . $bookingRef,
                    $body,
                    $replyTo
                );
            } else {
                $propName = htmlspecialchars((string)($activeBooking['property_name'] ?? 'your stay'), ENT_QUOTES, 'UTF-8');
                $total    = number_format((float)($activeBooking['total_amount'] ?? 0), 2);
                $ci       = htmlspecialchars((string)($activeBooking['check_in'] ?? ''), ENT_QUOTES, 'UTF-8');
                $co       = htmlspecialchars((string)($activeBooking['check_out'] ?? ''), ENT_QUOTES, 'UTF-8');
                $viewUrl  = $base . '/?page=booking&id=' . $activeBookingId;

                $body  = '<div style="font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;max-width:600px;margin:0 auto;color:#2d3748;">';
                $body .= '<h2 style="color:#00b894;margin:0 0 16px;">Payment received — booking confirmed</h2>';
                $body .= '<p>Hi ' . $guest . ',</p>';
                $body .= '<p>Thank you for your payment. Your booking at <strong>' . $propName . '</strong> is now fully confirmed.</p>';
                $body .= '<table style="border-collapse:collapse;margin:20px 0;width:100%;font-size:14px;">';
                $body .= '<tr><td style="padding:8px 12px 8px 0;color:#718096;">Reference</td><td style="padding:8px 0;font-family:monospace;font-weight:800;text-align:right;">' . $safeRef . '</td></tr>';
                $body .= '<tr><td style="padding:8px 12px 8px 0;color:#718096;">Check-in</td><td style="padding:8px 0;font-weight:700;text-align:right;">' . $ci . '</td></tr>';
                $body .= '<tr><td style="padding:8px 12px 8px 0;color:#718096;">Check-out</td><td style="padding:8px 0;font-weight:700;text-align:right;">' . $co . '</td></tr>';
                $body .= '<tr style="border-top:2px solid #00b894;"><td style="padding:12px 12px 12px 0;font-weight:800;font-size:16px;">Amount paid</td><td style="padding:12px 0;font-weight:900;font-size:18px;text-align:right;color:#00b894;">' . $cur . ' ' . $total . '</td></tr>';
                $body .= '</table>';
                $body .= '<p><a href="' . htmlspecialchars($viewUrl, ENT_QUOTES, 'UTF-8') . '" style="display:inline-block;padding:12px 24px;background:#00b894;color:#fff;text-decoration:none;border-radius:10px;font-weight:800;">View booking details</a></p>';
                $body .= '<p style="color:#a0aec0;font-size:13px;margin-top:24px;">The property has been notified and will be expecting you. Enjoy your stay!</p>';
                $body .= '</div>';

                $ok = miceSendMail(
                    $activeBooking['guest_email'],
                    'Payment received — booking confirmed #' . $bookingRef,
                    $body,
                    $replyTo
                );
            }

            if (!$ok) {
                rampexLogWebhook('guest_email_failed', [
                    'booking_id' => $activeBookingId,
                    'type'       => $bookingType,
                    'email'      => $activeBooking['guest_email'],
                ]);
            }
        } catch (Throwable $e) {
            rampexLogWebhook('guest_email_exception', [
                'booking_id' => $activeBookingId,
                'error'      => $e->getMessage(),
            ]);
        }
    }

    // ─── VENDOR / OPERATOR CONFIRMATION EMAIL ───
    if (function_exists('miceSendMail')) {
        try {
            $base    = defined('SITE_URL') ? rtrim(SITE_URL, '/') : 'https://revenda.tanzaquest.com';
            $replyTo = defined('SITE_EMAIL') ? SITE_EMAIL : 'info@tanzaquest.com';

            if ($bookingType === 'tour') {
                // Tour operator email
                $operatorEmail = trim((string)($activeBooking['operator_email'] ?? ''));
                if ($operatorEmail === '' && !empty($activeBooking['operator_id'])) {
                    $op = db()->fetchOne("SELECT email FROM tour_operators WHERE id = ? LIMIT 1", [(int)$activeBooking['operator_id']]);
                    $operatorEmail = trim((string)($op['email'] ?? ''));
                }

                if ($operatorEmail !== '' && filter_var($operatorEmail, FILTER_VALIDATE_EMAIL)) {
                    $dashUrl = $base . '/?page=vendor-tour-bookings';
                    $safeRef = htmlspecialchars($bookingRef, ENT_QUOTES, 'UTF-8');
                    $guest   = htmlspecialchars((string)($activeBooking['guest_name'] ?? 'Guest'), ENT_QUOTES, 'UTF-8');
                    $cur     = htmlspecialchars((string)($activeBooking['currency'] ?? 'USD'), ENT_QUOTES, 'UTF-8');
                    $total   = number_format((float)($activeBooking['total'] ?? 0), 2);
                    $pkgName = htmlspecialchars((string)($activeBooking['package_name'] ?? 'your tour'), ENT_QUOTES, 'UTF-8');

                    $vBody  = '<div style="font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;max-width:600px;margin:0 auto;color:#2d3748;">';
                    $vBody .= '<h2 style="color:#00b894;margin:0 0 16px;">Tour payment confirmed</h2>';
                    $vBody .= '<p><strong>' . $guest . '</strong> has paid for booking <strong>' . $safeRef . '</strong> for <strong>' . $pkgName . '</strong>.</p>';
                    $vBody .= '<p><strong>Amount paid:</strong> ' . $cur . ' ' . $total . '</p>';
                    $vBody .= '<p><a href="' . htmlspecialchars($dashUrl, ENT_QUOTES, 'UTF-8') . '" style="display:inline-block;padding:12px 24px;background:#00b894;color:#fff;text-decoration:none;border-radius:10px;font-weight:800;">Manage bookings</a></p>';
                    $vBody .= '</div>';

                    miceSendMail(
                        $operatorEmail,
                        'Tour payment confirmed — #' . $bookingRef,
                        $vBody,
                        $replyTo
                    );
                }
            } else {
                // Property vendor email — verbatim from v2.0.0
                $vendorId    = (int)($activeBooking['vendor_id'] ?? 0);
                $vendorEmail = '';
                if ($vendorId > 0) {
                    $vrow = db()->fetchOne(
                        "SELECT business_email, company_name, user_id FROM vendors WHERE id = ? LIMIT 1",
                        [$vendorId]
                    );
                    if ($vrow) {
                        $vendorEmail = trim((string)($vrow['business_email'] ?? ''));
                        if ($vendorEmail === '' && !empty($vrow['user_id'])) {
                            $u = db()->fetchOne("SELECT email FROM users WHERE id = ? LIMIT 1", [(int)$vrow['user_id']]);
                            $vendorEmail = trim((string)($u['email'] ?? ''));
                        }
                    }
                }

                if ($vendorEmail !== '' && filter_var($vendorEmail, FILTER_VALIDATE_EMAIL)) {
                    $dashUrl  = $base . '/?page=vendor-booking-detail&id=' . $activeBookingId;
                    $safeRef  = htmlspecialchars($bookingRef, ENT_QUOTES, 'UTF-8');
                    $propName = htmlspecialchars((string)($activeBooking['property_name'] ?? ''), ENT_QUOTES, 'UTF-8');
                    $guest    = htmlspecialchars((string)($activeBooking['guest_name'] ?? 'Guest'), ENT_QUOTES, 'UTF-8');
                    $cur      = htmlspecialchars((string)($activeBooking['currency'] ?? 'USD'), ENT_QUOTES, 'UTF-8');
                    $total    = number_format((float)($activeBooking['total_amount'] ?? 0), 2);
                    $payout   = number_format((float)($activeBooking['vendor_payout'] ?? 0), 2);
                    $ci       = htmlspecialchars((string)($activeBooking['check_in'] ?? ''), ENT_QUOTES, 'UTF-8');
                    $co       = htmlspecialchars((string)($activeBooking['check_out'] ?? ''), ENT_QUOTES, 'UTF-8');

                    $vBody  = '<div style="font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;max-width:600px;margin:0 auto;color:#2d3748;">';
                    $vBody .= '<h2 style="color:#00b894;margin:0 0 16px;">Payment confirmed — guest is booked</h2>';
                    $vBody .= '<p>The guest has paid for their stay at <strong>' . $propName . '</strong>. Please prepare for their arrival.</p>';
                    $vBody .= '<table style="border-collapse:collapse;margin:20px 0;width:100%;font-size:14px;">';
                    $vBody .= '<tr><td style="padding:6px 12px 6px 0;color:#718096;">Reference</td><td style="padding:6px 0;font-family:monospace;font-weight:800;text-align:right;">' . $safeRef . '</td></tr>';
                    $vBody .= '<tr><td style="padding:6px 12px 6px 0;color:#718096;">Guest</td><td style="padding:6px 0;font-weight:700;text-align:right;">' . $guest . '</td></tr>';
                    $vBody .= '<tr><td style="padding:6px 12px 6px 0;color:#718096;">Check-in</td><td style="padding:6px 0;font-weight:700;text-align:right;">' . $ci . '</td></tr>';
                    $vBody .= '<tr><td style="padding:6px 12px 6px 0;color:#718096;">Check-out</td><td style="padding:6px 0;font-weight:700;text-align:right;">' . $co . '</td></tr>';
                    $vBody .= '<tr style="border-top:2px solid #00b894;"><td style="padding:12px 12px 12px 0;font-weight:800;">Booking total</td><td style="padding:12px 0;font-weight:900;text-align:right;">' . $cur . ' ' . $total . '</td></tr>';
                    $vBody .= '<tr><td style="padding:6px 12px 6px 0;color:#718096;">Your payout</td><td style="padding:6px 0;font-weight:900;text-align:right;color:#00b894;">' . $cur . ' ' . $payout . '</td></tr>';
                    $vBody .= '</table>';
                    $vBody .= '<p><a href="' . htmlspecialchars($dashUrl, ENT_QUOTES, 'UTF-8') . '" style="display:inline-block;padding:12px 24px;background:#00b894;color:#fff;text-decoration:none;border-radius:10px;font-weight:800;">View in dashboard</a></p>';
                    $vBody .= '</div>';

                    miceSendMail(
                        $vendorEmail,
                        'Payment confirmed — #' . $bookingRef,
                        $vBody,
                        $replyTo
                    );
                }
            }
        } catch (Throwable $e) {
            rampexLogWebhook('vendor_email_exception', [
                'booking_id' => $activeBookingId,
                'type'       => $bookingType,
                'error'      => $e->getMessage(),
            ]);
        }
    }

    rampexLogWebhook('paid_ok', [
        'booking_id' => $activeBookingId,
        'type'       => $bookingType,
        'via'        => 'fallback_direct',
        'txid'       => $parsed['txid'],
    ]);
    echo json_encode(['ok' => true]);
    exit;
}

// ══════════════════════════════════════════════════════════
// FAILED
// ══════════════════════════════════════════════════════════
if (in_array($status, $failStates, true)) {
    try {
        if ($bookingType === 'tour') {
            db()->query("UPDATE tour_bookings SET payment_status = 'failed' WHERE id = ?", [$activeBookingId]);
        } else {
            db()->query("UPDATE bookings SET payment_status = 'failed' WHERE id = ?", [$activeBookingId]);
        }
    } catch (Throwable $e) {}

    try {
        if (function_exists('createNotification')) {
            $notifyUserId = (int)($activeBooking['user_id'] ?? 0);
            if ($notifyUserId > 0) {
                createNotification(
                    $notifyUserId,
                    'payment',
                    'Payment failed',
                    'Your payment for booking ' . $bookingRef . ' did not succeed. Please try again.',
                    $bookingType === 'tour'
                        ? '/?page=tour-booking-confirm&ref=' . urlencode($bookingRef)
                        : '/?page=booking&id=' . $activeBookingId
                );
            }
        }
    } catch (Throwable $e) {}

    rampexLogWebhook('payment_failed', ['booking_id' => $activeBookingId, 'type' => $bookingType, 'status' => $status]);
    echo json_encode(['ok' => true]);
    exit;
}

rampexLogWebhook('status_ignored', ['booking_id' => $activeBookingId, 'type' => $bookingType, 'status' => $status]);
echo json_encode(['ok' => true, 'note' => 'status_ignored']);