<?php
require_once 'config.php';
require_once '_vpn_helpers.php';
require_once 'swapwallet_lib.php';
header('Content-Type: application/json; charset=utf-8');

try {
    $input = json_decode(file_get_contents('php://input'), true) ?: $_POST;
    $providerOrderId = sw_order_id_from_webhook($input);
    if ($providerOrderId === '') sw_json_error('orderId required');

    $verify = sw_get_invoice_by_order_id($providerOrderId);
    $verifiedStatus = sw_status_from_json($verify['json']);
    $raw = json_encode(['webhook' => $input, 'verified' => $verify['json']], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

    $st = $pdo->prepare("SELECT cp.*, o.user_id AS order_user_id FROM crypto_payments cp LEFT JOIN orders o ON o.id=cp.order_id WHERE cp.provider_order_id=? AND cp.payment_type='order' LIMIT 1");
    $st->execute([$providerOrderId]);
    $pay = $st->fetch(PDO::FETCH_ASSOC);
    if (!$pay) sw_json_error('crypto payment not found');

    $orderId = (int)$pay['order_id'];
    $st = $pdo->prepare("SELECT * FROM orders WHERE id=?");
    $st->execute([$orderId]);
    $order = $st->fetch(PDO::FETCH_ASSOC);
    if (!$order) sw_json_error('order not found');

    if (sw_is_paid_status($verifiedStatus)) {
        $pdo->beginTransaction();
        try {
            $pdo->prepare("UPDATE crypto_payments SET status='PAID', paid_at=COALESCE(paid_at,NOW()), raw_response=? WHERE id=?")->execute([$raw, (int)$pay['id']]);
            $pdo->prepare("UPDATE orders SET payment_status='paid', status=IF(status='PENDING','PAID',status) WHERE id=?")->execute([$orderId]);
            $count = vpnOrderRequestedSeats($order);
            $creds = vpnAllocateCredentials($pdo, $order, $count);
            if (!$creds) vpnQueueOrderWithCount($pdo, $order, $count);
            $pdo->commit();
            $notification = $creds ? vpnNotifyDeliveryBatch((int)$order['user_id'], $creds, $order, $orderId, $pdo) : null;
            sw_json_ok(['verified_status' => $verifiedStatus, 'delivered' => count($creds), 'queued' => !$creds, 'notification' => $notification]);
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            throw $e;
        }
    }

    if (sw_is_failed_status($verifiedStatus)) {
        $pdo->prepare("UPDATE crypto_payments SET status=?, raw_response=? WHERE id=? AND status<>'PAID'")->execute([$verifiedStatus, $raw, (int)$pay['id']]);
        $pdo->prepare("UPDATE orders SET payment_status='failed', status='REJECTED' WHERE id=? AND status IN ('PENDING','PAID')")->execute([$orderId]);
        sw_json_ok(['verified_status' => $verifiedStatus]);
    }

    $pdo->prepare("UPDATE crypto_payments SET raw_response=? WHERE id=?")->execute([$raw, (int)$pay['id']]);
    sw_json_ok(['verified_status' => $verifiedStatus ?: 'UNKNOWN']);
} catch (Throwable $e) {
    error_log('[swapwallet_webhook] ' . $e->getMessage());
    sw_json_error($e->getMessage());
}
