<!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>Paypal</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>
        <nav class="navbar navbar-dark bg-primary">
            <a class="navbar-brand" href="#" style="margin-left: 15px;">ProgymCloud</a>
        </nav>
        <div class="container">
<?php
    require './vendor/autoload.php';
    use PayPal\Api\Amount;
    use PayPal\Api\Details;
    use PayPal\Api\Payment;
    use PayPal\Api\PaymentExecution;
    use PayPal\Api\Transaction;
    $msg1 = '';
    $msg2 = '';
    $msg3 = '';
    $msg4 = '';
    $msg5 = '';
    $msgQuery = '';
    $query_pagos;
    if (isset($_GET['success']) && $_GET['success'] == 'true') {
        base. ' '.$bd = $_GET['bd'];
        //echo "\n";
        $flag = $_GET['flag'];
        //echo "\n";
        $id_cliente = $_GET['id_cliente'];
        //echo "\n";
        $id_servicio = $_GET['id_servicio'];
        //echo "\n";
        $costo = $_GET['costo'];
        //echo "\n";
        $plan = $_GET['plan'];
        //echo "\n";
        $fecha_visita = $_GET['fecha_visita'];
        $paquete_clase = $_GET['paquete_clase'];
        $opcion = $_GET['opcion'];
        $id_sucursal = $_GET['suc'];
        
        $CLIENT_ID;
        $SECRET_ID;
        $prueba; 
        
        $var_bd = explode("_",$bd);
        $bdC = $var_bd[1];
        $conn = new mysqli("directoriofitness.com.mx","direct18","L4LL4v3M@3str@",'direct18_ProGymCloud');
        $conn -> set_charset("utf8");
        $queryApi = "SELECT info_paypal.*, info_plataformaspago.activar_paypal 
                        FROM info_paypal
                    INNER JOIN gimnasios ON info_paypal.gimnasio_idGimnasio = gimnasios.idGimnasio 
                    INNER JOIN info_plataformaspago ON info_plataformaspago.gimnasio_idGimnasio = gimnasios.idGimnasio 
                    WHERE gimnasios.BaseDatos = '$bdC' AND info_paypal.sucursal_idSucursal = '$id_sucursal'";
        
        $resultApi = $conn->query($queryApi);
        
        
        if ($resultApi->num_rows > 0){
            
            $row = $resultApi->fetch_assoc();
        
            $CLIENT_ID = $row['client_id'];
            $SECRET_ID = $row['secret_id'];
            $prueba = $row['prueba'];
            
        }else{
            $bandApi = FALSE;
        }
    
        $conn->close();
        /*$apiContext = new \PayPal\Rest\ApiContext(
            new \PayPal\Auth\OAuthTokenCredential(
                'AbMNQuC6FuWRkohnxxl4AhiZetgL8_99SDtSz_4fVDkKHZD_hEHmY71Sx-2j9UOycGTni5swWzyAD_7l',     // ClientID
                'EFViUhNVgqghUeIZFy0R8sdIdP2XSeheTGQVnyY1VIKs3ioeG0lwz4n96t42hohh_5fs3K2AYVn5JCb6'      // ClientSecret
            )
        );*/
        
        
        $apiContext = new \PayPal\Rest\ApiContext(
            new \PayPal\Auth\OAuthTokenCredential(
                $CLIENT_ID,
                $SECRET_ID
                /*'ATcJBoIQOQWb8I9YgNFXTfBI1Vx_FhSuuHGuFmjR7f5MLl1MosLu2zM_jrfOTJu-AD3O5DnT1UqDNIKx',     // ClientID
                'EGLWdM-RaUxmWRFTuxNotLqhMGWbFGAILTLhqypO1X6ZUYtUIADmTsCHGIJ9dUXlp53D1uawQ6DcM9Zl'  */    // ClientSecret
            )
        );
        
        if($prueba == 1){
            $apiContext->setConfig(
              array(
                'mode' => 'live',
              )
            );
        }
        
        $paymentId = $_GET['paymentId'];
        $payment = Payment::get($paymentId, $apiContext);
        $execution = new PaymentExecution();
        $execution->setPayerId($_GET['PayerID']);
        $transaction = new Transaction();
        $amount = new Amount();
        $details = new Details();
        /*$details->setShipping(2.2)
        ->setTax(1.3)
        ->setSubtotal(17.50);*/
    
        $amount->setCurrency('MXN');
        $amount->setTotal($costo);
        //$amount->setDetails($details);
        $transaction->setAmount($amount);
        $execution->addTransaction($transaction);
        try {
            $result = $payment->execute($execution, $apiContext);
            //echo "Executed Payment", "Payment", $payment->getId(), $execution, $result;
            try {
                $payment = Payment::get($paymentId, $apiContext);
                //echo 'Payment success';
            } catch (Exception $ex) {
                echo "Error Get Payment", "Payment", null, null, $ex;
                //exit(1);
            }
        } catch (Exception $ex) {
            echo "Error Executed Payment", "Payment", null, null, $ex;
            //exit(1);
            
        }
        $conn = new mysqli("directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$bd);
        $conn -> set_charset("utf8");
        $hoy = date('d/m/Y h:i:s A');
        $id_insert;
        $mes;
        $nombreGim;
        $desc_plan;
        $fechaI;
        $fechaA;
        
        $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";
            
        $query;
        if($opcion == '97'){
            $rowPlanP = $result_fecha->fetch_assoc();
            $idP = $rowPlanP['id'];
            $query = "INSERT INTO socio_servicio(idServicio,idSocio,idSocioTitular,FechaSolicitud,FechaInscripcion)
            VALUES('$idP','$id_cliente','$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->query($query);
        //$resultado = $conn->insert_query($query,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$bd);
        
        if($conn->query($query) == TRUE){
            $id_insert = $conn->insert_id;
            /*$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:
                    $desc_plan = 'VISITA';
                    $mes = 0;
                    break;
                case 2:
                    $desc_plan = 'SEMANAL';
                    $mes = 7;
                    break;
                case 3:
                    $desc_plan = 'QUINCENAL';
                    $mes = 15;
                    break;
                case 4:
                    $desc_plan = 'MENSUAL';
                    $mes = 1;
                    break;
                case 5:
                    $desc_plan = 'BIMESTRAL';
                    $mes = 2;
                    break;
                case 6:
                    $desc_plan = 'TRIMESTRAL';
                    $mes = 3;
                    break;
                case 7:
                    $desc_plan = 'CUATRIMESTRAL';
                    $mes = 4;
                    break;
                case 8:
                    $desc_plan = 'SEMESTRAL';
                    $mes = 6;
                    break;
                case 9:
                    $desc_plan = 'ANUAL';
                    $mes = 12;
                    break;
                
            }
            
            //echo $mes;
            $result_fecha = $conn->query($query_fecha);
            $row_fecha = $result_fecha->fetch_assoc();
            $fecha_hoy = date('Y-m-d');
            
            //$fechaI = $row_fecha['FechaFin'];
            $fecha_actual_hoy = date("d-m-Y", strtotime($fechaI));
            
            $concepto;
            $visible;
            //echo 'Op '.$obj->opcion."\n";
            if($opcion == "99"){
                $fechaI = $row_fecha['FechaFin'];
                $concepto = "99";
                $visible = "1";
            }else if($opcion != "00"){
                $fechaI = date('Y-m-d');
                $concepto = "97";
                $visible = "1";
                
            }else{
                $fechaI = $obj->fecha_visita;
                $concepto = "00";
                $visible = "0";
            }
            $desc_plan = $desc_plan.' '.$row_fecha['NombreServicio'];
                if($mes == 0 || $mes == 7 || $mes == 15){
                    $fecha_vencimiento = "DATE_ADD( '$fechaI', INTERVAL ".$mes." DAY)";
                    $fechaA = date("d/m/Y",strtotime($fechaI."+ ".$mes." days"));
                }else{
                    $fecha_vencimiento = "DATE_ADD( '$fechaI', INTERVAL ".$mes." MONTH)";
                    $fechaA = date("d/m/Y",strtotime($fechaI."+ ".$mes." month"));
                }
            
            $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(),'Paypal',0.00,'Paypal',0.00,$id_sucursal,$visible,$fecha_vencimiento,0)";
            

            if ($conn->query($query_pagos) === TRUE) {
                if($opcion == '97'){
                    $querySocio = "UPDATE socios SET Activo = 1 WHERE idSocio = $id_cliente";
                    if($conn->query($querySocio) == TRUE){
                        $msgQuery = "&iexcl;Transacci&oacute;n Exitosa!";
                    }else{
                        $msgQuery = "error";
                    }
                }else{
                    $msgQuery = "&iexcl;Transacci&oacute;n Exitosa!";
                }   
              
              
            } else {
              $msgQuery = "Error al registrar su pago, cheque en Administraci&oacute;n";
            } 
            //$conn->close();
        }else{
            //$conn->close();
            $msgQuery = 'Error al registrar su pago, cheque en Administraci&oacute;n';
        } ?>
        <div class="padre">
            <p class="hijo" style="text-align: center;">
                <img src="https://logos-marcas.com/wp-content/uploads/2020/04/PayPal-Logo.png" alt="PayPal-Logo" width="180px">
            </p>
            <p class="hijo" style="text-align: center; color: #73E45E; 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 $msgQuery; ?></h3>
        </div>
        <div class="padre recibo">
            <img src="https://logos-marcas.com/wp-content/uploads/2020/04/PayPal-Logo.png" alt="PayPal-Logo" width="100px">
            <p> Gracias por su pago!</p>
            <p><?php echo $hoy; ?></p>
            <hr>
            <p><b>ID de pago:</b> <?php echo $paymentId;?></p>
            <p><?php echo '<b>Nombre:</b> '.$payment->payer->payer_info->first_name.' '.$payment->payer->payer_info->last_name;?></p>
            <p><?php echo '<b>Correo electronico:</b> '.$payment->payer->payer_info->email?></p>
            <hr>
            <p><b>FECHAS</b></p>
            <div class="table-responsive">
                <table class="table">
                  <thead>
                    <tr>
                      <th scope="col"><b>Fecha de vencimiento anterior:</b></th>
                      <th scope="col"><b>Fecha de vencimiento actual:</b></th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr>
                      <td><?php echo date("d/m/Y", strtotime($fechaI)); ?></td>
                      <td><?php echo $fechaA; ?></td>
                    </tr>
                  </tbody>
                </table>
            </div>
            <p><b>PAGO</b></p>
            <div class="table-responsive">
                <table class="table">
                  <thead>
                    <tr>
                      <th scope="col">Descripcion</th>
                      <th scope="col">Costo</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr>
                      <td><?php echo $desc_plan; ?></td>
                      <td><?php echo $costo.' MXN';?></td>
                    </tr>
                  </tbody>
                </table>
            </div>
            
            <div class="table-responsive">
                <table class="table">
                  <thead>
                    <tr>
                      <th scope="col"></th>
                      <th scope="col"></th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr>
                      <td><b>TOTAL</b></td>
                      <td><?php echo $costo?></td>
                    </tr>
                  </tbody>
                </table>
            </div>
            <hr>
            <p><b>Pago via PayPal</b></p>
        </div>
      <? //php $conn->close();
    //echo "Get Payment", "Payment", $payment->getId(), null, $payment;
     $conn->close();
    return $payment;
    }else{ //$msg2 = "User Cancelled the Approval", null; ?>
        
        <div class="padre">
            <p class="hijo" style="text-align: center;">
                <img src="https://logos-marcas.com/wp-content/uploads/2020/04/PayPal-Logo.png" 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>
            <h3 class="hijo" style="text-align: center;"><?php echo $msgQuery; ?></h3>
        </div> 
    <?php
        //exit;
    }
    ?>
 </div>
</body>    
</html>