<?php
/**
 * تتبع معاملة بعينها
 * GET /api/pay/track.php?txn_ref=TRFxxx
 * GET /api/pay/track.php?bank_txn_id=xxx
 */
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']??''));
$bankTxnId = trim($_GET['bank_txn_id']??'');
if(!$txnRef && !$bankTxnId){http_response_code(400);die(json_encode(['error'=>'txn_ref or bank_txn_id required']));}
try {
    $st = db()->prepare(
        "SELECT t.*, sa_from.user_id as from_user_id, sa_to.user_id as to_user_id,
         bc.status as bank_status, bc.confirmed_at as bank_confirmed_at, bc.error_code, bc.error_message
         FROM sdpay_transactions t
         LEFT JOIN sdpay_accounts sa_from ON sa_from.account_no=t.from_account
         LEFT JOIN sdpay_accounts sa_to   ON sa_to.account_no=t.to_account
         LEFT JOIN bank_confirmations bc  ON bc.sdpay_txn_ref=t.txn_ref
         WHERE t.txn_ref=? OR t.bank_txn_id=?
         LIMIT 1"
    );
    $st->execute([$txnRef, $bankTxnId]);
    $txn = $st->fetch();
    if(!$txn){http_response_code(404);die(json_encode(['error'=>'transaction_not_found']));}
    // تحقق أن المستخدم طرف في المعاملة
    if($txn['from_user_id'] !== (int)$u['id'] && $txn['to_user_id'] !== (int)$u['id']){
        http_response_code(403);die(json_encode(['error'=>'access_denied']));
    }
    // إذا معلقة — اسأل البنك عن الحالة
    $bankStatus = null;
    if($txn['status']==='processing' && $txn['bank_txn_id']) {
        $bankStatus = BankAdapter::getTransactionStatus($txn['bank_txn_id']);
    }
    $statusLabels = [
        'pending'=>'في الانتظار','processing'=>'جاري المعالجة',
        'completed'=>'مكتملة','failed'=>'فاشلة','reversed'=>'مُعكوسة','disputed'=>'متنازع عليها'
    ];
    echo json_encode([
        'ok'         => true,
        'txn_ref'    => $txn['txn_ref'],
        'type'       => $txn['type'],
        'amount_sdg' => $txn['amount_sdg'],
        'fee_sdg'    => $txn['fee_sdg'],
        'status'     => $txn['status'],
        'status_ar'  => $statusLabels[$txn['status']] ?? $txn['status'],
        'failed_reason' => $txn['failed_reason'],
        'bank_txn_id'=> $txn['bank_txn_id'],
        'bank_status'=> $bankStatus,
        'narration'  => $txn['narration'],
        'created_at' => $txn['created_at'],
        'completed_at'=> $txn['completed_at'],
        'can_reverse'=> ($txn['can_reverse_until'] && strtotime($txn['can_reverse_until'])>time() && $txn['status']==='completed'),
        'can_dispute'=> in_array($txn['status'],['completed','failed']),
    ], JSON_UNESCAPED_UNICODE);
} catch(Throwable $e){http_response_code(500);echo json_encode(['error' => 'server_error', 'message' => 'خطأ مؤقت — حاول مرة أخرى'], JSON_UNESCAPED_UNICODE);}
