<?php
require_once __DIR__.'/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__.'/../../engine/Logger.php';
require_once __DIR__.'/../../engine/SudannaPayEngine.php';
if ($_SERVER['REQUEST_METHOD']!=='POST'){http_response_code(405);die(json_encode(['error'=>'method_not_allowed']));}
$ctx = Kernel::handle(['auth' => true]);
$u   = $ctx['user'];
$b = json_decode(file_get_contents('php://input'),true)??[];
$to     = trim($b['to_account'] ?? $b['to_phone'] ?? '');
$amount = (float)($b['amount_sdg'] ?? 0);
$pin    = trim($b['pin'] ?? '');
$idem   = trim($b['idempotency_key'] ?? uniqid('tf_',true));
$narr   = mb_substr(trim($b['narration'] ?? ''),0,100);
if(!$to || $amount<=0 || !$pin){http_response_code(400);die(json_encode(['error'=>'missing_fields']));}
// هاتف أم رقم حساب؟
if(preg_match('/^\d{9,13}$/', $to)){
  $acc = SudannaPayEngine::getAccountByPhone($to);
  if(!$acc){http_response_code(404);die(json_encode(['error'=>'recipient_not_found']));}
  $to = $acc['account_no'];
}
$result = SudannaPayEngine::transfer((int)$u['id'], $to, $amount, $narr, $idem, $pin);
http_response_code(($result['ok']??false)?200:400);
echo json_encode($result, JSON_UNESCAPED_UNICODE);
