<?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);exit;}
$ctx = Kernel::handle(['auth' => true]);
$u   = $ctx['user'];
$b = json_decode(file_get_contents('php://input'),true)??[];
$txnRef = trim($b['txn_ref']??'');
$reason = trim($b['reason']??'');
$desc   = mb_substr(trim($b['description']??''),0,500);
if(!$txnRef||!$reason){http_response_code(400);die(json_encode(['error'=>'txn_ref and reason required']));}
try {
    $st = db()->prepare("SELECT id FROM sdpay_transactions WHERE txn_ref=? AND (from_account IN (SELECT account_no FROM sdpay_accounts WHERE user_id=?) OR to_account IN (SELECT account_no FROM sdpay_accounts WHERE user_id=?)) LIMIT 1");
    $st->execute([$txnRef,(int)$u['id'],(int)$u['id']]);
    $txn = $st->fetch();
    if(!$txn){http_response_code(404);die(json_encode(['error'=>'transaction_not_found']));}
    // Admin can open dispute on behalf of user
    $isAdmin = !empty($u['is_admin']) || !empty($u['user_type']) && in_array($u['user_type'],['admin','staff']);
    db()->prepare("INSERT INTO sdpay_disputes (txn_id,raised_by,reason,description,status) VALUES (?,?,?,?,'open')")->execute([$txn['id'],(int)$u['id'],$reason,$desc]);
    echo json_encode(['ok'=>true,'dispute_id'=>db()->lastInsertId(),'message'=>'تم فتح النزاع — سيتم مراجعته خلال 48 ساعة'], JSON_UNESCAPED_UNICODE);
} catch(\Throwable $e){http_response_code(500);echo json_encode(['error' => 'server_error', 'message' => 'خطأ مؤقت — حاول مرة أخرى'], JSON_UNESCAPED_UNICODE);}
