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

    use GuzzleHttp\Client;
    use GuzzleHttp\Psr7\Request;
    
   $mensaje_final;
    $idT = $_GET['idT'];
    $PaReq = $_POST['PaRes'];
    $MD = $_POST['MD'];
    
        $bd = str_replace('_', ' ', $_GET['bd']);
        $id_cliente = "0";
        $id_servicio = str_replace('_', ' ', $_GET['plan']);
        $plan = str_replace('_', ' ', $_GET['plan']);
        $importe = str_replace('_', ' ', $_GET['importe']);
        $nombre = str_replace('_', ' ', $_GET['nombre']);
        $apellido = str_replace('_', ' ', $_GET['apellido']);
        $fechaN = str_replace('_', ' ', $_GET['fechaN']);
        $email = str_replace('_', ' ', $_GET['email']);
        $tel = str_replace('_', ' ', $_GET['telefono']);
        $domi = str_replace('_', ' ', $_GET['domi']);
        $col = str_replace('_', ' ', $_GET['colonia']);
        $cp = str_replace('_', ' ', $_GET['cp']);
        $genero = str_replace('_', ' ', $_GET['genero']);
        $fechaR = str_replace('_', ' ', $_GET['fechaR']);
        $sucursal = str_replace('_', ' ', $_GET['sucursal']);
        $qr = str_replace('_', ' ', $_GET['qr']);
        $msg;
         $API_KEY;
        $API_SECRET;
        $bdC = "direct18_".$bd;
        
        $bandApi = TRUE;
        $msg;
    
    
    
    $result = '';
    if (!is_object($result))
        $result = new stdClass;
    date_default_timezone_set('America/Mexico_City');
    // get data from ajax request
    $received = json_decode(file_get_contents('php://input'),true);

    //BUILD TRANSACTION 4931580001642617 4035874000424977
    //aqui se cambia la tarjeta
    $payload = [
        "authenticationType" =>"Secure3D10AuthenticationUpdateRequest",
          "merchantData" => $MD,
          "payerAuthenticationResponse" => $PaReq
        ];
    
    //SERIALIZE TO JSON
    $data_string = json_encode($payload);
    //GET VALUES FOR HEADERS AND SIGNATURE
    
    //OBTENEMOS LAS LLAVES
    $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($bandApi == FALSE){
        
        //colocal mensaje fallido
        exit();
        
    }
    
        
    //$API_KEY = 'npfhBnGhAAlExcxkG4PWmt6Dok6kPjjz';
    //$API_SECRET = 'JPVzTCmmocqGDTGT';
    $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,
        'transaction-id' => $idT
    ];
    
    try {
        
        //SEND REQUEST
        $request = new Request('PATCH', 'payments/'.$idT, $headers, $data_string);
        $response = $client->send($request);
        http_response_code($response->getStatusCode());
        $result = json_decode($response->getBody()->getContents());
        
        $conn = new mysqli("directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$bdC);
        
        $id_insert;
                $query_socio = "INSERT INTO socio_servicio(idServicio,idSocio,idSocioTitular,FechaSolicitud,FechaInscripcion) 
                VALUES('$id_servicio','$id_cliente','$id_cliente',CURDATE(),CURDATE())";
                
                if($conn->query($query_socio) === TRUE){
                    $q_select = "SELECT MAX(idSocio_Servicio) AS idInsert FROM socio_servicio WHERE idSocioTitular = '$id_cliente'";
    
                    $result = $conn->query($q_select);
    
                    $row = $result->fetch_assoc();
    
                    $id_insert = $row['idInsert'];
                    
                    $fecha_vencimiento = "DATE_ADD( '$fechaR', INTERVAL 1 DAY)";
                    
                    $query_pagos ="INSERT INTO pagos (idSocio_Servicio,Concepto,FechaPago,Importe,idUsuario,Pago,Descuento,Subtotal,
                    FechaInicio,Forma1,Importe1,Forma2,Importe2,idSucursal,Visible,FechaFin,Cancelado) 
                    VALUES ($id_insert,'00',NOW(),$importe,2,2,0.00,$importe,CURDATE(),'firstdata',0.00,'firstdata',0.00,$sucursal,0,$fecha_vencimiento,0)";
                    
                    
                    //$conn->insert_query($query_pagos,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$bd);
                    
                    if($conn->query($query_pagos) === TRUE){
                        $query = "INSERT INTO prospectos (nombre_prospecto,apll_prospecto,fecha_nacimiento,genero,correo_prospecto,telefono_prospecto,
                        domicilio_prospecto,colonia_prospecto,cp_prospecto,notas_prospecto,fecha_registro,estatus_prospecto,qr) 
                        VALUES ('$nombre','$apellido','$fechaN',$genero,'$email','$tel',
                        '$domi','$col','$cp','visita',NOW(),6,'$qr')";
                        
                        $conn->query($query);
                        if($conn->query($query) === TRUE){
                            $msg = 'Pago Exitoso';
                        }else{
                            $msg ='Error al guardar tu pago, checa en la administracion <br> ID Pago: '.$payment_id;
                        }
                    }else{
                        $msg ='Error al guardar tu pago, checa en la administracion <br> ID Pago: '.$payment_id;
                    }
                
                }else{
                    $msg ='Error al guardar tu pago, checa en la administracion <br> ID Pago: '.$payment_id;
                }
        
        $conn->close();
    }catch (Exception $e) {
        $msg = 'Error al procesar la transacción '.$e;
        http_response_code(503);
        //HANDLE GUZZLE EXCEPTION 
        //FOR EXAMPLE: SERVER IMPOSSIBLE TO REACH DUE CONNECTION ERRORS
    } 

?>

    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" />
        <title>First Data 3D Secure</title>
    </head>
    <style>
        .padre {
    
        padding: 0 1rem;
        margin: 1rem;
        }
    
        .hijo {
            /* IMPORTANTE */
            width: 200px;
            margin-left: auto;
            margin-right: auto;
        }
        .recibo{
            border-style: ridge;
        }

    </style>
    <body>
<?php    
    if($msg == 'Pago Exitoso'){ 
?>
  
    <div class="padre">
        <p class="hijo" style="text-align: center;">
            <img src="https://902558.smushcdn.com/2161880/wp-content/uploads/2017/09/First-DAta-logo.jpg?lossy=1&strip=1&webp=1" alt="PayPal-Logo" width="180px">
        </p>
        <p class="hijo" style="text-align: center; color: #31D800; font-size: 70px;">
            <i class="fas fa-check-circle"></i>
        </p>
        <h3 class="hijo" style="text-align: center;">Gracias por su pago</h3>
        <h3 class="hijo" style="text-align: center;"><?php echo $msg; ?></h3>
    </div>
  
        
<?php    }else{
?>

    <div class="padre">
        <p class="hijo" style="text-align: center;">
            <img src="https://902558.smushcdn.com/2161880/wp-content/uploads/2017/09/First-DAta-logo.jpg?lossy=1&strip=1&webp=1" alt="PayPal-Logo" width="180px">
        </p>
        <p class="hijo" style="text-align: center; color: #d11515; font-size: 70px;">
            <i class="fas fa-times-circle"></i>
        </p>
        <h3 class="hijo" style="text-align: center;">Cancelo el Pago</h3>
        <p class="hijo" style="text-align: center;"><?php echo $msg; ?></p>
    </div> 

<?php } ?>
</body>
</html>