<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Str;


class GS extends Model
{
    use HasFactory;
    public $timestamps = false;
    //protected $table = 'settings';
    //protected $primarykey = 'id';

static function HttpGet($url)
    {
        $ch = curl_init();
        $timeout = 10;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/0 (Windows; U; Windows NT 0; zh-CN; rv:3)");
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $file_contents = curl_exec($ch);
        curl_close($ch);
        return $file_contents;
    }

static function checkout( $order_no, $amount, $mid, $app_key, $app_secret ) {

        $error_message = '';

        //creating order request
        $order_id = $order_no;//helper::randomString( 3 ) . str_pad( $order_no, 14, "0", STR_PAD_LEFT );
        $requestData = compact('order_id', 'mid', 'app_key', 'app_secret');
        $response = GS::checkout_initialize($order_id, $mid, $app_key, $app_secret );

        if ( isset( $response['sensitiveData'] ) && isset( $response['signature'] ) ) {
            if ( $response['sensitiveData'] != "" && $response['signature'] != "" ) {

              $decrypted_response = json_decode( GS::decryptDataWithPrivateKey( $response['sensitiveData'], $app_secret ), true );
              $payment_reference_id = $decrypted_response['paymentReferenceId'];

                //execute order request
                $execute = GS::checkout_complete( $response['sensitiveData'], $order_id, $amount, $order_no, $mid, $app_key, $app_secret );
                if ( $execute ) {

                    if (array_key_exists('status', $execute) && $execute['status'] == "Success" ) {
                        $url = json_encode($execute['callBackUrl'] );

                        return [ 'status' => 'success', 'url' => ( $url ), 'pid'=> $payment_reference_id ];
                        // echo "<script>window.open($url, '_self')</script>";
                    } else {
                        $error_message = "execute fail: " . $execute['message'];
                    }
                }
            }
        } else {
        $error_message = isset($response['message']) ? $response['message'] : 'Nagad server issue.';

        $server_ip = isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : 'Unknown';
        $data = [
            'status' => 'fail',
            'message' => $error_message,
            'response' => $response,
            'ip' => $server_ip
        ];

        $json_data = json_encode($data);

        DB::table('nagadError')->insertOrIgnore(['req' => json_encode($requestData), 'res' => $json_data]);

        return ['status' => 'fail', 'message' => $error_message];

}

    }

static function checkout_complete( $sensitive_data, $order_id, $amount, $original_order_no, $mid, $app_key, $app_secret ) {

      //  $lib = DB::table('p2c_credential')->where('id',2)->first(); 

        $decrypted_response = json_decode( GS::decryptDataWithPrivateKey( $sensitive_data,$app_secret ), true );

        if ( isset( $decrypted_response['paymentReferenceId'] ) && isset( $decrypted_response['challenge'] ) ) {
            $payment_reference_id = $decrypted_response['paymentReferenceId'];
$fee ="0.00";
            $serviceFee = [
                "serviceFee" => $fee,//self::gatewayOption('service_fee'),
                "additionalCharge" => '0.00'//self::gatewayOption('additional_charge'),
            ];

            $order_sensitive_data = [
                'merchantId'   => $mid,
                'orderId'      => $order_id,
                'currencyCode' => '050',
                'amount'       => $amount,
                'challenge'    => $decrypted_response['challenge'],
                'otherAmount'  => $serviceFee,
            ];

            $order_post_data = [
                'sensitiveData'          => GS::encryptDataWithPublicKey( $order_sensitive_data,$app_key ),
                'signature'              => GS::generateSignature( $order_sensitive_data,$app_secret ),
                'merchantCallbackURL'    => 'https://zzamankanak.com/redirect.php',
                'additionalMerchantInfo' =>  [
                    'order_no' => $original_order_no,
                    'serviceLogoURL' => 'https://payment.mynagad.com:30000/img/cart.png',
                    'additionalFieldNameEN' => '',
                    'additionalFieldNameBN' => '',
                    'additionalFieldValue'  => ''
                ],
            ];

            $checkout_complete_api  = "https://api.mynagad.com/api/dfs/check-out/complete/".$payment_reference_id;

           // $response = http_request( $url, $order_post_data );
$response = GS::HttpPostMethod($checkout_complete_api, $order_post_data );
return $response;

        }

        return false;
    }



static function checkout_initialize( $order_id, $mid, $app_key, $app_secret ) {
  date_default_timezone_set('Asia/Dhaka');
//$lib = DB::table('p2c_credential')->where('id',2)->first();  
 // $mid=$lib->mid;


        $sensitive_data = [
            'merchantId' => $mid,
            'datetime'   => date('YmdHis',time()),
            'orderId'    => $order_id,
            'challenge'  => GS::randomString(),
        ];

        $checkout_init_data = [
            'dateTime'      => date('YmdHis',time()),
            'sensitiveData' => GS::encryptDataWithPublicKey( $sensitive_data,$app_key ),
            'signature'     => GS::generateSignature( $sensitive_data,$app_secret ),
        ];

        $language = 'EN';

   $checkout_initialize_api  = "https://api.mynagad.com/api/dfs/check-out/initialize/$mid/".$order_id. "?locale=" . $language;


       // $response = http_request( $url, $checkout_init_data );

        //return $response;
$response = GS::HttpPostMethod($checkout_initialize_api, $checkout_init_data );
return $response;
    }


static function randomString( $length = 40 ) {
        $characters        = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $characters_length = strlen( $characters );
        $random_string     = '';

        for ( $i = 0; $i < $length; $i ++ ) {
            $random_string .= $characters[ rand( 0, $characters_length - 1 ) ];
        }

        return $random_string;
    }

static function encryptDataWithPublicKey( $data,$app_key) {
        if ( gettype( $data ) == 'array' ) {
            $data = json_encode( $data );
        }

           // $lib = DB::table('p2c_credential')->where('id',2)->first(); 

        $pgw_public_key = $app_key;
        $public_key     = "-----BEGIN PUBLIC KEY-----\n" . $pgw_public_key . "\n-----END PUBLIC KEY-----";
        $key_resource   = openssl_get_publickey( $public_key );

        openssl_public_encrypt( $data, $crypttext, $key_resource );

        return base64_encode( $crypttext );
    }

static function generateSignature( $data,$app_secret ) {
        if ( gettype( $data ) == 'array' ) {
            $data = json_encode( $data );
        }

            //$lib = DB::table('p2c_credential')->where('id',2)->first(); 

        $merchant_private_key = $app_secret;
        $private_key = "-----BEGIN RSA PRIVATE KEY-----\n" . $merchant_private_key . "\n-----END RSA PRIVATE KEY-----";
        openssl_sign( $data, $signature, $private_key, OPENSSL_ALGO_SHA256 );

        return base64_encode( $signature );
    }

static function decryptDataWithPrivateKey( $crypt_text,$app_secret ) {
       //  $lib = DB::table('p2c_credential')->where('id',2)->first();  
      $merchant_private_key = $app_secret;

        $private_key = "-----BEGIN RSA PRIVATE KEY-----\n" . $merchant_private_key . "\n-----END RSA PRIVATE KEY-----";

        openssl_private_decrypt( base64_decode( $crypt_text ), $plain_text, $private_key );

        return $plain_text;
    }
 public function getCurrentBDtime( $format = "YmdHis", $timezone = "Asia/Dhaka" ) {

        $timezone = new DateTimeZone( $timezone );
        $datetime = new DateTime( 'now', $timezone );

        return $datetime->format( $format );
    }

function http_request( $url, $data ) {
        $args = [
            'body'        => json_encode( $data ),
            'timeout'     => '30',
            'redirection' => '30',
            'httpversion' => '1.0',
            'blocking'    => true,
            'headers'     => get_header(),
            'cookies'     => [],
        ];


       // $response = file_get_contents( $url , $args ); // HTTP request using POST method
        $response = wp_remote_post( esc_url_raw( $url ), $args ); // HTTP request using POST method
        $response = wp_remote_retrieve_body( $response ); //retrieve only the body from the raw response

        if ( strpos( $response, 'Your support ID is:' ) ) {
            return [ 'message' => $response ];
        }

        return json_decode( $response, true );
    }

function get_header() {
        $headers = [
            'Content-Type'     => 'application/json',
            'X-KM-Api-Version' => 'v-0.2.0',
            'X-KM-IP-V4'       => GS::get_client_ip(),
            'X-KM-Client-Type' => 'PC_WEB',
        ];


        return $headers;
    }

static function get_client_ip() {
        $ipaddress = '';

        $keys = [
            'HTTP_CLIENT_IP',
            'HTTP_X_FORWARDED_FOR',
            'HTTP_X_FORWARDED',
            'HTTP_FORWARDED_FOR',
            'HTTP_FORWARDED',
            'REMOTE_ADDR',
        ];

        foreach ( $keys as $key ) {
            if ( isset( $_SERVER[ $key ] ) ) {
                $ipaddress = $_SERVER[ $key ];
                break;
            }
        }

        $ipaddress = $ipaddress ? $ipaddress : 'UNKNOWN';

        return $ipaddress;
    }

static function HttpPostMethod($PostURL, $PostData)
    {

        $url = curl_init($PostURL);
        $postToken = json_encode($PostData);
        $header = array(
            'Content-Type:application/json',
            'X-KM-Api-Version:v-0.2.0',
            'X-KM-IP-V4:' . GS::get_client_ip(),
            'X-KM-Client-Type:PC_WEB'
        );

        curl_setopt($url, CURLOPT_HTTPHEADER, $header);
        curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($url, CURLOPT_POSTFIELDS, $postToken);
        curl_setopt($url, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($url, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($url, CURLOPT_SSL_VERIFYPEER, 0);
        $resultData = curl_exec($url);
        $curl_error = curl_error($url);

        if (!empty($curl_error)) {
            return [
                'error' => $curl_error
            ];
        } else {
            $response = json_decode($resultData, true, 512);
            curl_close($url);
            return $response;
        }

    }

}
