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

$baseUrl       = rtrim(getenv('MTN_API_BASE_URL'), '/');
$terminalId    = getenv('MTN_TERMINAL_ID');
$privateKeyPem = getenv('MTN_PRIVATE_KEY');
$privateKey    = openssl_pkey_get_private(file_get_contents("private_key.pem"));
$invoice         = filterRequest('invoiceNumber');
$phone           = filterRequest('phone');
$guid            = filterRequest('guid');
$operationNumber = filterRequest('operationNumber');
$code            = filterRequest('otp');  // الـ OTP

error_log("MTN Confirm: Start request for invoice={$invoice}, phone={$phone}, guid={$guid}, opNum={$operationNumber}");

if (!$invoice || !$phone || !$guid || !$operationNumber || !$code) {
    error_log("MTN Confirm: Missing parameters");
    printFailure("Missing parameters.");
    exit;
}

// تشفير الكود
$hashBin  = hash('sha256', $code, true);
$codeB64  = base64_encode($hashBin);

$body = [
    'Invoice'         => intval($invoice),
    'Phone'           => $phone,
    'Guid'            => $guid,
    'OperationNumber' => intval($operationNumber),
    'Code'            => $codeB64
];
$bodyJson = trim(stripslashes(json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_LINE_TERMINATORS)), '"');

error_log("MTN Confirm: Prepared body JSON: " . $bodyJson);

// توليد التوقيع
$signResult = openssl_sign($bodyJson, $sig, $privateKey, OPENSSL_ALGO_SHA256);
if (!$signResult) {
    error_log("MTN Confirm: Failed to generate signature");
    printFailure("Signature error.");
    exit;
}
$xSignature = base64_encode($sig);
error_log("MTN Confirm: Generated signature");

// إرسال الطلب
$ch = curl_init("{$baseUrl}/pos_web/payment_phone/confirm");
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $bodyJson,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => [
        "Content-Type: application/json",
        "Request-Name: pos_web/payment_phone/confirm",
        "Subject: {$terminalId}",
        "X-Signature: {$xSignature}"
    ]
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);

error_log("MTN Confirm: HTTP $httpCode - Response: $response");
if ($curlError) {
    error_log("MTN Confirm: cURL error - $curlError");
}

// تحديث قاعدة البيانات في حال نجاح
if ($httpCode === 200) {
    try {
        $stmt = $con->prepare(
            "UPDATE `paymentsLogSyria` SET status = 1, updated_at = NOW()
             WHERE order_ref = :inv"
        );
        $stmt->execute([':inv' => $invoice]);
        error_log("MTN Confirm: Payment updated successfully in DB for invoice={$invoice}");
		
      	$stmt = $con->prepare("SELECT * FROM paymentsLogSyria WHERE order_ref = :order_ref LIMIT 1");
        $stmt->execute([':order_ref' => $invoice]);
        $payment = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($payment) {
            $userId = $payment['user_id'];
            $amount = $payment['amount'];
            $paymentMethod = $payment['payment_method'] ?? 'mtn';

            $finalAmount = calculateBonus($amount);
            $token = generatePaymentToken($userId, $finalAmount);
            $walletResult = addToPassengerWallet($userId, $finalAmount, $token);

            $siroToken = generatePaymentToken($userId, $amount);
            $siroWalletResult = addToSiroWallet($userId, $amount, $paymentMethod, $siroToken);
				
          printSuccess('MTN Confirm');
           
            exit;
        }
        
      
    } catch (PDOException $e) {
        error_log("MTN Confirm: DB update error - " . $e->getMessage());
    }
} else {
    error_log("MTN Confirm: Payment failed with HTTP code $httpCode");
}

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

function calculateBonus($amount) {
    if ($amount == 200000) return 205000;
    if ($amount == 400000) return 425000;
    if ($amount == 1000000) return 1040000;
    return $amount;
}

function generatePaymentToken($passengerId, $amount) {
    $url = BASE_URL . "/passengerWallet/addPaymentTokenPassenger.php";
    $postData = ['passengerId' => $passengerId, 'amount' => $amount];
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($httpCode != 200) return null;
    $data = json_decode($response, true);
    return $data['message'] ?? null;
}
function addToPassengerWallet($passengerId, $amount, $token) {
    $url = BASE_URL . "/passengerWallet/add.php";
    $postData = ['passenger_id' => $passengerId, 'balance' => $amount, 'token' => $token];
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($httpCode != 200) return null;
    return json_decode($response, true);
}

function addToSiroWallet($passengerId, $amount, $paymentMethod, $token) {
    $url = BASE_URL . "/siroWallet/add.php";
    $postData = [
        'amount' => $amount,
        'paymentMethod' => $paymentMethod,
        'passengerId' => $passengerId,
        'token' => $token,
        'driverId' => 'passenger'
    ];
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($httpCode != 200) return null;
    return json_decode($response, true);
}
?>