<?php

  require 'vendor/autoload.php';
  
  $access_token = 'TEST-3311809027950880-061115-e08e384a6c5151c92ddf1f5b4b0e3d66-774035859';  
  
  $suc = $_GET['suc'];
  $bd = trim($_GET['bd']);
  
  $opBD = explode("_",$bd);
  $bdC = $opBD[1];
  
  $bandApi = TRUE;
  $PUBLIC_KEY;
  $ACCESS_TOKEN;
  $conn = new mysqli("directoriofitness.com.mx","direct18","L4LL4v3M@3str@",'direct18_ProGymCloud');
  $conn -> set_charset("utf8");
    $queryApi = "SELECT info_mercadopago.*, info_plataformaspago.activar_mercadopago 
                    FROM info_mercadopago 
                INNER JOIN gimnasios ON info_mercadopago.gimnasio_idGimnasio = gimnasios.idGimnasio 
                INNER JOIN info_plataformaspago ON info_plataformaspago.gimnasio_idGimnasio = gimnasios.idGimnasio 
                WHERE gimnasios.BaseDatos = '$bdC' AND info_mercadopago.sucursal_idSucursal = '$suc' limit 1";
    $resultApi = $conn->query($queryApi);
    $conn -> set_charset("utf8");
    
    
    if ($resultApi->num_rows > 0){
        
        $row = $resultApi->fetch_assoc();
    
        $PUBLIC_KEY = $row['public_key'];
        
        $ACCESS_TOKEN = $row['access_token'];
    }else{
        $bandApi = FALSE;
    }
    
    $idg = $_GET['centro'];
    $query_zonaHoraria = "
        SELECT zonasHorarias.pais 
        FROM redes_sociales_gym 
        JOIN zonasHorarias 
            ON zonasHorarias.zonahoraria = redes_sociales_gym.zona_horaria 
        JOIN gimnasios 
            ON gimnasios.idGimnasio = redes_sociales_gym.gimnasio_idGym 
        WHERE gimnasios.Clave  = '$bdC'";
    $stmt = $conn->prepare($query_zonaHoraria);
    //$stmt->bind_param('s', $idg);
    $stmt->execute();
    $rs = $stmt->get_result(); 
    $pais = "Mexico";
    if ($rs->num_rows > 0) {
        $row = $rs->fetch_assoc();
        $pais = $row['pais'];
    }

    $conn->close();

  MercadoPago\SDK::setAccessToken($ACCESS_TOKEN); 

  
  $preference = new MercadoPago\Preference();
 
  //"https://api.progymcloud.com/estaciones/Progymcloud_app/php/mercado_pago/index.php?bd=${widget.bd}&
  //flag=4&id_cliente=${widget.idCliente}&concepto=${widget.plan}&costo=${widget.costo}&idLocker=${widget.locker}
  //&lock_asig=${widget.lockerAsig}&suc=${widget.sucursal}&tipo=locker" 
  
  
  $id_cliente = $_GET['id_cliente'];
  $id_servicio;
  $costo;
  $plan;
  $tipo = $_GET['tipo'];
  $fecha_visita;
  $paquete_clase;
  $opcion;
  $url_redirect;
  $concepto;
  $idLocker;
  $lock_asig;
  
  //bd=${widget.bd}&flag=4&id_cliente=${widget.idCliente}&concepto=${widget.plan}&costo=${widget.costo}&
  //idLocker=${widget.locker}&lock_asig=${widget.lockerAsig}&suc=${widget.sucursal}&tipo=locker
  
    if($tipo == 'planes'){
      $id_servicio = $_GET['id_servicio'];
      $costo = (float)$_GET['importe'];
      $plan = trim($_GET['plan']);
      $tipo = $_GET['tipo'];
      $fecha_visita = $_GET['fecha_visita'];
      $paquete_clase = $_GET['paquete_clase'];
      $opcion = $_GET['opcion'];
      $url_redirect = "https://api.progymcloud.com/progymcloud_app/pagos/mercado_pago/success.php?error=0&bd=$bd&flag=4&id_cliente=$id_cliente&id_servicio=$id_servicio&importe=$costo&plan=$plan&tipo=planes&fecha_visita=$fecha_visita&paquete_clase=$paquete_clase&suc=$suc&opcion=$opcion";
  
    }else{
      $concepto = $_GET['concepto'];
      $costo = (float)$_GET['costo'];
      $idLocker = $_GET['idLocker'];
      $lock_asig = $_GET['lock_asig'];
      
      $url_redirect = "https://api.progymcloud.com/progymcloud_app/pagos/mercado_pago/success.php?error=0&bd=$bd&flag=4&id_cliente=$id_cliente&concepto=$concepto&costo=$costo&idLocker=$idLocker&lock_asig=$lock_asig&suc=$suc&tipo=locker"; 
    }
    
    //echo json_encode($preference);
    
  # Building an item
  $preference->back_urls = array(
      "success" => $url_redirect,
      "failure" => "https://api.progymcloud.com/progymcloud_app/pagos/mercado_pago/failure.php?error=1",
      "pending" => "https://api.progymcloud.com/progymcloud_app/pagos/mercado_pago/failure.php?error=2"
  );
  
  //echo json_encode($preference);
  
  $preference->auto_return = "approved";

  $item = new MercadoPago\Item();
  $item->id = "00001";
  $item->title = "pago mercado libre"; 
  $item->quantity = 1;
  $item->unit_price = $costo;
  
  $preference->items = array($item);
  
  $preference->save(); # Save the preference and send the HTTP Request to create


  
  // echo json_encode($preference);
  # Return the HTML code for button
 //{"id":775498255,"nickname":"TESTBOISC5EI","password":"qatest8511",
 //"site_status":"active","email":"test_user_54574451@testuser.com"} //vendedor
 
 //{"id":775498915,"nickname":"TETE2436608","password":"qatest785",
    //"site_status":"active","email":"test_user_82460305@testuser.com"} //comprador
?>
<!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">
    <title>Document</title>
</head>
<style>
    .padre {

    padding: 0 1rem;
    margin: 1rem;
    }

    .hijo {
        /* IMPORTANTE */
        width: 200px;
        margin-left: auto;
        margin-right: auto;
    }
    .recibo{
        border-style: ridge;
    }
    .boton{
        text-align: center; 
    }
</style>
<body>
    <div classs="padre">
        <div class="hijo">
            <?php if($bandApi == TRUE){ 
            
                function obtenerDominioMercadoPago($pais) {
                    $mapa = [
                        'Mexico' => 'com.mx',
                        'Argentina' => 'com.ar',
                        'Brasil' => 'com.br',
                        'Chile' => 'cl',
                        'Colombia' => 'com.co',
                        'Peru' => 'com.pe',
                        'Uruguay' => 'com.uy'
                    ];
                
                    return $mapa[$pais] ?? "com.mx";
                }
                $dominio = obtenerDominioMercadoPago($pais);
                $URI = "https://www.mercadopago.$dominio/integrations/v1/web-payment-checkout.js";
            ?>
                <form action="/procesar-pago" method="POST" id="myform" name="myform"> 
                    </p class="boton"><script
                        src="<?php echo $URI; ?>"
                        data-preference-id="<?= $preference->id ?>"> 
                        
                    </script>  </p>
                </form>
            <?php }else{ ?>
                <h2>Forma de pago no disponible, favor de revisar en Administracion</h2>
            
            <?php } ?>
            
            <!-- Inicializa el checkout -->

        </div>
    </div>
</body>
</html>