<?php
/**
 * Sudanna Pay — Partner Payment Init
 * POST /api/partners/init.php
 *
 * Headers:
 *   X-Api-Key: sk_live_xxx
 *   X-Timestamp: unix_timestamp
 *   X-Signature: hmac_sha256(timestamp+body, secret)
 *
 * Body:
 *   {
 *     "amount_sdg": 5000,
 *     "partner_reference": "ORDER-123",
 *     "description": "شراء منتج",
 *     "callback_url": "https://yoursite.com/webhook",
 *     "integration_type": "hosted|inline|api",
 *     "customer_phone": "0912345678" (optional)
 *   }
 */
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, X-Api-Key, X-Timestamp, X-Signature');
if($_SERVER['REQUEST_METHOD']==='OPTIONS'){http_response_code(200);exit;}
if($_SERVER['REQUEST_METHOD']!=='POST'){http_response_code(405);exit;}
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'] ?? '';
$rawBody   = file_get_contents('php://input');
$b         = json_decode($rawBody, true) ?? [];

if(!$apiKey||!$timestamp||!$signature){
    http_response_code(401);die(json_encode(['error'=>'Authentication headers required']));
}

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

$result = IntegrationEngine::initiatePayment($partner, $b);
http_response_code(($result['ok']??false)?200:400);
echo json_encode($result, JSON_UNESCAPED_UNICODE);
