<?php
session_start();
if($_SESSION['loggedin']){
        $foto=$_SESSION['icon'];
        $gym=$_SESSION['gym'];
        $idg = $_SESSION['idg'];
        $cliente = $_SESSION['num_cliente'];
        $nombre_cliente = $_SESSION['nombre'];
        $db = $_SESSION['db'];
        $img_socio = $_SESSION['foto'];
        
        require_once("./lib/Twocheckout.php");
        require '../../registro/registra_pago.php';
        
        //PRIMERO VAMOS A OBTENER TODOS LOS DATOS NECESARIO PARA REALIZAR LA VENTA
        // OBTENEMOS EL TOKEN CORRESPONDIENTE AL PRIVADO
        
        // TRAEMOS LOS DATOS DEL SERVIDOR PARA LA CONEXION A LA BD
        include("../../../mysql_connection/mysql_data.php");
        $server_data = new serverData;
        $servername = $server_data -> getServerName();
        $username = $server_data -> getUserName();
        $password = $server_data -> getPassword();
        $db = "direct18_ProGymCloud";
        $conn = new mysqli($servername,$username,$password, $db);
        mysqli_set_charset($conn, 'utf8');
        // **END
        
        // PRIMERO OBTENEMOS EL TOKEN DE PAYPAL
        $query = "SELECT num_cuenta as 'cuenta', private_key as 'privkey', public_key as 'pubkey' FROM info_checkout WHERE info_checkout.sucursal_idSucursal = ? AND info_checkout.activo = 1;";
        $stmt = $conn->prepare($query);
        $stmt->bind_param('i', $idg);
        $stmt->execute();
        $rs = $stmt->get_result();
        $row = mysqli_fetch_array($rs, MYSQLI_ASSOC);
        define("checkoutPrivateKey", $row['privkey']);
        $cuenta_gym = $row['cuenta'];
        
        mysqli_close($conn);
        
        // AHORA VAMOS A OBTENER EL ULTIMO FOLIO REGISTRADO
        $db = $_SESSION['db'];
        $conn = new mysqli($servername,$username,$password, $db);
        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;
        // VAMOS A OBTENER LOS DATOS DEL CLIENTE
        $query = "SELECT socios.Direccion as 'dom', socios.CodigoPostal as 'cp', socios.Email as 'correo', socios.TelefonoCelular as 'movil' FROM socios WHERE socios.idSocio = ?;";
        $stmt = $conn->prepare($query);
        $stmt->bind_param('s', $cliente);
        $stmt->execute();
        $rs = $stmt->get_result();
        $row = mysqli_fetch_array($rs, MYSQLI_ASSOC);
        $dom = $row["dom"];
        $dom = !empty($dom) ? $dom : "Sin Registrar.";
        $cp = $row["cp"];
        $cp = !empty($cp) ? $cp : "00000";
        $mail = $row["correo"];
        $mail = !empty($mail) ? $mail : "correonoregistrado@mail.com";
        $tel = $row["movil"];
        $tel = !empty($tel) ? $tel : "0000000000";
        $id_paquete = $_POST['idp'];
        $nombre_paquete = $_POST['np'];
        $importe = $_POST['importe'];
        $concepto = $_POST['concepto'];
        $fecha_vencimiento = $_POST['venci'];
        $n_concepto = $_POST['ncon'];
        $metodo_pago = "2Chk";
        
        /*echo "LA LLAVE PRIVADA: ".checkoutPrivateKey."<br>";
        echo "LA CUENTA DEL CLIENTE: ".$cuenta_gym."<br>";
        echo "EL ULTIMO FOLIO: ".$folio."<br>";
        echo "NOMBRE CLIENTE: ".$nombre_cliente."<br>";
        echo "domicilio CLIENTE: ".$dom."<br>";
        echo "TELEFONO CLIENTE: ".$tel."<br>";
        echo "CORREO CLIENTE: ".$mail."<br>";
        echo "IMPORTE: ".$importe."<br>";
        echo "CONCEPTO: ".$concepto."<br>";*/
        
        // ASIGNAMOS LOS DATOS PARA REALIZAR LA PETICION A LA API
        Twocheckout::privateKey(checkoutPrivateKey);
        Twocheckout::sellerId($cuenta_gym);
        Twocheckout::sandbox(false);
        try {
            $charge = Twocheckout_Charge::auth(array(
                "merchantOrderId" => $folio,
                "token"      => $_POST['token'],
                "currency"   => 'MXN',
                "total"      => $importe,
                "billingAddr" => array(
                    "name" => $nombre_cliente,
                    "addrLine1" => $dom,
                    "city" => 'Aguascalientes',
                    "state" => 'Aguascalientes',
                    "zipCode" => $cp,
                    "country" => 'MEX',
                    "email" => $mail,
                    "phoneNumber" => $tel
                )
            ));
        
            if ($charge['response']['responseCode'] == 'APPROVED') {
                $obj = new RegistraPago();
                $t = $obj -> registrarPago($db, $id_paquete, $cliente, $nombre_cliente, $idg, $gym, $nombre_paquete, $n_concepto, $concepto, $importe, $fecha_vencimiento, $metodo_pago);
                if($t == 0)
                    header('Location: ../gestionar_paquete.php?err=1');
                elseif($t == 2)
                    header('Location: ../gestionar_paquete.php?err=2');
                elseif($t == 1)
                    header('Location: ../gestionar_paquete.php?err=0');
                
            }
        } catch (Twocheckout_Error $e) { 
            header('Location: ../gestionar_paquete.php?err=3'); 
        }
        mysqli_close($conn);
}else{
    header('Location: ../index.php?err=3');
}
?>