<?php

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

    use GuzzleHttp\Client;
    use GuzzleHttp\Psr7\Request;
    /*$TemUrl = $result->authenticationResponse->params->termURL."?idT=".$transationid."&id_cliente=".$obj->id_cliente."&concepto=".
                $obj->concepto."&costo=".$obj->costo."&idLocker=".$obj->idLocker."&lock_asig=".$obj->lock_asig."&suc=".$obj->suc."&bandLocker=".$obj->bandLocker;*/
    $idT = $_GET['idT'];
    $PaReq = $_POST['PaRes'];
    $MD = $_POST['MD'];
    $bd = $_GET['bd'];
    $id_cliente;
    $concepto;
    $costo;
    $id_Locker;
    $lock_asig;
    $suc;
    $bandLocker = $_GET['bandLocker'];
    $mensaje_final = 'Pago Exitoso';
    $fecha_visita;
    
    $API_KEY; //'npfhBnGhAAlExcxkG4PWmt6Dok6kPjjz';
    $API_SECRET; //'JPVzTCmmocqGDTGT';
    
    if($bandLocker === 'TRUE'){
        $id_cliente = $_GET['id_cliente'];
        $concepto = $_GET['concepto'];
        $costo = $_GET['costo'];
        $id_Locker = $_GET['idLocker'];
        $lock_asig = $_GET['lock_asig'];
        $suc = $_GET['suc'];
    }else{
        $plan = $_GET['plan'];
        $opcion = $_GET['opcion'];
        $id_cliente = $_GET['id_cliente'];
        $id_servicio = $_GET['id_servicio'];
        $costo = $_GET['costo'];
        $bandD = $_GET['bandD']; 
        $fecha_visita = $_GET['fecha_clase'];
    }
    
    
    
    $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 = '$suc'";
    
    $resultApi = $conn->query($queryApi);
    
    if ($result->num_rows > 0){
        $row = $resultApi->fetch_assoc();
    
        $API_KEY = row['api_key'];
        $API_SECRET = row['secret_key'];
    }else{
        $bandApi = FALSE;
    }
    
    
    $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
    
        
    
    
    $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@",$bd);
        //pago insert 
        
        if($bandLocker === 'FALSE'){ //INSERT PAGO DE PLAN
         $id_insert;
                $query_fecha ="SELECT  * FROM(SELECT 
                        socio_servicio.idServicio as 'id',
                        pagos.FechaInicio,
                        servicios.NombreServicio,
                        socio_servicio.idSocio_Servicio AS 'idss',
                        socio_servicio.idSocioTitular as 'st',
                        pagos.FechaFin
                    FROM 
                        socio_servicio
                        INNER JOIN pagos
                            ON socio_servicio.idSocio_Servicio = pagos.idSocio_Servicio
                            INNER JOIN servicios
                            ON socio_servicio.idServicio = servicios.idServicio
                            INNER JOIN socios
                            ON socio_servicio.idSocio = socios.idSocio
                    WHERE
                        socio_servicio.idSocio = '$id_cliente'
                        AND pagos.Cancelado = 0  
                        AND pagos.Visible = 1
                    GROUP BY
                    socio_servicio.idSocio_Servicio DESC
                                ) AS tmp
                            GROUP BY
                            tmp.id
                            ORDER BY
                                tmp.idss DESC";
            
                $mes;
                $query;
                if($opcion == "97"){
                    $result_fecha = $conn->query($query_fecha);
                    $rowPlanP = $result_fecha->fetch_assoc();
                    $idP = $rowPlanP['id'];
                    $query = "INSERT INTO socio_servicio(idServicio,idSocio,idSocioTitular,FechaSolicitud,FechaInscripcion)
                    VALUES('$idP','$obj->id_cliente','$obj->id_cliente',CURDATE(),CURDATE())";
                }else{
                    $query = "INSERT INTO socio_servicio(idServicio,idSocio,idSocioTitular,FechaSolicitud,FechaInscripcion)
                    VALUES('$id_servicio','$id_cliente','$id_cliente',CURDATE(),CURDATE())";
                }
                
                

                

                //$resultado = $conn->quer($query);

                //$resultado = 1;

                if($conn->query($query) === 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'];

                

                    $query_suc = "SELECT sucursal_idSucursal AS sucursal FROM socios WHERE idSocio = '$id_cliente'";

                    $recult_suc = $conn->query($query_suc);

                    $row_suc = $recult_suc->fetch_assoc();

                    $id_sucursal = $row_suc['sucursal'];

                    switch($plan){
                        case '1':
                            $mes = 0;
                            break;
                        case '2':
                            $mes = 7;
                            break;
                        case '3':
                            $mes = 15;
                            break;
                        case '4':
                            $mes = 1;
                            break;
                        case '5':
                            $mes = 2;
                            break;
                        case '6':
                            $mes = 3;
                            break;
                        case '7':
                            $mes = 4;
                            break;
                        case '8':
                            $mes = 6;
                            break;
                        case '9':
                            $mes = 12;
                            break;

                    }

                    $result_fecha = $conn->query($query_fecha);

                    $row_fecha = $result_fecha->fetch_assoc();

                    $fecha_hoy = date('Y-m-d');

                    $fechaI;

                    $concepto;
                    $visible;
                    //echo 'Op '.$obj->opcion."\n";

                    if($opcion == "99"){

                        $fechaI = $row_fecha['FechaFin'];

                        $concepto = "99";
                        $visible = '1';

                    }else if($opcion == "97"){
                        $fechaI = date('Y-m-d');
                        $concepto = "97";
                        $visible = '1';
                    }else{

                        $fechaI = $fecha_visita;

                        $concepto = "00";
                        $visible = '0';

                    }

                    $query_pagos;

                    

                    if($mes == 0 || $mes == 7 || $mes == 15){
                        if($mes == 0){
                            $fecha_vencimiento = "DATE_ADD( '$fechaI', INTERVAL 1 DAY)";
                        }else{
                            $fecha_vencimiento = "DATE_ADD( '$fechaI', INTERVAL ".$mes." DAY)";
                        }
                        

                    }else{

                        $fecha_vencimiento = "DATE_ADD( '$fechaI', INTERVAL ".$mes." MONTH)";

                    }

                    

                    if($opcion != "00"){

                        $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,'$concepto',NOW(),$costo,2,2,0.00,$costo,CURDATE(),'Firstdata',0.00,'Firstdata',0.00,

                        $id_sucursal,1,$fecha_vencimiento,0)";

                    }else{

                        $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(),$costo,2,2,0.00,$costo,CURDATE(),'Firstdata',0.00,'Firstdata',0.00,

                        $id_sucursal,0,$fecha_vencimiento,0)";

                    }

                    

                    //$resultado2 = $conn->insert_query($query_pagos,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$bd);
    
                    
                    if($conn->query($query_pagos) === TRUE){ 
                        
                        $mensaje_final = 'Pago Exitoso';
                    }else{
                        $mensaje_final = 'Ocurrio un error => '.$query_pagos.' => '.$conn->error;
                    }
                    //echo $resultado2;

                }else{

                    $mensaje_final = 'Ocurrio un error => '.$query.' => '.$conn->error;

                }
        }else{ //PAGO DE LOCKER
            $addFecha;
            $queryLocker ="SELECT 
              	lockers_socios.Socios_idSocio as 'id', 
                lockers.idLocker as 'id_gl', 
                locker.id_locker as 'idlk_c', 
                CONCAT(socios.Nombre, ' ', socios.Apellidos) as 'name', 
                lockers.Clave as 'grupo',
                locker.num_locker as 'num_locker', 
                lockers_socios.FechaAsignacion as 'pago', 
                lockers_socios.FechaVencimiento, 
                lockers_socios.concepto_pago as 'concepto', 
                lockers_socios.importe as 'total', 
                lockers_socios.estado 'status',
                lockers_socios.cancelado,
                sucursal.NombreSucursal as 'sucursal',
                IF(lockers_socios.FechaVencimiento < DATE_FORMAT(NOW(), '%d/%m/%Y') 
            		AND lockers_socios.cancelado = 0 AND lockers_socios.estado = 1, 'TRUE', 'FALSE') as 'vencimiento'
            FROM 
                lockers_socios, 
                socios, 
                lockers, 
                sucursal, 
                locker 
            WHERE 
                lockers_socios.Lockers_idLocker = lockers.idLocker 
                AND lockers_socios.Socios_idSocio = socios.idSocio 
                AND lockers_socios.sucursal_idSucursal = sucursal.idSucursal 
                AND socios.idSocio = $id_cliente
                AND lockers_socios.locker_asignado = locker.id_locker
                AND lockers_socios.cancelado = 0
            ORDER BY 
                lockers_socios.id_lockers_socios DESC LIMIT 1";
            
            $resultadoL = $conn->query($queryLocker);
            $row_fecha = $resultadoL->fetch_assoc();
            $fechaVen = $row_fecha['FechaVencimiento'];
            $fecha_act = $row_fecha['FechaAsignacion'];
            switch($concepto){
                case '1':
                    $addFecha = "DATE_ADD( '$fechaVen', INTERVAL 1 DAY)";
                    break;
                case '2':
                    $addFecha = "DATE_ADD( '$fechaVen', INTERVAL 7 DAY)";
                    break;
                case '3':
                    $addFecha = "DATE_ADD( '$fechaVen', INTERVAL 15 DAY)";
                    break;
                case '4':
                    $addFecha = "DATE_ADD( '$fechaVen', INTERVAL 1 MONTH)";
                    break;
                case '5':
                    $addFecha = "DATE_ADD( '$fechaVen', INTERVAL 6 MONTH)";
                    break;
                case '6':
                    $addFecha = "DATE_ADD( '$fechaVen', INTERVAL 12 MONTH)";
                    break;
            }
            
            $query = "INSERT lockers_socios(Lockers_idLocker,Socios_idSocio,locker_asignado,FechaAsignacion,FechaVencimiento,estado,concepto_pago,tipo_pago,
            cantidad_tarjeta,importe,user_idUsuario,sucursal_idSucursal,cancelado)
            VALUES('$id_Locker','$id_cliente','$lock_asig','$fechaVen',$addFecha,1,'$concepto',2,'$costo','$costo',21,'$suc',0)";
            
            //$resultado = $conn->query($query);
            if($conn->query($query) === TRUE){
                if($opcion == "97"){
                    $querySocio = "UPDATE socios SET Activo = 1 WHERE idSocio = $id_cliente";
                    if($conn->query($querySocio) == TRUE){
                        $mensaje_final = 'Pago Exitoso';  
                    }else{
                        $mensaje_final = 'error';  
                    }
                }else{
                    $mensaje_final = 'Pago Exitoso';   
                }
            }else{
                $mensaje_final = 'Ocurrio un error => '.$query.' => '.$conn->error;
            }
        }
        
        //fin pago
        $conn->close();
    } catch (Exception $e) {
        echo $mensaje_final = 'Error al procesar la transacción '.$e;
        http_response_code(503);
        //HANDLE GUZZLE EXCEPTION 
        //FOR EXAMPLE: SERVER IMPOSSIBLE TO REACH DUE CONNECTION ERRORS
    } 
    //echo json_encode($result);
?>
    
    
    <!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($mensaje_final == '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 $mensaje_final; ?></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 $mensaje_final; ?></p>
    </div> 

<?php } ?>
