<?php
    header('Content-type: application/json; charset=utf-8');
    $path = "../../../../../";
    include("".$path."deppo/tools/script/cevir.php");
    $path2 = "config/"; include("".$path."config/map.php");
    include("".$path."deppo/tools/script/fonksiyon".$ver.".php");
    ## API Entegrasyon Bilgileri
    $app_id = tanim("pay+qnbpay","n1",0);
    $app_secret = tanim("pay+qnbpay","n2",0);
    $merchant_key = tanim("pay+qnbpay","n3",0);
    ## POST Verileri
    $invoice_id = $_POST["transid"];
    $amount = $_POST["Total"] ?? "0"; // Boş veya 0 girilirse tüm tutar iade edilir
    ## 1. ADIM: QNBPay'den Token Al
    $token_url = "https://portal.qnbpay.com.tr/ccpayment/api/token";
    $token_data = json_encode(["app_id" => $app_id, "app_secret" => $app_secret]);
    $ch = curl_init($token_url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $token_data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $token_response = json_decode(curl_exec($ch), true);
    curl_close($ch);
    if (!isset($token_response["data"]["token"])) {
        die(json_encode(["error" => "Token alınamadı", "details" => $token_response]));
    }
    $token = $token_response["data"]["token"];
    ## 2. ADIM: Hash Key Oluştur
    function generateRefundHashKey($amount, $invoice_id, $merchant_key, $app_secret) {
        $data = $amount . '|' . $invoice_id . '|' . $merchant_key;
        $iv = substr(sha1(mt_rand()), 0, 16);
        $password = sha1($app_secret);
        $salt = substr(sha1(mt_rand()), 0, 4);
        $saltWithPassword = hash('sha256', $password . $salt);
        $encrypted = openssl_encrypt("$data", 'aes-256-cbc', "$saltWithPassword", 0, $iv);
        $msg_encrypted_bundle = "$iv:$salt:$encrypted";
        return str_replace('/', '__', $msg_encrypted_bundle);
    }
    $hash_key = generateRefundHashKey($amount, $invoice_id, $merchant_key, $app_secret);
    ## 3. ADIM: İade İsteği Gönder
    $refund_url = "https://portal.qnbpay.com.tr/ccpayment/api/refund";
    $refund_data = json_encode([
        "invoice_id"   => $invoice_id,
        "merchant_key" => $merchant_key,
        "amount"       => $amount,
        "hash_key"     => $hash_key
    ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    $ch = curl_init($refund_url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer $token",
        "Content-Type: application/json"
    ]);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $refund_data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $refund_response = curl_exec($ch);
    curl_close($ch);
    $refund_result = json_decode($refund_response, true);
    print_r($refund_response);
?>