<?php
/** API: استقبال Webhooks من البنوك الشريكة */
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
require_once dirname(__DIR__).'/config.php';
require_once __DIR__.'/../engine/BankAdapter.php';

$payload   = json_decode(file_get_contents('php://input'), true) ?? [];
$signature = $_SERVER['HTTP_X_BANK_SIGNATURE'] ?? $_SERVER['HTTP_X_SIGNATURE'] ?? '';
$instCode  = $_SERVER['HTTP_X_INSTITUTION'] ?? 'BOK';

try {
    $inst = db()->prepare("SELECT id FROM financial_institutions WHERE code=? LIMIT 1");
    $inst->execute([$instCode]);
    $institutionId = (int)($inst->fetchColumn() ?? 0);
} catch(Throwable $e){ $institutionId = 0; }

$result = BankAdapter::processWebhook($payload, $signature, $institutionId);
http_response_code($result['ok'] ? 200 : 400);
echo json_encode($result, JSON_UNESCAPED_UNICODE);
