<?php
// /v1/main/ride/mtn/passenger/initiate_payment.php
include "../../../jwtconnect.php";

$baseUrl       = rtrim(getenv('MTN_API_BASE_URL'), '/');
$terminalId    = getenv('MTN_TERMINAL_ID');
$privateKeyPem = getenv('MTN_PRIVATE_KEY');

$invoice = filterRequest('invoice');  // رقم الفاتورة
$phone   = filterRequest('phone');    // رقم الزبون
$guid    = uniqid('mtn_');

if (!$invoice || !$phone) {
    printFailure("Missing invoice or phone.");
    exit;
}

$body = json_encode([
    'Invoice' => intval($invoice),
    'Phone'   => $phone,
    'Guid'    => $guid
], JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);

$hash = hash('sha256', $body, true);
$pkey = openssl_get_privatekey($privateKeyPem);
if (!$pkey) {
    error_log("[MTN Initiate] Failed to load private key");
    printFailure("Payment configuration error");
    exit;
}
openssl_sign($hash, $sig, $pkey, OPENSSL_ALGO_SHA256);
openssl_free_key($pkey);
$xSignature = base64_encode($sig);

$ch = curl_init("{$baseUrl}/pos_web/payment_phone/initiate");
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $body,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_SSL_VERIFYHOST => 2,
    CURLOPT_HTTPHEADER     => [
        "Content-Type: application/json",
        "Request-Name: pos_web/payment_phone/initiate",
        "Subject: {$terminalId}",
        "X-Signature: {$xSignature}"
    ]
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

// سجل المحاولة مع Guid
$stmt = $con->prepare(
    "UPDATE `mtn_payments`
     SET guid = :guid, status = 3, updated_at = NOW()
     WHERE invoice = :inv"
);
$stmt->execute([':guid'=>$guid, ':inv'=>$invoice]);

header('Content-Type: application/json');
http_response_code($httpCode);
echo $response;