<?php
require_once __DIR__.'/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__.'/../../engine/Logger.php';
require_once __DIR__.'/../../engine/BankAdapter.php';
$ctx = Kernel::handle(['auth' => true]);
$u   = $ctx['user'];
$txnRef = preg_replace('/[^A-Z0-9_-]/','',strtoupper($_GET['txn_ref']??''));
if(!$txnRef){http_response_code(400);die(json_encode(['error'=>'txn_ref required']));}
try {
    $st = db()->prepare("SELECT status, bank_txn_id, failed_reason, completed_at FROM sdpay_transactions WHERE txn_ref=? LIMIT 1");
    $st->execute([$txnRef]);
    $txn = $st->fetch();
    if(!$txn){http_response_code(404);die(json_encode(['error'=>'not_found']));}
    $statusAr=['pending'=>'معلقة','processing'=>'قيد المعالجة','completed'=>'مكتملة','failed'=>'فاشلة','reversed'=>'مُعكوسة'];
    echo json_encode(['ok'=>true,'txn_ref'=>$txnRef,'status'=>$txn['status'],'status_ar'=>$statusAr[$txn['status']]??$txn['status'],'failed_reason'=>$txn['failed_reason'],'completed_at'=>$txn['completed_at']], JSON_UNESCAPED_UNICODE);
} catch(Throwable $e){http_response_code(500);echo json_encode(['error' => 'server_error', 'message' => 'خطأ مؤقت — حاول مرة أخرى'], JSON_UNESCAPED_UNICODE);}
