<?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 
            redes_sociales_gym.zona_horaria,
            zonasHorarias.pais,
            zonasHorarias.utc
        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.BaseDatos = '$bdC'
        LIMIT 1";
        $stmt = $conn->prepare($query_zonaHoraria);
        $stmt->execute();
        $rs = $stmt->get_result();
        
        $pais = "Mexico";
        $zonaHoraria = "America/Mexico_City";
        
        if ($rs->num_rows > 0) {
            $rowZona = $rs->fetch_assoc();
        
            $pais = $rowZona['pais'];
        
            if (!empty($rowZona['zona_horaria'])) {
                $zonaHoraria = $rowZona['zona_horaria'];
            }
        }
        
        if (!in_array($zonaHoraria, timezone_identifiers_list())) {
            $zonaHoraria = "America/Mexico_City";
        }
        
        date_default_timezone_set($zonaHoraria);

    $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;
  $titulo_item = "";
  $item_id = "";
  
  
  //TRAER DATOS DEL CLIENTE
  
      $connDatosClientes = new mysqli(
        "directoriofitness.com.mx",
        "direct18",
        "L4LL4v3M@3str@",
        $bd
    );
    
    $connDatosClientes->set_charset("utf8");
    
    $nombreCliente = "";
    $apellidoCliente = "";
    $emailCliente = "";
    $fechaRegistroCliente = "";
    
    $id_cliente_safe = (int)$id_cliente;
    
    $queryCliente = "
        SELECT 
            Nombre,
            Apellidos,
            Email,
            FechaIngreso
        FROM socios
        WHERE idSocio = $id_cliente_safe
        LIMIT 1
    ";
    
    $resultCliente = $connDatosClientes->query($queryCliente);
    
    if ($resultCliente && $resultCliente->num_rows > 0) {
        $rowCliente = $resultCliente->fetch_assoc();
    
        $nombreCliente = trim($rowCliente['Nombre']);
        $apellidoCliente = trim($rowCliente['Apellidos']);
        $emailCliente = trim($rowCliente['Email']);
    
        if (!empty($rowCliente['FechaIngreso'])) {
            $fechaRegistroCliente = date('c', strtotime($rowCliente['FechaIngreso']));
        }
    }
    
    $connDatosClientes->close();
    
    $payerData = [
        "name" => $nombreCliente,
        "surname" => $apellidoCliente
    ];
    
    if (!empty($emailCliente)) {
        $payerData["email"] = $emailCliente;
    }
    
    if (!empty($fechaRegistroCliente)) {
        $payerData["registration_date"] = $fechaRegistroCliente;
    }


  
  //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=" . urlencode($plan) . "&tipo=planes&fecha_visita=$fecha_visita&paquete_clase=$paquete_clase&suc=$suc&opcion=$opcion";
  
      $titulo_item = $plan;
      $item_id = "PLAN_" . $id_servicio;
  
    }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=" . urlencode($concepto) . "&costo=$costo&idLocker=$idLocker&lock_asig=$lock_asig&suc=$suc&tipo=locker"; 

      $titulo_item = $concepto;
      $item_id = "LOCKER_" . $idLocker;
    }
    
    // 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
  */

  $preference_id = null;

  if($bandApi == TRUE){

      $external_reference = "MP_" . $bdC . "_" . $suc . "_" . $id_cliente . "_" . time();

        $body = [
            "items" => [
                [
                    "id" => $item_id,
                    "title" => $titulo_item,
                    "description" => "Pago de " . $titulo_item,
                    "category_id" => "services",
                    "quantity" => 1,
                    "currency_id" => "MXN",
                    "unit_price" => (float)$costo
                ]
            ],
            "payer" => $payerData,
            "expires" => true,
            "expiration_date_from" => date('c'),
            "expiration_date_to" => date('c', strtotime('+30 minutes')),
            "back_urls" => [
                "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/success.php?error=2"
            ],
            "auto_return" => "approved",
            "external_reference" => $external_reference,
            "notification_url" => "https://api.progymcloud.com/progymcloud_app/pagos/mercado_pago/webhook_mp.php?bd=" . urlencode($bd) . "&suc=" . urlencode($suc),
            "statement_descriptor" => "PROGYMCLOUD",
            "metadata" => [
                "bd" => $bd,
                "bdc" => $bdC,
                "suc" => $suc,
                "id_cliente" => $id_cliente,
                "tipo" => $tipo,
                "id_servicio" => $id_servicio,
                "importe" => $costo,
                "plan" => $plan,
                "fecha_visita" => $fecha_visita,
                "paquete_clase" => $paquete_clase,
                "opcion" => $opcion,
                "concepto" => $concepto,
                "id_locker" => $idLocker,
                "lock_asig" => $lock_asig
            ]
        ];

      $headers = [
          "Content-Type: application/json",
          "Authorization: Bearer " . $ACCESS_TOKEN,
          "X-Idempotency-Key: " . uniqid("mp_", true),
          "X-Integrator-Id: dev_4b9deb9a00bf11edbed90242ac130004",
          "X-Platform-Id: dev_d10bfd63060611f1a6c9ea96417070b3"
      ];

      $ch = curl_init("https://api.mercadopago.com/checkout/preferences");

      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_POST, true);
      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
      curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));

      $response = curl_exec($ch);
      $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
      $errorCurl = curl_error($ch);

      curl_close($ch);

      $resultado = json_decode($response, true);

      if ($errorCurl || $httpCode < 200 || $httpCode >= 300 || !isset($resultado["id"])) {
          error_log("ERROR MP CREATE PREFERENCE HTTP: " . $httpCode);
          error_log("ERROR MP CURL: " . $errorCurl);
          error_log("ERROR MP RESPONSE: " . $response);

          $bandApi = FALSE;
      }else{
          $preference_id = $resultado["id"];
              file_put_contents(
        __DIR__ . "/mp_debug.log",
        date("Y-m-d H:i:s") . "\n" .
        "MP OK preference_id: " . $preference_id . "\n" .
        "MP OK external_reference: " . $external_reference . "\n" .
        "MP OK idempotency usado: " . $headers[2] . "\n" .
        "MP OK integrator usado: " . $headers[3] . "\n" .
        "MP OK platform usado: " . $headers[4] . "\n" .
        "MP RESPONSE: " . $response . "\n\n",
        FILE_APPEND
    );
    
    file_put_contents(
    'body_debug.log',
    date('Y-m-d H:i:s') . "\n" .
    json_encode(
        $body,
        JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE
    ) . "\n\n",
    FILE_APPEND
);
      }
  }


  
  // 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 && !empty($preference_id)){ 
            
                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>