<?php
require_once 'config.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 * FROM crypto_payments WHERE provider_order_id=? AND payment_type='wallet_topup' LIMIT 1");
    $st->execute([$providerOrderId]);
    $pay = $st->fetch(PDO::FETCH_ASSOC);
    if (!$pay) sw_json_error('crypto wallet payment not found');
    $txId = (int)$pay['wallet_transaction_id'];

    if (sw_is_paid_status($verifiedStatus)) {
        $pdo->beginTransaction();
        try {
            $st = $pdo->prepare("SELECT * FROM wallet_transactions WHERE id=? FOR UPDATE");
            $st->execute([$txId]);
            $tx = $st->fetch(PDO::FETCH_ASSOC);
            if (!$tx) throw new RuntimeException('wallet transaction not found');
            if (strtoupper((string)$tx['status']) !== 'COMPLETED') {
                $pdo->prepare("UPDATE wallet_transactions SET status='COMPLETED', receipt_text=?, processed_at=NOW() WHERE id=?")->execute([$raw, $txId]);
                $pdo->prepare("UPDATE users SET balance=balance+? WHERE id=?")->execute([(int)$tx['amount'], (int)$tx['user_id']]);
            }
            $pdo->prepare("UPDATE crypto_payments SET status='PAID', paid_at=COALESCE(paid_at,NOW()), raw_response=? WHERE id=?")->execute([$raw, (int)$pay['id']]);
            $pdo->commit();
            sw_json_ok(['verified_status' => $verifiedStatus]);
        } 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 wallet_transactions SET status='FAILED', receipt_text=? WHERE id=? AND status<>'COMPLETED'")->execute([$raw, $txId]);
        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_wallet_webhook] ' . $e->getMessage());
    sw_json_error($e->getMessage());
}
