<?php
require_once __DIR__.'/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__.'/../../engine/Logger.php';
$ctx = Kernel::handle(['auth' => 'admin']);
$admin = $ctx['user']; // admin session array
$u     = $admin;          // alias for backward compat
try {
    $status = preg_replace('/[^a-z]/','', $_GET['status'] ?? 'open');
    $st = db()->prepare(
        "SELECT d.*, t.txn_ref, t.amount_sdg, u.name as user_name 
         FROM sdpay_disputes d
         JOIN sdpay_transactions t ON t.id=d.txn_id
         JOIN users u ON u.id=d.raised_by
         WHERE d.status=? ORDER BY d.created_at DESC LIMIT 50"
    );
    $st->execute([$status]);
    echo json_encode(['ok'=>true,'data'=>$st->fetchAll(),'status'=>$status], JSON_UNESCAPED_UNICODE);
} catch(Throwable $e){http_response_code(500);echo json_encode(['error' => 'server_error', 'message' => 'خطأ مؤقت — حاول مرة أخرى'], JSON_UNESCAPED_UNICODE);}
