<?php
require_once __DIR__ . '/plisio_lib.php';
require_once __DIR__ . '/_vpn_helpers.php';
require_once dirname(__DIR__, 3) . '/src/GemAcc/Wallet.php';
header('Content-Type: text/plain; charset=utf-8');
try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo 'Method not allowed'; exit; }
    $post = $_POST;
    if (!$post) { http_response_code(400); echo 'Empty payload'; exit; }
    if (!plisio_verify_callback($post)) { http_response_code(422); echo 'Invalid signature'; exit; }
    $txnId = trim((string)($post['txn_id'] ?? ''));
    $orderNumber = trim((string)($post['order_number'] ?? ''));
    $status = strtolower(trim((string)($post['status'] ?? '')));
    $raw = json_encode($post, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    $cp = null;
    if ($txnId !== '') {
        $st = $pdo->prepare("SELECT * FROM crypto_payments WHERE provider='Plisio' AND provider_invoice_id=? LIMIT 1");
        $st->execute([$txnId]); $cp = $st->fetch(PDO::FETCH_ASSOC);
    }
    if (!$cp && preg_match('/^(ORD|WALLET)-(\d+)$/', $orderNumber, $m)) {
        if ($m[1] === 'ORD') { $st=$pdo->prepare("SELECT * FROM crypto_payments WHERE provider='Plisio' AND order_id=? LIMIT 1"); $st->execute([(int)$m[2]]); }
        else { $st=$pdo->prepare("SELECT * FROM crypto_payments WHERE provider='Plisio' AND wallet_transaction_id=? LIMIT 1"); $st->execute([(int)$m[2]]); }
        $cp = $st->fetch(PDO::FETCH_ASSOC);
    }
    if (!$cp) { http_response_code(404); echo 'Payment not found'; exit; }
    $mapped = in_array($status, ['completed'], true) ? 'PAID' : (in_array($status, ['expired','cancelled','cancelled duplicate','error','mismatch'], true) ? 'FAILED' : strtoupper($status ?: 'PENDING'));
    $pdo->prepare("UPDATE crypto_payments SET status=?, raw_response=?, paid_at=IF(?='PAID',COALESCE(paid_at,NOW()),paid_at), processed_at=IF(? IN ('PAID','FAILED'),NOW(),processed_at) WHERE id=?")->execute([$mapped,$raw,$mapped,$mapped,(int)$cp['id']]);
    if ($mapped === 'PAID') {
        if (($cp['payment_type'] ?? '') === 'order' && !empty($cp['order_id'])) {
            vpnApproveOrderAndNotify($pdo, (int)$cp['order_id'], true);
        } elseif (($cp['payment_type'] ?? '') === 'wallet_topup' && !empty($cp['wallet_transaction_id'])) {
            $wallet = new \GemAcc\Wallet($pdo);
            $res = $wallet->approveDeposit((int)$cp['wallet_transaction_id'], 0);
            if (!empty($res['success'])) tg('sendMessage', ['chat_id'=>(int)$res['user_id'], 'text'=>'✅ پرداخت Plisio شما تأیید شد و کیف پولتان شارژ شد.']);
        }
    }
    echo 'OK';
} catch (Throwable $e) { error_log('[plisio_webhook] '.$e->getMessage()); http_response_code(500); echo 'ERROR'; }
