<?php

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

    use GuzzleHttp\Client;
    use GuzzleHttp\Psr7\Request;
    
    
    $transationid;
    $transaction;
    $send_ruta;
    $unit;
    $costo;
    $result = '';
    $addFecha;
    $mes;
    if (!is_object($result))
        $result = new stdClass;
    date_default_timezone_set('America/Mexico_City');
    // get data from ajax request
    $json = file_get_contents('php://input');   
    $obj = json_decode($json);
    header('Content-Type: application/json');
   
    //BUILD TRANSACTION 4931580001642617 4035874000424977
    //aqui se cambia la tarjeta
    $card_number = explode(' ',$obj->numbercard);
    //echo sizeof($card_number),' - ',$obj->numbercard;
    $numero_card = $card_number[0].$card_number[1].$card_number[2].$card_number[3];
    
    
    $API_KEY; //'npfhBnGhAAlExcxkG4PWmt6Dok6kPjjz';
    $SECRET_KEY; //'JPVzTCmmocqGDTGT';
    
    $var_bd = explode("_",$obj->bd);
    $bdC = $var_bd[1];
    $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 = '$bdC' AND info_firstdata.sucursal_idSucursal = '$obj->suc'";
    
    $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($obj->bandLocker == TRUE){
            $costo = $obj->costo;
    }else{
            $costo = $obj->importe;
    }
    if($obj->bandD == FALSE){
        
        $send_ruta = 'payments';
        $transaction = ["paymentMethod"=>[
        "paymentCard"=>[
                "number"=>$numero_card,
                "securityCode"=>$obj->ccv,
                "expiryDate"=>[
                    "month" => $obj->month,
                    "year" => $obj->year
                ]
            ]
        ],
        "transactionAmount" =>["total"=>$costo,"currency"=>"MXN"],
        "requestType"=>"PaymentCardSaleTransaction",
        "authenticationRequest" => [
            "authenticationType" => "Secure3D21AuthenticationRequest",
            "termURL" => "https://directoriofitness.com.mx/progymcloud_app/pagos/firstdata/secure3d.php",
            "methodNotificationURL" => "https://directoriofitness.com.mx/progymcloud_app/pagos/firstdata/notificacion.php",
            "challengeIndicator" => "03"
        ]];
        /*$transaction = [
          "requestType"=> "PaymentCardSaleTransaction",
          "transactionAmount"=> [
            "total"=>"$costo",
            "currency"=>"MXN"
          ],
          "paymentMethod"=> [
            "paymentCard"=> [
              "number"=> "$numero_card",
              "securityCode"=> "$obj->ccv",
              "expiryDate"=> [
                "month"=> "$obj->month",
                "year"=> "$obj->year"
              ]
            ]
          ]
        ];*/
    }else{
        
        if($obj->bandLocker == TRUE){
            switch($obj->concepto){
                case '1':
                    $mes = 1;
                    $unit = 'DAY';
                    $addFecha = "DATE_ADD( '$fechaVen', INTERVAL 1 DAY)";
                    break;
                case '2':
                    $mes = 7;
                    $unit = 'DAY';
                    $addFecha = "DATE_ADD( '$fechaVen', INTERVAL 7 DAY)";
                    break;
                case '3':
                    $mes = 15;
                    $unit = 'DAY';
                    $addFecha = "DATE_ADD( '$fechaVen', INTERVAL 15 DAY)";
                    break;
                case '4':
                    $mes = 1;
                    $unit = 'MONTH';
                    $addFecha = "DATE_ADD( '$fechaVen', INTERVAL 1 MONTH)";
                    break;
                case '5':
                    $mes = 6;
                    $unit = 'MONTH';
                    $addFecha = "DATE_ADD( '$fechaVen', INTERVAL 6 MONTH)";
                    break;
                case '6':
                    $mes = 12;
                    $unit = 'MONTH';
                    $addFecha = "DATE_ADD( '$fechaVen', INTERVAL 12 MONTH)";
                    break;
            }
        }else{
            switch($obj->plan){
                case '1':
                    $mes = 0;
                    $unit = 'DAY';
                break;
                case '2':
                    $mes = 7;
                    $unit = 'DAY';
                break;
                case '3':
                    $mes = 15;
                    $unit = 'DAY';
                break;
                case '4':
                    $mes = 1;
                    $unit = 'MONTH';
                break;
                case '5':
                    $mes = 2;
                    $unit = 'MONTH';
                break;
                case '6':
                    $mes = 3;
                    $unit = 'MONTH';
                break;
                case '7':
                    $mes = 4;
                    $unit = 'MONTH';
                break;
                case '8':
                    $mes = 6;
                    $unit = 'MONTH';
                break;
                case '9':
                    $mes = 12;
                    $unit = 'MONTH';
                break;
            }
        }
        $numberPurchase = rand(000000000,999999999);
        
        $conn = new mysqli("directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);
        $queryFolio = 'SELECT MAX(idPago) AS folio FROM pagos';
        $resultFolio = $conn->query($queryFolio);
        
        $rowFolio = $resultFolio->fetch_assoc();
        
        //echo 'folio '.$folio = $rowFolio['folio'];
        
        $conn->close();
        
        $send_ruta = 'payment-schedules';
        $transaction = [
            //"invoiceNumber" => "96126098",
            "purchaseOrderNumber" => "$folio",
            "requestType" => "PaymentMethodPaymentSchedulesRequest",
            "transactionAmount" => [
                "total" => (float)$costo,
                "currency" => "MXN"
            ],
            "startDate" => "2021-12-31",
            "frequency" => [
                "every" => (int)$mes,
                "unit" => $unit
            ],
            "paymentMethod" => [
                "paymentCard" => [
                    "number" => $numero_card,
                    "securityCode" => $obj->ccv,
                    "expiryDate" => [
                        "month" => $obj->month,
                        "year" => $obj->year
                    ]
                ]
            ],
            "numberOfPayments" => 3
        ];
    }
    
    
    //SERIALIZE TO JSON
    $data_string = json_encode($transaction);
    //echo "<br>";
    //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
    ];

    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);
        //$transationid = $result;
   
    } catch (Exception $e) {
        http_response_code(503);
        echo json_encode($data_string);
        //HANDLE GUZZLE EXCEPTION 
        //FOR EXAMPLE: SERVER IMPOSSIBLE TO REACH DUE CONNECTION ERRORS
    }
    
    
    if($obj->bandD == FALSE){
        $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;
        
        if($obj->bandLocker == TRUE){
            $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=TRUE".
                "&bd=".$obj->bd;
        }else{
            $TemUrl = $result->authenticationResponse->params->termURL."?idT=".$transationid."&plan=".$obj->plan."&suc=".$obj->suc."&bd=".$obj->bd."&id_cliente=".$obj->id_cliente.
            "&id_servicio=".$obj->id_servicio."&costo=".$costo."&bandD=FALSE&bandLocker=FALSE&opcion=".$obj->opcion."&fecha_clase=".$obj->fecha_clase;
        }
        
        $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>";
    ?>
        
    <?php
    }else{
        echo json_encode($result);
        $conn = new mysqli("directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);
        if($obj->bandLocker == FALSE){
            //echo json_encode($result->orderId);
            
            $orderid = $result->orderId;
            /*
                <!--<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 ?>">
                <script language="JavaScript">document.myform.submit();</script>
           </form>-->
            */
            $id_insert;
            $mes;
            $tipo_plan;
            $query = "INSERT INTO socio_servicio(idServicio,idSocio,idSocioTitular,FechaSolicitud,FechaInscripcion)
            VALUES('$obj->id_servicio','$obj->id_cliente','$obj->id_cliente',CURDATE(),CURDATE())";
            
            //echo $resultado = $conn->query($query);
            //$resultado = 1;
            if($conn->query($query) === TRUE){
                $q_select = "SELECT MAX(idSocio_Servicio) AS idInsert FROM socio_servicio WHERE idSocioTitular = '$obj->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 = '$obj->id_cliente'";
                $recult_suc = $conn->query($query_suc);
                $row_suc = $recult_suc->fetch_assoc();
                $id_sucursal = $row_suc['sucursal'];
                
                switch($obj->plan){
                    case '1':
                        $mes = 0;
                        $tipo_plan = 'Diario';
                        break;
                    case '2':
                        $mes = 7;
                        $tipo_plan = 'Semanal';
                        break;
                    case '3':
                        $mes = 15;
                        $tipo_plan = 'Quincenal';
                        break;
                    case '4':
                        $mes = 1;
                        $tipo_plan = 'Mensual';
                        break;
                    case '5':
                        $mes = 2;
                        $tipo_plan = 'Bimestral';
                        break;
                    case '6':
                        $mes = 3;
                        $tipo_plan = 'Trimestral';
                        break;
                    case '7':
                        $mes = 4;
                        $tipo_plan = 'Cuatrimestral';
                        break;
                    case '8':
                        $mes = 6;
                        $tipo_plan = 'Semestral';
                        break;
                    case '9':
                        $mes = 12;
                        $tipo_plan = 'Anual';
                        break;
                    
                }
                
                
                $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 = '$obj->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";
                
                $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($obj->opcion != "00"){
                    $fechaI = $row_fecha['FechaFin'];
                    $concepto = "99";
                    $visible = '1';
                }else{
                    $fechaI = $obj->fecha_visita;
                    $concepto = "00";
                    $visible = '0';
                }
                $query_pagos;
                
                if($mes == 0 || $mes == 7 || $mes == 15){
                    $fecha_vencimiento = "DATE_ADD( '$fechaI', INTERVAL ".$mes." DAY)";
                    
                }else{
                    $fecha_vencimiento = "DATE_ADD( '$fechaI', INTERVAL ".$mes." MONTH)";
                }
                
                if($obj->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,'99',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)";
                }
                /*$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(),'Stripe',0.00,'Stripe',0.00,
                $id_sucursal,1,$fecha_vencimiento,0)";*/
                
                $name_query = "SELECT * FROM servicios WHERE idServicio = '$obj->id_servicio'";
                $row_name = $result_fecha->fetch_assoc();
                $nombre_plan_s = $row_name['NombreServicio'].'-'.$tipo_plan;
                $description = 'Pago Recurrente '.$tipo_plan;
                if($conn->query($query_pagos) === TRUE){
                    $query_planes_c = "INSERT INTO suscripcion_planes (id_paquete,plan_name,planCode,description,interval_suscription,
                    interval_count,max_payments,plan_value,token,id_sucursal,borrado) VALUES ('$obj->id_servicio','$nombre_plan_s','','$description',
                    '$unit','1','3','$costo','$orderid',$id_sucursal,'1')";
                    
                    if($conn->query($query_planes_c) === TRUE){
                        echo 'Pago Exitoso';
                    }else{
                        echo 'Ocurrio un error';
                    }
                }else{
                    echo 'Ocurrio un error';
                }
                
            }else{
                echo 'Ocurrio un error';
            }
        }else{
            
            $queryLocker ="SELECT 
                locker.num_locker,
                lockers_socios.Lockers_idLocker,
              	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, 
                lockers_socios.importe as 'total', 
                lockers_socios.estado,
                lockers_socios.cancelado,
                sucursal.NombreSucursal as 'sucursal',
                lockers_socios.locker_asignado,
                lockers.*,
                IF(lockers_socios.FechaVencimiento < DATE_FORMAT(NOW(), '%d/%m/%Y') 
            		AND lockers_socios.cancelado = 0 AND lockers_socios.estado = 1, 'TRUE', 'FALSE') as 'vencimiento',
            	DATE_FORMAT(lockers_socios.FechaVencimiento, '%e-%c-%Y') AS Fecha_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 = '$obj->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($obj->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('$obj->idLocker','$obj->id_cliente','$obj->lock_asig','$fechaVen',$addFecha,1,'$obj->concepto',2,'$costo','$costo',21,'$obj->suc',0)";
            
            //$resultado = $conn->query($query);
            if($conn->query($query) === TRUE){
                
                echo 'Pago Exitoso';   
            }else{
                echo 'Ocurrio un error';
            }
            //echo $resultado;
        }
        $conn->close();
    }
    ?>
    
    
        
    