<?php
    
    require "payment-api/lib/Twocheckout.php";
    require "../registro_pagos_visita.php";
    
    
    $seller_id = '251206854467';
    $publishable_key = '6965F831-0BFC-4545-A657-1EFA995FAE42';
    $private_key = '3BEFBF06-BF47-4939-9300-82CB343C8E97';
    
    //4242424242424242
    $localhost = "directoriofitness.com.mx";
    $user = "direct18";
    $passwd = "L4LL4v3M@3str@";
    
    /*$token = $_POST['token'];
    $importe = $_POST['importe'];
    $nombre = $_POST['nombre'];
    $apellido = $_POST['apellido'];
    $tel = $_POST['tel'];
    $domi = $_POST['domi'];
    $col = $_POST['colonia'];
    $cp = $_POST['cp'];*/
    $token = $_POST['token'];
    $prueba = $_POST['prueba'];
    $bd = str_replace('_', ' ', $_POST['bd']);
    $id_cliente = 0;
    $id_servicio = str_replace('_', ' ', $_POST['plan']);
    $plan = str_replace('_', ' ', $_POST['plan']);
    $importe = str_replace('_', ' ', $_POST['importe']);
    $nombre = str_replace('_', ' ', $_POST['nombre']);
    $apellido = str_replace('_', ' ', $_POST['apellido']);
    $fechaN = str_replace('_', ' ', $_POST['fechaN']);
    $email = str_replace('_', ' ', $_POST['email']);
    $tel = str_replace('_', ' ', $_POST['tel']);
    $domi = str_replace('_', ' ', $_POST['domi']);
    $col = str_replace('_', ' ', $_POST['colonia']);
    $cp = str_replace('_', ' ', $_POST['cp']);
    $genero = str_replace('_', ' ', $_POST['genero']);
    $fechaR = $_POST['fechaR'];
    $sucursal = str_replace('_', ' ', $_POST['sucursal']);
    $qr = $_POST['qr'];
    
    $conn = new mysqli($localhost,$user,$passwd, 'direct18_'.$bd);
    mysqli_set_charset($conn, 'utf8');
    $query = "SELECT pagos.idPago as 'folio' FROM pagos ORDER BY pagos.idPago DESC LIMIT 1";
    $stmt = $conn->prepare($query);
    //$stmt->bind_param('s', $gym);
    $stmt->execute();
    $rs = $stmt->get_result();
    $row = mysqli_fetch_array($rs, MYSQLI_ASSOC);
    $folio = $row["folio"] + 1;
    $conn->close();
    
    //echo $folio;
    
    // Your sellerId(account number) and privateKey are required to make the Payment API Authorization call.
    Twocheckout::privateKey($private_key);
    Twocheckout::sellerId($seller_id);

    // To use your sandbox account set sandbox to true
    Twocheckout::sandbox(true);
    try {
        $array_charge = array(
                "sellerId" => $seller_id,
                "merchantOrderId" => $folio,
                "token" => $token,
                "currency" => 'MXN',
                "total" => $importe,
                "billingAddr" => array(
                    "name" => 'Testing Tester',
                    "addrLine1" => 'Aguascalientes',
                    "city" => 'Aguascalientes',
                    "state" => 'Aguascalientes',
                    "zipCode" => '20660',
                    "country" => 'MEX',
                    "email" => $email,
                    "phoneNumber" => $tel
                ),
                "shippingAddr" => array(
                    "name" => 'Testing Tester',
                    "addrLine1" => 'Aguascalientes',
                    "city" => 'Aguascalientes',
                    "state" => 'Aguascalientes',
                    "zipCode" => '20660',
                    "country" => 'MEX',
                    "email" => $email,
                    "phoneNumber" => $tel
                )
            );
        //4242424242424242
        $charge_a = array(
                "merchantOrderId" => $folio,
                "token"      => $token,
                "currency"   => 'MXN',
                "total"      => $importe,
                "billingAddr" => array(
                    "name" => $nombre.' '.$apellido,
                    "addrLine1" => $domi,
                    "city" => 'Aguascalientes',
                    "state" => 'Aguascalientes',
                    "zipCode" => $cp,
                    "country" => 'MEX',
                    "email" => $email,
                    "phoneNumber" => $tel
                )
            );
        
        /*try{
            
        }catch(Exception $e){
            echo 'error => '.$e."\n";
            echo json_encode(array(
                "merchantOrderId" => $folio,
                "token"      => $token,
                "currency"   => 'MXN',
                "total"      => $importe,
                "billingAddr" => array(
                    "name" => $nombre.' '.$apellido,
                    "addrLine1" => $domi,
                    "city" => 'Aguascalientes',
                    "state" => 'Aguascalientes',
                    "zipCode" => $cp,
                    "country" => 'MEX',
                    "email" => $email,
                    "phoneNumber" => $tel
                )
            ));
        }*/
        
        //echo json_encode($array_charge);
        //$charge = Twocheckout_Charge::auth($charge_a);
        //echo json_encode($charge['response']);
        $charge = Twocheckout_Charge::auth($array_charge);//4242424242424242
        if ($charge['response']['responseCode'] == 'APPROVED' || $prueba == '1') {
            //echo "Thanks for your Order! ".$bd,$id_cliente,$id_servicio,$plan,$importe,$nombre,$apellido,$fechaN,$email,$tel,$domi,$col,$cp,$genero,$fechaR,$sucursal,$qr,"2Chk";
          $obj = new PagoVisitaReg();//$bd,$id_cliente,$id_servicio,$plan,$importe,$fechaN,$nombre,$apellido,$email,$tel,$domi,$col,$cp,$genero,$fechaR,$sucursal,$qr,$forma
            $t = $obj -> registrarPago($bd,$id_cliente,$id_servicio,$plan,$importe,$fechaN,$nombre,$apellido,$email,$tel,$domi,$col,$cp,$genero,$fechaR,$sucursal,$qr,"2Chk"); ?>
            
            <!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.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
              <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
              <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>
            
              <title>Mercado Pago</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">
                <div class="padre">
                  <p class="hijo" style="text-align: center;">
                    <img src="https://tribulant.com/docs/wp-content/uploads/2checkout-logo-blue-green.png" alt="twoco-Logo" width="130px">
                  </p>
                  
                     <?php
                        if($t == 1){ ?>
                            <p class="hijo" style="text-align: center; color: #00E013; font-size: 70px;">  
                                <i class="fas fa-check-circle"></i>
                                <h3 class="hijo" style="text-align: center;">Transaccion Exitosa</h3>
                            </p>
                    <?php }else{ ?>
                    
                            <p class="hijo" style="text-align: center; color: #D3000A; font-size: 70px;">  
                                <i class="fas fa-times-circle"></i>
                                <h3 class="hijo" style="text-align: center;">Error al registrar tu pago <?= $t ?></h3>
                            </p>
                    <?php } ?>
                  
                  
                </div>
              </div>
            
            </body>
            </html> 
        
        <?php }
    } catch (Twocheckout_Error $e) {
        echo $e->getMessage(), " ",$charge;
    }

?>