<?php
/**
 * QNBPay API Class - Production Ready
 * Location: /magaza/includes/QNBPay.php
 */

class QNBPay
{
    private $baseUrl;
    private $appId;
    private $appSecret;
    private $token;
    private $merchantKey;
    private $merchantId;

    public function __construct($appId, $appSecret, $merchantKey, $merchantId = '18330', $isTest = false)
    {
      // Banka dokümanına göre direkt CANLI linki sabitlendi
        $this->baseUrl = 'https://portal.qnbpay.com.tr'; 
        $this->appId = $appId;
        $this->appSecret = $appSecret;
        $this->merchantKey = $merchantKey;
        $this->merchantId = $merchantId;
    }

    // Token alma
    public function getToken()
    {
        $endpoint = '/ccpayment/api/token';
        $data = [
            'app_id' => $this->appId,
            'app_secret' => $this->appSecret
        ];

        $response = $this->makeRequest('POST', $endpoint, $data);
        if (isset($response['data']['token'])) {
            $this->token = $response['data']['token'];
            return $response['data']['token'];
        }
        return false;
    }

    // Taksit bilgisi sorgulama
    public function getInstallments($creditCard, $amount, $is_comission_from_user, $currencyCode = 'TRY')
    {
        $endpoint = '/ccpayment/api/getpos';
        $data = [
            'credit_card' => $creditCard,
            'amount' => $amount,
            'currency_code' => $currencyCode,
            'merchant_key' => $this->merchantKey,
            'is_comission_from_user' => $is_comission_from_user,
            'is_single_payment_allowed'=> true
        ];

        return $this->makeRequest('POST', $endpoint, $data, true);
    }

    public function paymentComplete($paymentData)
    {
        $endpoint = '/ccpayment/payment/complete';
        return $this->makeRequest('POST', $endpoint, $paymentData, true);
    }

    // 3D ödeme
    public function pay3D($paymentData)
    {
        $endpoint = '/ccpayment/api/paySmart3D';
        return $this->makeRequest('POST', $endpoint, $paymentData, true);
    }

    // Non-secure ödeme
    public function pay2D($paymentData)
    {
        $endpoint = '/ccpayment/api/paySmart2D';
        return $this->makeRequest('POST', $endpoint, $paymentData, true);
    }

    // Sipariş durumu sorgulama
    public function checkOrderStatus($data)
    {
        $endpoint = '/ccpayment/api/checkstatus';

        return $this->makeRequest('POST', $endpoint, $data, true);
    }

    // İade işlemi
    public function refund($data)
    {
        $endpoint = '/ccpayment/api/refund';

        return $this->makeRequest('POST', $endpoint, $data, true);
    }

    public function confirmPayment($data)
    {
        $endpoint = '/ccpayment/api/confirmPayment';
        return $this->makeRequest('POST', $endpoint, $data, true);
    }

    public function confirmPaymentMerchant($data)
    {
        $endpoint = '/ccpayment/payment/complete';
        return $this->makeRequest('POST', $endpoint, $data, true);
    }

    public function generateConfirmPaymentHashKey($merchant_key, $invoice_id, $status, $app_secret)
    {
        $data = $merchant_key . '|' . $invoice_id . '|' . $status;

        $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",
            null,
            $iv
        );
        $msg_encrypted_bundle = "$iv:$salt:$encrypted";
        $msg_encrypted_bundle = str_replace('/', '__', $msg_encrypted_bundle);
        return $msg_encrypted_bundle;
    }

    // Orijinal kodda yer alan yanlış yazımlı (Confrim) metod - Uyumluluk için korundu
    public function generateConfrimPaymentHashKey($merchant_key, $invoice_id, $order_id,  $status, $app_secret)
    {
        $data = $merchant_key . '|' . $invoice_id . '|' . $order_id . '|' . $status;

        $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",
            null,
            $iv
        );
        $msg_encrypted_bundle = "$iv:$salt:$encrypted";
        $msg_encrypted_bundle = str_replace('/', '__', $msg_encrypted_bundle);
        return $msg_encrypted_bundle;
    }

    public function generateHashKey(
        $total,
        $installment,
        $currency_code,
        $merchant_key,
        $invoice_id,
        $app_secret
    ) {
        $data = $total . '|' . $installment . '|' . $currency_code . '|' . $merchant_key . '|' . $invoice_id;

        $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, null, $iv);

        $msg_encrypted_bundle = "$iv:$salt:$encrypted";
        $msg_encrypted_bundle = str_replace('/', '__', $msg_encrypted_bundle);

        return $msg_encrypted_bundle;
    }

    public function generateConfirmPaymentMerchantHashKey($merchant_key, $invoice_id, $order_id,  $status, $app_secret)
    {
        $data = $merchant_key . '|' . $invoice_id . '|' . $order_id . '|' . $status; 
        $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",
            null,
            $iv
        );
        $msg_encrypted_bundle = "$iv:$salt:$encrypted";
        $msg_encrypted_bundle = str_replace('/', '__', $msg_encrypted_bundle);
        return $msg_encrypted_bundle;
    }

    public 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, null, $iv);

        $msg_encrypted_bundle = "$iv:$salt:$encrypted";
        $msg_encrypted_bundle = str_replace('/', '__', $msg_encrypted_bundle);

        return $msg_encrypted_bundle;
    }

    public function validateHashKey($hashKey, $secretKey)
    {
        $status = $currencyCode = "";
        $total = $invoiceId = $orderId = 0;

        if (!empty($hashKey)) {
            $hashKey = str_replace('__', '/', $hashKey);
            $password = sha1($secretKey);

            $components = explode(':', $hashKey);
            if (count($components) > 2) {
                $iv = isset($components[0]) ? $components[0] : "";
                $salt = isset($components[1]) ? $components[1] : "";
                $salt = hash('sha256', $password . $salt);
                $encryptedMsg = isset($components[2]) ? $components[2] : "";

                $decryptedMsg = openssl_decrypt($encryptedMsg, 'aes-256-cbc', $salt, null, $iv);

                if (strpos($decryptedMsg, '|') !== false) {
                    $array = explode('|', $decryptedMsg);
                    $status = isset($array[0]) ? $array[0] : 0;
                    $total = isset($array[1]) ? $array[1] : 0;
                    $invoiceId = isset($array[2]) ? $array[2] : '0';
                    $orderId = isset($array[3]) ? $array[3] : 0;
                    $currencyCode = isset($array[4]) ? $array[4] : '';
                }
            }
        }

        return [$status, $total, $invoiceId, $orderId, $currencyCode];
    }

    // HTTP istek yapma
    private function makeRequest($method, $endpoint, $data, $requiresToken = false)
    {
        $url = $this->baseUrl . $endpoint;
        $headers = ['Accept: application/json'];

        if ($requiresToken) {
            if (!$this->token) {
                $this->getToken();
            }
            $headers[] = 'Authorization: Bearer ' . $this->token;
        }
        $headers[] = 'Content-Type: application/json';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        
        if ($method === 'POST') {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        // 3D Secure yönlendirme formunu ekrana basar
        if ($endpoint == '/ccpayment/api/paySmart3D') {
            if (empty($response)) {
                die("Bankadan yanit donmedi. Lutfen API anahtarlarinizi ve portal adresini kontrol edin.");
            }
            echo $response;
            die;
        }
        return json_decode($response, true);
    }
}