<?php
header('Access-Control-Allow-Origin: *');
require_once __DIR__.'/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
Kernel::handle(['auth' => false, 'public' => true]);
require_once __DIR__.'/../../engine/Logger.php';
require_once __DIR__.'/../../engine/IntegrationEngine.php';

$apiKey    = $_SERVER['HTTP_X_API_KEY'] ?? '';
$timestamp = $_SERVER['HTTP_X_TIMESTAMP'] ?? '';
$signature = $_SERVER['HTTP_X_SIGNATURE'] ?? '';
$query     = $_SERVER['QUERY_STRING'] ?? '';

$partner = IntegrationEngine::authenticatePartner($apiKey, $timestamp, $signature, $query);
if(!$partner){http_response_code(401);die(json_encode(['error'=>'Auth failed']));}

try {
    $limit  = min((int)($_GET['limit']??20), 100);
    $status = preg_replace('/[^a-z]/','',$_GET['status']??'');
    $where  = 'partner_id=?';
    $params = [$partner['id']];
    if($status){$where.=' AND status=?';$params[]=$status;}
    $st = db()->prepare(
        "SELECT payment_id,partner_reference,amount_sdg,description,status,integration_type,completed_at,created_at
         FROM sdpay_partner_transactions WHERE {$where} ORDER BY created_at DESC LIMIT ?"
    );
    $params[]=$limit;
    $st->execute($params);
    $txns = $st->fetchAll();
    echo json_encode(['ok'=>true,'data'=>$txns,'count'=>count($txns)], JSON_UNESCAPED_UNICODE);
} catch(\Throwable $e){
    http_response_code(500);echo json_encode(['error' => 'server_error', 'message' => 'خطأ مؤقت — حاول مرة أخرى'], JSON_UNESCAPED_UNICODE);
}
