<?php

namespace App\Danoral\Bancos\MercantilAPI;

use App\Danoral\Bancos\MercantilAPI\AesCipher;
use Illuminate\Support\Facades\Http;

class MercantilAPI
{

    static function search($datos) {

        # movil empresa
        $origin_mobile_number       = mb_convert_encoding(env('MERCANTIL_API_ORIGIN_MOBILE_NUMBER'), "UTF-8"); 

        # movil cliente
        $destination_mobile_number  = mb_convert_encoding($datos['destination_mobile_number'], "UTF-8");
        # monto compra
        $amount                     = $datos['amount'];
        # referencia de pago
        $payment_reference          = $datos['payment_reference'];
        # trx_date
        $trx_date                   = $datos['trx_date'];


        # Generacion del hash a partir de la clave secreta del banco
        $keyhash = AesCipher::createKeyhash(mb_convert_encoding(env('MERCANTIL_API_KEYBANK'), "UTF-8"));

        $bodyAPI = [
            "merchant_identify" => [
                "integratorId"      => 1,
                "merchantId"        => env('MERCANTIL_API_MERCHANT_ID'),
                "terminalId"        => "1"
            ],  
            "client_identify"   => [
                "ipaddress"         => "10.0.0.1",
                "browser_agent"     => "Chrome 18.1.3",
                "mobile"            => [
                    "manufacturer"      => "Samsung",
                    "model"             => "S9",
                    "os_version"        => "Oreo 9.1",
                    "location"          => [
                        "lat"               => 0,
                        "lng"               => 0
                    ]
                ]
            ],
            "search_by"         => [
                "amount"                    => $amount,
                "currency"                  => "VES",
                "origin_mobile_number"      => AesCipher::encrypt($keyhash, $origin_mobile_number),
                "destination_mobile_number" => AesCipher::encrypt($keyhash, $destination_mobile_number),
                "payment_reference"         => $payment_reference,
                "trx_date"                  => $trx_date
            ]
        
        ];

        print_r($bodyAPI);

        $response = Http::withHeaders([
            'Content-Type'      => 'application/json',
            'X-IBM-Client-Id'   => env('MERCANTIL_API_X_IBM_Client_Id'),
        ])
        ->post(env('MERCANTIL_API_URL').'mobile-payment/search', $bodyAPI);

        echo "respuesta: " . $response->status() . PHP_EOL;
        echo PHP_EOL;


        $res = $response->json();
        
        print_r($res);

        if($response->ok()){
            echo "200  | OK" . PHP_EOL;
        }



    }

