<?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);
    
    $API_KEY; //'npfhBnGhAAlExcxkG4PWmt6Dok6kPjjz';
    $API_SECRET; //JPVzTCmmocqGDTGT
    
    $conn = new mysqli("directoriofitness.com.mx","direct18","L4LL4v3M@3str@",'direct18_ProGymCloud');
    $queryApi = "SELECT info_firstdata.*, info_plataformaspago.activar_firstdata 
                    FROM info_firstdata 
                INNER JOIN gimnasios ON info_firstdata.gimnasio_idGimnasio = gimnasios.idGimnasio 
                INNER JOIN info_plataformaspago ON info_plataformaspago.gimnasio_idGimnasio = gimnasios.idGimnasio 
                WHERE gimnasios.BaseDatos = '$bd' AND info_firstdata.sucursal_idSucursal = '$sucursal'";
    
    $resultApi = $conn->query($queryApi);
    
    if ($resultApi->num_rows > 0){
        $row = $resultApi->fetch_assoc();
    
        $API_KEY = $row['api_key'];
        $API_SECRET = $row['secret_key'];
    }else{
        $bandApi = FALSE;
    }
    
    $conn->close();
    
    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/progymcloud_app/pagos/firstdata/notificacion.php",
            "methodNotificationURL" => "https://directoriofitness.com.mx/progymcloud_app/pagos/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 = $API_KEY. $uuid . $timestamp . $data_string;
        
    $hmac = hash_hmac('sha256', $msg, $API_SECRET);
    $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());
        echo json_encode($result);
        
        $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/progymcloud_app/pagos/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; 
        //$transationid = $result; ?>
        
        <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>
   
   <?php } catch (Exception $e) {
        http_response_code(503); 
        //echo $e;
        //HANDLE GUZZLE EXCEPTION 
        //FOR EXAMPLE: SERVER IMPOSSIBLE TO REACH DUE CONNECTION ERRORS
        ?>
        
        <html>
            
            <body>
                <div>
                    <h3>Ocurrio un error en tu transacción</h3>
                    <h3>Datos Incorrectos</h3>
                </div>
                
            </body>
        </html>
        
        
   <?php }
    
    
    
        
        
        //echo json_encode($result);
        /*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>";*/
    ?>
    
        
    