<?php

require 'vendor/autoload.php'; //composer packages (guzzle)

    use GuzzleHttp\Client;
    use GuzzleHttp\Psr7\Request;
    
    
    $bd = $_GET['bd'];
    
    $id_cliente = $_GET['id_cliente'];
    
    $id_servicio = $_GET['plan'];
    
    $plan = $_GET['plan'];
    
    $importe = $_GET['importe'];
    
    $nombre = $_GET['nombre'];
    
    $apellido = $_GET['apellido'];
    
    $fechaN = $_GET['fechaN'];
    
    $email = $_GET['email'];
    
    $tel = $_GET['telefono'];
    
    $domi = $_GET['domi'];
    
    $col = $_GET['colonia'];
    
    $cp = $_GET['cp'];
    
    $genero = $_GET['genero'];
    
    $fechaR = $_GET['fechaR'];
    
    $sucursal = $_GET['sucursal'];
    
    $qr = $_GET['qr'];
    
    $numero_card = $_GET['credicard'];
    
    $cvv = $_GET['cvv'];
    
    $dateExp = $_GET['dateExp'];
    
    $expiry = explode("/", $dateExp);
    
    if (!is_object($result))
        $result = new stdClass;
    date_default_timezone_set('America/Mexico_City');
    // get data from ajax request

    //BUILD TRANSACTION 4931580001642617 4035874000424977
    //aqui se cambia la tarjeta
    //echo sizeof($card_number),' - ',$obj->numbercard;

        
        $send_ruta = 'payments';
        $transaction = ["paymentMethod"=>[
        "paymentCard"=>[
                "number"=>$numero_card,
                "securityCode"=>$cvv,
                "expiryDate"=>[
                    "month" => $expiry[0],
                    "year" => $expiry[1]
                ]
            ]
        ],
        "transactionAmount" =>["total"=>$importe,"currency"=>"MXN"],
        "requestType"=>"PaymentCardSaleTransaction",
        "authenticationRequest" => [
            "authenticationType" => "Secure3D21AuthenticationRequest",
            "termURL" => "https://directoriofitness.com.mx/estaciones/Progymcloud_app/php/firstdata/notificacion.php",
            "methodNotificationURL" => "https://directoriofitness.com.mx/estaciones/Progymcloud_app/php/firstdata/notificacion.php",
            "challengeIndicator" => "03"
        ]];
    
    
    
    //SERIALIZE TO JSON
    $data_string = json_encode($transaction);
    //GET VALUES FOR HEADERS AND SIGNATURE
    
        
    $API_KEY = 'npfhBnGhAAlExcxkG4PWmt6Dok6kPjjz';
    $uuid = sprintf(
            '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0x0fff) | 0x4000,
            mt_rand(0, 0x3fff) | 0x8000,
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff)
        );
    $timestamp = round(microtime(true) * 1000);
    
    $msg = 'npfhBnGhAAlExcxkG4PWmt6Dok6kPjjz'. $uuid . $timestamp . $data_string;
        
    $hmac = hash_hmac('sha256', $msg, 'JPVzTCmmocqGDTGT');
    $messageSignature = base64_encode($hmac);
    $msg_signature = $messageSignature;
    //echo "uuid ".$uuid;
    //echo "msg_signature ".$msg_signature;
    //API URL
    $url = "https://cert.api.firstdata.com/gateway/v2/";

    //PREPARE REQUEST
    $client = new Client([
        'base_uri' => $url,
        'timeout' => $timestamp,
        'headers' => ['Content-Type' => 'application/json', 'Accept' => 'application/json'],
        'http_errors' => false
    ]);
    $headers = [
        'Api-Key' => $API_KEY,
        'Client-Request-Id' => $uuid,
        'Timestamp' => $timestamp,
        'Message-Signature' => $msg_signature
    ];

    try {

        //SEND REQUEST
        $request = new Request('POST', $send_ruta, $headers, $data_string);
        $response = $client->send($request);
        http_response_code($response->getStatusCode());
        $result = json_decode($response->getBody()->getContents());
        json_encode($result);
        //$transationid = $result;
   
    } catch (Exception $e) {
        http_response_code(503);
        //HANDLE GUZZLE EXCEPTION 
        //FOR EXAMPLE: SERVER IMPOSSIBLE TO REACH DUE CONNECTION ERRORS
    }
    
    
    
        $TemUrl;
         $transationid = $result->ipgTransactionId;
        //localStorage.setItem('id', '888888'); 
        //return response to ajax request ipgTransactionId
        //header('Location: https://directoriofitness.com.mx/estaciones/Progymcloud_app/php/firstdata/getparams.php?PaReq='.$result->authenticationResponse->params->payerAuthenticationRequest.'&TermUrl='.$result->authenticationResponse->params->termURL.'&MD='.$result->authenticationResponse->params->merchantData.'&url='.$result->authenticationResponse->params->acsURL);
        $url_3d = $result->authenticationResponse->params->acsURL;
        $PaReq = $result->authenticationResponse->params->payerAuthenticationRequest;
       
        $TemUrl = "https://directoriofitness.com.mx/estaciones/Progymcloud_app/php/firstdata/notificacion.php".'?bd='.$bd.'&id_cliente='.$id_cliente.'&plan='.$plan.'&importe='
        .$importe.'&nombre='.$nombre.'&apellido='.$apellido.'&fechaN='.$fechaN.'&email='.$email.'&telefono='.$tel.'&domi='.$domi
        .'&colonia='.$col.'&cp='.$cp.'&genero='.$genero.'&fechaR='.$fechaR.'&sucursal='.$sucursal.'&qr='.$qr;
        
        
        $MD = $result->authenticationResponse->params->merchantData;
    
        /*echo "
        <html>
            <body onload='document.myform.submit();'>
                <form action=$url_3d method='POST' id='myform' name='myform'>
                    <input type='hidden' name='PaReq' value=$PaReq>
                    <input type='hidden' name='TermUrl' value=$TemUrl>
                    <input type='hidden' name='MD' value=$MD>
                    
               </form>
           </body>
       </html>";*/
    ?>
    
    <html>
            <body onload='document.myform.submit();'>
                <form action='<?= $url_3d ?>' method='POST' id='myform' name='myform'>
                    <input type='hidden' name='PaReq' value='<?= $PaReq ?>'>
                    <input type='hidden' name='TermUrl' value='<?= $TemUrl ?>'>
                    <input type='hidden' name='MD' value='<?= $MD ?>'>
                    
               </form>
           </body>
       </html>
    