    static function c2p_compra($datos) {        
        /*
        MercantilAPI::c2p_compra([
            "destination_mobile_number" => '584241513063',   # movil cliente
            "destination_id"            => 'V18367443',      # cedula cliente
            "destination_bank_id"       => '0105',           # banco cliente
            "twofactor_auth"            => '00001111',       # clave temporal
            "amount"                    => 100.00,           # monto compra
            "invoice_number"            => '12345678',       # numero factura ref   
        ]);
        */

        # movil empresa
        $origin_mobile_number       = mb_convert_encoding(env('MERCANTIL_API_ORIGIN_MOBILE_NUMBER'), "UTF-8"); 

        # movil cliente
        $destination_mobile_number  = mb_convert_encoding($datos['destination_mobile_number'], "UTF-8");
        # cedula cliente
        $destination_id             = mb_convert_encoding($datos['destination_id'], "UTF-8");
        # banco cliente
        $destination_bank_id        = $datos['destination_bank_id'];
        # clave temporal
        $twofactor_auth             = mb_convert_encoding($datos['twofactor_auth'], "UTF-8");
        # monto compra
        $amount                     = $datos['amount'];
        # nro factura
        $invoice_number             = $datos['invoice_number'];

        # Generacion del hash a partir de la clave secreta del banco
        $keyhash = AesCipher::createKeyhash(mb_convert_encoding(env('MERCANTIL_API_KEYBANK'), "UTF-8"));

        $bodyAPI = [
            "merchant_identify" => [
                "integratorId"      => 1,
                "merchantId"        => env('MERCANTIL_API_MERCHANT_ID'),
                "terminalId"        => "1"
            ],  
            "client_identify"   => [
                "ipaddress"         => "10.0.0.1",
                "browser_agent"     => "Chrome 18.1.3",
                "mobile"            => [
                    "manufacturer"      => "Samsung",
                    "model"             => "S9",
                    "os_version"        => "Oreo 9.1",
                    "location"          => [
                        "lat"               => 0,
                        "lng"               => 0
                    ]
                ]
            ],
            "transaction_c2p"   => [
                "trx_type"                  => "compra",
                "payment_method"            => "c2p",
                "destination_id"            => AesCipher::encrypt($keyhash, $destination_id),
                "invoice_number"            => $invoice_number,
                "currency"                  => "VES",
                "amount"                    => $amount,
                "destination_bank_id"       => $destination_bank_id,
                "destination_mobile_number" => AesCipher::encrypt($keyhash, $destination_mobile_number),
                "payment_reference"         => "",
                "origin_mobile_number"      => AesCipher::encrypt($keyhash, $origin_mobile_number),
                "twofactor_auth"            => AesCipher::encrypt($keyhash, $twofactor_auth)
            ]            
        ];

        //print_r($bodyAPI);

        $response = Http::withHeaders([
            'Content-Type'      => 'application/json',
            'X-IBM-Client-Id'   => env('MERCANTIL_API_X_IBM_Client_Id'),
        ])
        ->post(env('MERCANTIL_API_URL').'payment/c2p', $bodyAPI);

        echo "respuesta: " . $response->status() . PHP_EOL;
        echo PHP_EOL;


        $res = $response->json();
        
        print_r($res);

        

        if($response->ok()){
            echo "date | ". $res['transaction_c2p_response']['processing_date'] . PHP_EOL;
            echo "200  | OK" . PHP_EOL;
            echo "ref  | ". $res['transaction_c2p_response']['payment_reference'] . PHP_EOL;
            echo "fee  | ". $res['transaction_c2p_response']['service_fee'] . PHP_EOL;
            echo "auth | ". $res['transaction_c2p_response']['authorization_code'] . PHP_EOL;
        }

        if($response->badRequest()){
            echo "date | ". $res['processing_date'] . PHP_EOL;
            echo "400  | Bad Request" . PHP_EOL;            

            foreach($res['error_list'] as $err){
                echo $err['error_code'] ." | ". $err['description'] . PHP_EOL;
            }
        }

        if($response->unauthorized()){
            echo "date | ". $res['processing_date'] . PHP_EOL;
            echo "401  | Unauthorized" . PHP_EOL;    
            
            foreach($res['error_list'] as $err){
                echo $err['error_code'] ." | ". $err['description'] . PHP_EOL;
            }
        }


    }



     /**
     *  
     * Ejemplo para cifrar y descifrar datos intercambios 
     * pos los API de Mercantil Banco 
     * 
     *
    */
    static function test() {
        
        echo "Genera del CVV y la clave telefonica cifrada\n";
                
        # Clave secreta enviada por el Banco
        $keybank                = mb_convert_encoding("A11103402525120190822HB01", "UTF-8");
        # Generacion del hash a partir de la clave secreta del banco
        $keyhash                = AesCipher::createKeyhash($keybank);

        # CVV
        $cvv                    = mb_convert_encoding("752", "UTF-8");
        $cvv_encrypt            = AesCipher::encrypt($keyhash, $cvv);
        
        # Movil
        $movilOrigen_encrypt    = AesCipher::encrypt($keyhash, mb_convert_encoding("584148508980", "UTF-8"));
        $movilDestino_encrypt   = AesCipher::encrypt($keyhash, mb_convert_encoding("584241513063", "UTF-8"));

        # Cedula 
        $cedula_encrypt         = AesCipher::encrypt($keyhash, mb_convert_encoding("V18367443", "UTF-8"));

        # Clave de Compra
        $claveCompra_encrypt    = AesCipher::encrypt($keyhash, mb_convert_encoding("00001111", "UTF-8"));
              
        # Des-Encripta
        $decrypted = AesCipher::decrypt($keyhash, $cvv_encrypt);
        
        echo "CVV utilizado         : $cvv" . PHP_EOL;
        echo "CVV Encriptado        : $cvv_encrypt" . PHP_EOL;
        echo "CVV Des-Encriptado    : $decrypted" . PHP_EOL;
        echo PHP_EOL;
        echo "Movil Origen encrypt  : $movilOrigen_encrypt" . PHP_EOL;
        echo "Movil Destino encrypt : $movilDestino_encrypt" . PHP_EOL;
        echo "Cedula encrypt        : $cedula_encrypt" . PHP_EOL;
        echo "Clave encrypt         : $claveCompra_encrypt" . PHP_EOL;
        
    }


}