<?php
include '../clases/db.php';
include '../clases/db2.php';
require 'vendor/autoload.php'; //composer packages (guzzle)

$json = file_get_contents('php://input');   
$obj = json_decode($json);
$id = $obj->flag;
$conn = new conexion_sec("directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);
// Returns a Json
header('Content-Type: application/json');
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request; 
switch($id){
    case '0':
        date_default_timezone_set('America/Mexico_City');
        $fecha_fin = strtotime($obj->fecha);
        $date = date('Y-m-d H:i:s');
        $fecha_hoy = strtotime($date);
        $msg = "success";

        //$fecha_fin."-".$fecha_hoy."\n";
        if($fecha_fin < $fecha_hoy){
            $msg = "No puedes reservar, la clase termino";
        }else{
            $query_s = "SELECT * FROM aforo_reservaciones WHERE id_cliente = '$obj->id_cliente' AND fecha_reservacion = '$obj->fecha' AND status_reservacion = 0";

            $resultado = $conn->selectQuery($query_s,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);

            //var_dump($resultado);
            if(mysqli_num_rows($resultado) > 0){
                $msg = 'Ya cuentas con una reservacion para esa clase';
            }else{
            //$conn->close();
                $conn2 = new conexion_sec("directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);

                $query = "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";
            
                $resultadoQ = $conn->selectQuery($query,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);

                //$numrows = mysqli_num_rows($query);

                if(mysqli_num_rows($resultadoQ) > 0){
                    while($row = $resultadoQ->fetch_assoc()){
                        $idSer = $row["id"];
                        $subQuery = "SELECT * FROM servicios_sucursal WHERE servicios_idservicio = '$idSer'";
                        $resultado2 = $conn->selectQuery($subQuery, "directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);
                        if(mysqli_num_rows($resultado2) > 0){
                            if($row_2 = mysqli_fetch_array($resultado2)){
                                if($obj->gym != $row_2['sucursal_idsucursal']){
                                    echo $msg = 'No tienes acceso a esta sucursal';
                                }
                            }
                        }
        
                    }
                }
                

                if($msg == 'success')
                {
                    $query = "INSERT INTO aforo_reservaciones(id_cliente, fecha_registro, fecha_reservacion, status_reservacion, id_sucursal) VALUES('$obj->id_cliente',NOW(),'$obj->fecha','0','$obj->gym')";
                
                    $conn->insert_query($query,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);
                }
                

                
            }
        }
        
        
        echo $msg;
        
        break;
    
    case "1":
            //$conn = new conexion_sec("localhost:3306","root","",$obj->bd);

        $query ="UPDATE socios SET token_qr = '$obj->qr' WHERE idSocio = $obj->id";

        $conn->insert_query($query, "directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);

        break;
        
    case "2":
        $first_pass = $obj->pass_anterior;
        $old_password;
        $passwd = $obj->passwd;
        $passwdConfirm = $obj->passwdConfirm;
        
        $query = "SELECT socios.Contrasena FROM socios WHERE socios.idSocio = '$obj->id_cliente'";
        $resultado = $conn->selectQuery($query, "directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);

        while($row = mysqli_fetch_array($resultado)){

            $old_password = $row['Contrasena'];
        }

        if(password_verify($first_pass, $old_password)){
            if($passwd == $passwdConfirm){
                if(strlen($passwdConfirm) >= 6){
                    $passHash = password_hash($passwdConfirm, PASSWORD_BCRYPT);
                    $queryUpdate = "UPDATE socios SET socios.Contrasena = '$passHash' WHERE socios.idSocio = '$obj->id_cliente'";
                    $conn->insert_query($queryUpdate, "directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);
                    echo 'success';
                }else{
                    echo 'Tu contrasena nueva debe contener al menos 6 caracteres';
                }
                
            }else{
                echo 'Las contrasenas no coinciden';
            }
        }else{
            echo 'Tu contrasena actual no coincide, intenta de nuevo.';
        }
        break;
    
    case "3":
        $query = "INSERT INTO stripe(id_socio, id_stripe) VALUES('$obj->id_cliente','$obj->idStripe')";
        $conn->insert_query($query,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);
        
        break;
    case "4":
        $id_insert;
        $mes;
        
        $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,
                socios.Activo
            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->selectQuery($query_fecha,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);
            
        if($obj->opcion == "00"){
            $msg = 'No tienes acceso a esta sucursal';
            if(mysqli_num_rows($result_fecha) > 0){
                while($row = $result_fecha->fetch_assoc()){
                    $idSer = $row["id"];
                    //echo $row["Activo"]."\n";
                    $subQuery = "SELECT * FROM servicios_sucursal JOIN servicios ON servicios_sucursal.servicios_idservicio = servicios.idServicio
                    WHERE servicios_sucursal.servicios_idservicio = '$obj->id_servicio' AND servicios.Borrado != 1";
                    $resultado2 = $conn->selectQuery($subQuery, "directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);
                    if($row['Activo'] == '0'){
                       $band_activo == TRUE;
                    }
                    
                    //echo $obj->paquetes, $row['id']."\n";
                    if(strpos($obj->paquetes, $row['id']) || $obj->paquetes == $row['id']){
                        $band_clase = TRUE;
                    }
                    if(mysqli_num_rows($resultado2) > 0){
                        //$row_2 = mysqli_fetch_array($resultado2);
                        while($row_2 = $resultado2->fetch_assoc()){
                            //echo $obj->sucursal. ' != '. $row_2['sucursal_idsucursal']."\n";
                            if($obj->sucursal == $row_2['sucursal_idsucursal']){
                                //$msg = 'No tienes acceso a esta sucursal';
                                $msg = 'OK';
                                //exit();
                            }
                        }
                    }
            
                }
            }
            
            if($msg == 'OK'){
                echo 'Esta clase esta incluida en tu Plan';
                exit();
            }
        }
        $query = "INSERT INTO socio_servicio(idServicio,idSocio,idSocioTitular,FechaSolicitud,FechaInscripcion)
        VALUES('$obj->id_servicio','$obj->id_cliente','$obj->id_cliente',CURDATE(),CURDATE())";
        
        $resultado = $conn->insert_query($query,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);
        //$resultado = 1;
        if($resultado == 1){
            $q_select = "SELECT MAX(idSocio_Servicio) AS idInsert FROM socio_servicio WHERE idSocioTitular = '$obj->id_cliente'";
            $result = $conn->selectQuery($q_select, "directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);
            $row = mysqli_fetch_array($result);
            $id_insert = $row['idInsert'];
        
            $query_suc = "SELECT sucursal_idSucursal AS sucursal FROM socios WHERE idSocio = '$obj->id_cliente'";
            $recult_suc = $conn->selectQuery($query_suc, "directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);
            $row_suc = mysqli_fetch_array($recult_suc);
            $id_sucursal = $row_suc['sucursal'];
            
            switch($obj->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;
                
            }
            
        
            /*$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,
                socios.Activo
            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->selectQuery($query_fecha,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);*/
            $row_fecha = mysqli_fetch_array($result_fecha);
            $fecha_hoy = date('Y-m-d');
            $fechaI;
            $concepto;
            //echo 'Op '.$obj->opcion."\n";
            if($obj->opcion != "00"){
                $fechaI = $row_fecha['FechaFin'];
                $concepto = "99";
            }else{
                $fechaI = $obj->fecha_visita;
                $concepto = "00";
            }
            $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(),$obj->importe,2,2,0.00,$obj->importe,CURDATE(),'Stripe',0.00,'Stripe',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(),$obj->importe,2,2,0.00,$obj->importe,CURDATE(),'Stripe',0.00,'Stripe',0.00,
                $id_sucursal,0,$fecha_vencimiento,0)";
            }
            
            
            $resultado2 = $conn->insert_query($query_pagos,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);
            
            echo $resultado2;
        }else{
            echo 'Ocurrio un error';
        }
        break;
        
        case '5':
            $query ="UPDATE aforo_reservaciones SET status_reservacion = 1 WHERE id_reservacion = '$obj->id_res'";
            $resultado = $conn->insert_query($query,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);
            
            echo $resultado;
            break;
        case '6':
            $addFecha;
            $queryLocker ="SELECT ls.*, l.*, locks.*
            FROM socios s JOIN lockers_socios ls ON s.idSocio = ls.Socios_idSocio JOIN locker l ON ls.id_lockers_socios = l.id_locker JOIN lockers locks ON locks.idLocker = l.Lockers_idLockers
            WHERE ls.id_lockers_socios = (SELECT MAX(id_lockers_socios) FROM lockers_socios WHERE Socios_idSocio = '$obj->id_cliente')";
            
            $resultadoL = $conn->selectQuery($queryLocker,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);
            $row_fecha = mysqli_fetch_array($resultadoL);
            $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,'$obj->costo','$obj->costo',21,'$obj->suc',0)";
            
            $resultado = $conn->insert_query($query,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);
            
            echo $resultado;
            break;
        
        case '7':
            
            $fecha_hoy = date('Y-m-d');
            $horarios_clase;
            if($fecha_hoy == $obj->fechaClase){
                $horarios_clase = explode("-", $obj->horario);
                $hora_inicio = ltrim($horarios_clase[0]);
                
                $hora_hoy = date('H:i:s');
                
                //echo $hora_inicio .'-'.$hora_hoy;
                
                if(strtotime($hora_inicio) < strtotime($hora_hoy)){
                    echo 'No es posible reservar, la clase finalizo';
                    //$conn->disconnect();
                    exit();
                }
            }
            
            $band_clase = FALSE;
            $band_activo = FALSE;
            if(empty($obj->paquetes)){
                echo 'No hay paquetes asignados a esta clase';
                exit();
            }
            
            $queryP = "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,
                socios.Activo
            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
                AND socios.Activo != 0
			GROUP BY
				socio_servicio.idSocio_Servicio DESC
            ) AS tmp
        GROUP BY
        	tmp.id
        ORDER BY
            tmp.idss DESC;";
        
        $resultadoP = $conn->selectQuery($queryP,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);
        
        $band_acceso = TRUE;
        
        $msg = 'No tienes acceso a esta sucursal';
        if(mysqli_num_rows($resultadoP) > 0){
            while($row = $resultadoP->fetch_assoc()){
                $idSer = $row["id"];
                //echo $row["Activo"]."\n";
                $subQuery = "SELECT * FROM servicios_sucursal JOIN servicios ON servicios_sucursal.servicios_idservicio = servicios.idServicio
                WHERE servicios_sucursal.servicios_idservicio = '$idSer' AND servicios.Borrado != 1";
                $resultado2 = $conn->selectQuery($subQuery, "directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);
                if($row['Activo'] == '0'){
                   $band_activo == TRUE;
                }
                
                //echo $obj->paquetes, $row['id']."\n";
                if(strpos($obj->paquetes, $row['id']) || $obj->paquetes == $row['id']){
                    $band_clase = TRUE;
                }
                if(mysqli_num_rows($resultado2) > 0){
                    //$row_2 = mysqli_fetch_array($resultado2);
                    while($row_2 = $resultado2->fetch_assoc()){
                        //echo $obj->sucursal. ' != '. $row_2['sucursal_idsucursal']."\n";
                        if($obj->sucursal == $row_2['sucursal_idsucursal']){
                            //$msg = 'No tienes acceso a esta sucursal';
                            $msg = 'OK';
                            //exit();
                        }
                    }
                }
        
            }
        }
        
        if($msg != 'OK'){
            echo $msg;
            $conn->disconnect();
            exit();
        }
        /*while($rowP = $resultadoP->fetch_assoc()){ //recorremos los paquetes
        echo 'fin';
        echo $rowP['NombreDisciplina']."\n";
        //echo $rowP['id']."\n";    
        //var_dump($resultado);
        /*echo $obj->paquetes, ' ' ,$rowP['id'];
        echo "\n";
            
            
            if($row['Activo'] == '0'){
                $band_activo == TRUE;
            }
            
            if(strpos($obj->paquetes, $rowP['id']) || $obj->paquetes == $rowP['id']){
                $band_clase = TRUE;
            }
            
         
            
        }*/
        
        if($band_activo == TRUE){
            echo 'Cliente Inactivo';
            $conn->disconnect();
            exit();
        }
        //echo $band_clase;
        if($band_clase == FALSE){
            echo 'Tu paquete no tiene acceso la clase';
            $conn->disconnect();
            exit();
        }
        
            $queryBR = "SELECT * FROM socio_clase 
            WHERE Socios_idSocio = '$obj->id_cliente' 
            AND fecha_de_clase = '$obj->fechaClase' 
            AND Clase_idClase = '$obj->idClase'
            AND status = 1";
            $resultadoBR = $conn->selectQuery($queryBR,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);
            
            $resultadoB;
            $row;
            if(mysqli_num_rows($resultadoBR) > 0){
                echo 'Ya cuentas con una reservacion para esta clase';
                $conn->disconnect();
                exit();
            }else{
                $queryBuscar = "SELECT fecha_clase.*, clase.Cupo FROM 
	                fecha_clase JOIN clase ON fecha_clase.clase_idClase = clase.idClase 
	                WHERE fecha_de_clase ='$obj->fechaClase' AND clase_idClase = '$obj->idClase'";
	                
                $resultadoB = $conn->selectQuery($queryBuscar,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);
                
                $row = $resultadoB->fetch_assoc();
                
                /*if($row['clientes_registrados'] >= $row['Cupo']){
                    echo 'Clase Llena';
                    $conn->disconnect();
                    exit();
                }*/
            }
            $query = "INSERT socio_clase(Clase_idClase,Socios_idSocio,fecha_de_clase,fecha_registro,status)
            VALUES('$obj->idClase','$obj->id_cliente','$obj->fechaClase','$obj->registro','1')";
            
            $resultado = $conn->insert_query($query,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);
            $resultado = 1;
            if($resultado == 1){
                
                if(mysqli_num_rows($resultado) == 1){
                    $row = mysqli_fetch_array($resultadoB);
                    $numCliente = $row['clientes_registrados'] + 1;
                    $queryUdt = "UPDATE fecha_clase SET clientes_registrados = '$numCliente' 
                    WHERE fecha_de_clase = '$obj->fechaClase' AND clase_idClase = '$obj->idClase'";
                    $resultadoU = $conn->insert_query($queryUdt,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);
                    if($resultadoU == 1){
                        echo 'Suucess';
                    }else{
                        echo 'Error';
                    }
                    
                }else{
                    $queryFecha = "INSERT fecha_clase(clase_idClase,clientes_registrados,fecha_de_clase)
                    VALUES('$obj->idClase','1','$obj->fechaClase')"; 
                    $resultadoF = $conn->insert_query($queryFecha,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);
                
                    if($resultadoF == 1){
                        echo 'Suucess';
                    }else{
                        echo 'Error';
                    }
                }
                
            }else{
                echo 'Error';
            }
            break;
            
        case '8':
            $bandUpdate = FALSE;
            if($obj->idCliente == null || $obj->token == null || $obj->sucursal == null || $obj->bd == null){
                exit();
            }
            
            $queryBuscar = "SELECT * FROM push_notificaciones WHERE idSocio = '$obj->idCliente'";
            $resultado = $conn->selectQuery($queryBuscar,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);
            
            if(mysqli_num_rows($resultado) > 0){
                
                while($row = $resultado->fetch_assoc()){
                    if($obj->token != $row["token"]){
                        $bandUpdate = TRUE;
                    }else{
                        $conn->disconnect();
                        exit();
                    }
                }
                
            
            }
            
            if($bandUpdate == TRUE){
                $query= "UPDATE push_notificaciones SET token = '$obj->token' WHERE idSocio = '$obj->idCliente'";
                $conn->insert_query($query,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);
            }else{
                $query= "INSERT push_notificaciones(idSocio,token,sucursal,notificacion) 
                VALUES('$obj->idCliente','$obj->token','$obj->sucursal',1)";
                $conn->insert_query($query,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);
            }
            
            break;
        case '9':

            $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 5426064000424979

            $transaction = ["paymentMethod"=>[

                "paymentCard"=>[

                        "number"=>$obj->numbercard,//5426064000424979

                        "securityCode"=>$obj->ccv,

                        "expiryDate"=>[

                            "month" => $obj->month,

                            "year" => $obj->year

                        ]

                    ]

                ],

                "transactionAmount" =>["total"=>$obj->importe,"currency"=>"MXN"],

                "requestType"=>"PaymentCardSaleTransaction",

                "authenticationRequest" => [

                    "authenticationType" => "Secure3D21AuthenticationRequest",

                    "termURL" => "https://localhost/firstdata/index.php",

                    "methodNotificationURL" => "https://localhost/firstdata/index.php",

                    "challengeIndicator" => "01"

                ]];

            
            //SERIALIZE TO JSON

            echo $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));
            
            $msg = $API_KEY. $uuid . $timestamp . $data_string;
            
             
                

            $hmac = hash_hmac('sha256', $msg, $API_KEY);
            
            //echo $hmac;
            $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
            //echo '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 {

        
                //echo '-Send request';
                //SEND REQUEST

                $request = new Request('POST', 'payments', $headers, $data_string);

                $response = $client->send($request);

                //http_response_code($response->getStatusCode());

                $result_pago = json_decode($response->getBody()->getContents());

                //echo 'hola';

                //insert pago

                $id_insert;

                $mes;

                $query = "INSERT INTO socio_servicio(idServicio,idSocio,idSocioTitular,FechaSolicitud,FechaInscripcion)

                VALUES('$obj->id_servicio','$obj->id_cliente','$obj->id_cliente',CURDATE(),CURDATE())";

                

                $resultado = $conn->insert_query($query,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);

                //$resultado = 1;

                if($resultado == 1){

                    $q_select = "SELECT MAX(idSocio_Servicio) AS idInsert FROM socio_servicio WHERE idSocioTitular = '$obj->id_cliente'";

                    $result = $conn->selectQuery($q_select, "directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);

                    $row = mysqli_fetch_array($result);

                    $id_insert = $row['idInsert'];

                

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

                    $recult_suc = $conn->selectQuery($query_suc, "directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);

                    $row_suc = mysqli_fetch_array($recult_suc);

                    $id_sucursal = $row_suc['sucursal'];

                    

                    switch($obj->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;

                        

                    }

                    

                    

                    $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->selectQuery($query_fecha,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);

                    $row_fecha = mysqli_fetch_array($result_fecha);

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

                    $fechaI;

                    $concepto;

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

                    if($obj->opcion != "00"){

                        $fechaI = $row_fecha['FechaFin'];

                        $concepto = "99";

                    }else{

                        $fechaI = $obj->fecha_visita;

                        $concepto = "00";

                    }

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

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

                    }else{

                        echo $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(),$obj->importe,2,2,0.00,$obj->importe,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@",$obj->bd);

                    

                    //echo $resultado2;

                }else{

                    echo 'Ocurrio un error';

                }

                

                //fin insert pago

            } catch (Exception $e) {

                http_response_code(503);

                //HANDLE GUZZLE EXCEPTION 

                //FOR EXAMPLE: SERVER IMPOSSIBLE TO REACH DUE CONNECTION ERRORS

            }

        

            echo json_encode($result_pago);//return response to ajax request


        break;
        
        case '10':
             $query = "UPDATE socio_clase, fecha_clase SET socio_clase.status = '2', fecha_clase.clientes_registrados = fecha_clase.clientes_registrados -1
            WHERE socio_clase.Clase_idClase = '$obj->id_clase' AND fecha_clase.Clase_idClase = '$obj->id_clase'";
            echo $resultado = $conn->insert_query($query,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);
            break;
        case '11':
            /*
                telefono_prospecto
            */
            echo $bd = $obj->bd;
            $id_insert;
            $query_socio = "INSERT INTO socio_servicio(idServicio,idSocio,idSocioTitular,FechaSolicitud,FechaInscripcion) 
            VALUES('$obj->id_servicio','$obj->id_cliente','$obj->id_cliente',CURDATE(),CURDATE())";
            
           echo $resultado = $conn->insert_query($query_socio,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$bd);
            
            //if($resultado == 1){
                $q_select = "SELECT MAX(idSocio_Servicio) AS idInsert FROM socio_servicio WHERE idSocioTitular = '$obj->id_cliente'";

                $result = $conn->selectQuery($q_select, "directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$bd);

                $row = mysqli_fetch_array($result);

                $id_insert = $row['idInsert'];
                
                $fecha_vencimiento = "DATE_ADD( '$obj->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(),$obj->importe,2,2,0.00,$obj->importe,CURDATE(),'Stripe',0.00,'Stripe',0.00,$obj->sucursal,0,$fecha_vencimiento,0)";
                
                
                $conn->insert_query($query_pagos,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$bd);
                
                //if($res == 1){
                    $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 ('$obj->nombre','$obj->apellido','$obj->fechaN',$obj->genero,'$obj->email','$obj->tel',
                    '$obj->domi','$obj->col','$obj->cp','visita',NOW(),6,'$obj->qr')";
                    
                    $conn->insert_query($query,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$bd);
                /*}else{
                    echo 'error';
                }*/
            
            /*}else{
                echo 'error';
            }*/
            
            break;
}
$conn->disconnect("directoriofitness.com.mx","direct18","L4LL4v3M@3str@",'direct18_'.$obj->bd);
?>
