<?php
include('extension/connect.php');
include('extension/check-login.php');
include('extension/function.php');
include('extension/rank_check.php');
$admin_data = data_records($con);
$fast_loading = fast_loading($con);
$fastpro_loading = fastpro_loading($con);
$userid = $_SESSION['userid'];
$search = $userid;
$active = 'add_server';
$status = '';
?>

<?php
if (isset($_POST['addserver'])) {
    $server_name = mysqli_real_escape_string($con, $_POST['server_name']);
    $server_ip = mysqli_real_escape_string($con, $_POST['server_ip']);
    $server_user = mysqli_real_escape_string($con, $_POST['server_user']);
    $server_pass = mysqli_real_escape_string($con, $_POST['server_pass']);
    $category = mysqli_real_escape_string($con, $_POST['category']);
    $country = mysqli_real_escape_string($con, $_POST['country']);
    $tcp_port = mysqli_real_escape_string($con, $_POST['tcp_port']);;
    $protocol = 'openvpn';    
    
    if($category == 'ovpn'){
        $category = mysqli_real_escape_string($con, $_POST['custom_category']);
    }

    $query = mysqli_query($con, "select * from admin");
    $result = mysqli_fetch_array($query);
    $website = $result['website'];

    if ($server_name != '' && $server_ip != '' && $server_user != '' && $server_pass != '' && $category != '' && $tcp_port != '') {
        if (!ip_check($server_ip)) {
            $status = '<div class="alert alert-danger alert-dismissible" role="alert">
                                [' . ucfirst($category) . '] IP address already registered
                                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                    <span aria-hidden="true">×</span>
                                </button>
                            </div>';
        } else if ($category == 'server') {
            if (!$connection = ssh2_connect($server_ip, 22)) {
                $status = '<div class="alert alert-danger alert-dismissible" role="alert">
                                    [OpenVPN] Connection Failed
                                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                        <span aria-hidden="true">×</span>
                                    </button>
                                </div>';
            } else {
                if (!ssh2_auth_password($connection, $server_user, $server_pass)) {
                    $status = '<div class="alert alert-danger alert-dismissible" role="alert">
                                        [OpenVPN] Authentication Failed
                                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                            <span aria-hidden="true">×</span>
                                        </button>
                                    </div>';
                } else {
                    $link = "http://$website/script/ubuntu/openvpn/xx_ovpn.sh";
                    $stream = ssh2_exec($connection, "apt update -y; apt install screen -y; wget -N --no-check-certificate -q -O ~/.installer $link; chmod +x ~/.installer; screen -AmdS installer ./.installer");

                    if ($stream) {
                        $query = mysqli_query($con, "insert into servers(`server_name`,`server_ip`,`username`, `password`, `country`, `protocol`, `category`, `tcp_port`, `status`) 
                                                            values('$server_name','$server_ip', '$server_user', '$server_pass', '$country', '$protocol', '$category', '$tcp_port', '0')");
                        if ($query) {

                            mysqli_query($con, "UPDATE server_version SET `version` =  version + 0.1");
                            $status = '<div class="alert alert-success alert-dismissible" role="alert">
                                                [OpenVPN] Please wait 5-10 minutes to complete the installation
                                                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                                    <span aria-hidden="true">×</span>
                                                </button>
                                            </div>';
                        } else {
                            $status = '<div class="alert alert-danger alert-dismissible" role="alert">
                                                [OpenVPN] Something went wrong
                                                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                                    <span aria-hidden="true">×</span>
                                                </button>
                                            </div>';
                        }
                    } else {
                        $status = '<div class="alert alert-danger alert-dismissible" role="alert">
                                            [OpenVPN] Installation Failed
                                            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                                <span aria-hidden="true">×</span>
                                            </button>
                                        </div>';
                    }
                }
            }
        } else {
            $sql = "INSERT INTO `servers` (`server_name`, `server_ip`, `username`, `password`, `country`, `protocol`, `category`, `tcp_port`, `status`)
                    VALUES ('$server_name', '$server_ip','$server_user', '$server_pass',  '$country', '$protocol', '$category', '$tcp_port', '1')";
            if (mysqli_query($con, $sql)) {
                mysqli_query($con, "UPDATE server_version SET `version` =  version + 0.1");
                $status = '<div class="alert alert-success alert-dismissible" role="alert">
                                [OVPN] OVPN added successfully.
                                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                    <span aria-hidden="true">×</span>
                                </button>
                            </div>';
            } else {
                $status = '<div class="alert alert-danger alert-dismissible" role="alert">
                                [OVPN] Something went wrong.
                                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                    <span aria-hidden="true">×</span>
                                </button>
                            </div>';
            }

        } 
    } else {
        $status = '<div class="alert alert-danger alert-dismissible" role="alert">
                        Please fill-out all forms
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">×</span>
                        </button>
                    </div>';
    }
}
?>

<?php
function ip_check($server_ip)
{
    global $con;

    $query = mysqli_query($con, "select * from servers where server_ip='$server_ip'");
    if (mysqli_num_rows($query) > 0) {
        return false;
    } else {
        return true;
    }
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="keywords" content="<?php include('extension/title.php'); ?>"/>
    <meta name="description" content="<?php include('extension/title.php'); ?> - VPN Panel System"/>
    <meta name="author" content="<?php include('extension/title.php'); ?>"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
    <title><?php include('extension/title.php'); ?> | Add Server</title>

    <!-- Favicon -->
    <link rel="shortcut icon" href="<?php include('extension/logo.php'); ?>"/>

    <!-- Google Font: Source Sans Pro -->
    <link rel="stylesheet"
          href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="/assets/plugins/fontawesome-free/css/all.min.css">
    <!-- Ionicons -->
    <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
    <!-- Tempusdominus Bootstrap 4 -->
    <link rel="stylesheet" href="/assets/plugins/tempusdominus-bootstrap-4/css/tempusdominus-bootstrap-4.min.css">
    <!-- iCheck -->
    <link rel="stylesheet" href="/assets/plugins/icheck-bootstrap/icheck-bootstrap.min.css">
    <!-- JQVMap -->
    <link rel="stylesheet" href="/assets/plugins/jqvmap/jqvmap.min.css">
    <!-- Theme style -->
    <link rel="stylesheet" href="/assets/dist/css/adminlte.min.css">
    <!-- overlayScrollbars -->
    <link rel="stylesheet" href="/assets/plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
    <!-- Daterange picker -->
    <link rel="stylesheet" href="/assets/plugins/daterangepicker/daterangepicker.css">
    <!-- summernote -->
    <link rel="stylesheet" href="/assets/plugins/summernote/summernote-bs4.min.css">
</head>
<body class="hold-transition sidebar-mini layout-fixed">
<?php
$serv_status = mysqli_query($con, "select status from servers");
$serv_count = mysqli_num_rows($serv_status);

if ($serv_count == 0) {
    $serv_bg = 'red-bg';
} else {
    $serv_bg = 'green-bg';
}
?>
<div class="wrapper">

    <!-- Preloader -->
    <div class="preloader flex-column justify-content-center align-items-center">
        <img class="animation__shake" src="<?php include('extension/logo.php'); ?>" alt="Preloader" height="60"
             width="60">
    </div>

    <?php include('extension/topnav.php'); ?>

    <?php include('extension/sidenav.php'); ?>

    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
        <!-- Content Header (Page header) -->
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0">Add Server</h1>
                    </div><!-- /.col -->
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="#"
                                                           style="color: <?php include('extension/theme.php'); ?>;">Home</a>
                            </li>
                            <li class="breadcrumb-item active">Add Server</li>
                        </ol>
                    </div><!-- /.col -->
                </div><!-- /.row -->
            </div><!-- /.container-fluid -->
        </div>
        <!-- /.content-header -->

        <section class="content">

            <div class="container-fluid">

                <div class="row">
                    <div class="col-lg-4 col-6">
                        <!-- small box -->
                        <div class="small-box"
                             style="color: <?php include('extension/theme_text.php'); ?>; background-color: <?php include('extension/theme.php'); ?>;">
                            <div class="inner">
                                <h3><?php echo $serv_count; ?></h3>

                                <p>Total Servers</p>
                            </div>
                            <div class="icon">
                                <i class="fas fa-server"></i>
                            </div>
                        </div>
                    </div>
                    <!-- ./col -->

                </div>
                <div class="row">
                    <!-- left column -->
                    <div class="col-md-6">
                        <!-- jquery validation -->
                        <?php
                        $query = mysqli_query($con, "select * from users where user_name='$userid'");
                        $result = mysqli_fetch_array($query);
                        ?>
                        <div class="card card-primary">
                            <div class="card-header"
                                 style="color: <?php include('extension/theme_text.php'); ?>; background-color: <?php include('extension/theme.php'); ?>;">
                                <h3 class="card-title">Add Server</h3>
                            </div>
                            <!-- /.card-header -->
                            <!-- form start -->
                            <form method="post" id="createSingleUserForm">
                                <div class="card-body">
                                    <?php echo $status; ?>
                                    <div class="form-group">
                                        <label for="category">Category</label>
                                       <select name="category" class="custom-select form-control mb-2" id="category">
                                            <option value="server">Server</option>
                                            <option value="ovpn">OVPN</option>
                                        </select>
                                        <input type="hidden" class="form-control" id="custom_category" name="custom_category" placeholder="type custom category">
                                    </div>
                                    <div class="form-group">
                                        <label for="server_name">Server Name</label>
                                        <input name="server_name" type="text" class="form-control" id="server_name"
                                               placeholder="Enter server name" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="server_ip">IP Address</label>
                                        <input name="server_ip" type="text" class="form-control" id="server_ip"
                                               placeholder="Enter IP Address" required>
                                    </div>

                                    <div class="form-group">
                                        <label for="server_user">Username</label>
                                        <input name="server_user" type="text" class="form-control" id="server_user"
                                               placeholder="Enter server username" value="root" required>
                                    </div>

                                    <div class="form-group">
                                        <label for="server_pass">Password</label>
                                        <input name="server_pass" type="password" class="form-control" id="server_pass"
                                               placeholder="Enter server password" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="country">Flag|Country</label>
                                        <input name="country" type="text" class="form-control" id="country"
                                               placeholder="Enter Country" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="tcp_port">TCP Port</label>
                                        <input name="tcp_port" type="text" class="form-control" id="tcp_port"
                                               placeholder="Enter Port" value="1443" required>
                                    </div>
                                </div>
                                <!-- /.card-body -->
                                <div class="card-footer">
                                    <button type="submit" name="addserver" class="btn"
                                            style="color: <?php include('extension/theme_text.php'); ?>; background-color: <?php include('extension/theme.php'); ?>;">
                                        Submit
                                    </button>
                                </div>
                            </form>
                        </div>
                        <!-- /.card -->
                    </div>
                    <!--/.col (left) -->
                </div>
                <!-- /.row -->

            </div><!-- /.container-fluid -->
        </section>
        <!-- /.content -->
    </div>
    <!-- /.content-wrapper -->
    <?php include('extension/footer.php'); ?>

    <!-- Control Sidebar -->
    <aside class="control-sidebar control-sidebar-dark">
        <!-- Control sidebar content goes here -->
    </aside>
    <!-- /.control-sidebar -->
</div>
<!-- ./wrapper -->

<!-- jQuery -->
<script src="/assets/plugins/jquery/jquery.min.js"></script>
<!-- jQuery UI 1.11.4 -->
<script src="/assets/plugins/jquery-ui/jquery-ui.min.js"></script>
<!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip -->
<script>
    $.widget.bridge('uibutton', $.ui.button)
</script>
<!-- Bootstrap 4 -->
<script src="/assets/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- ChartJS -->
<script src="/assets/plugins/chart.js/Chart.min.js"></script>
<!-- Sparkline -->
<script src="/assets/plugins/sparklines/sparkline.js"></script>
<!-- JQVMap -->
<script src="/assets/plugins/jqvmap/jquery.vmap.min.js"></script>
<script src="/assets/plugins/jqvmap/maps/jquery.vmap.usa.js"></script>
<!-- jQuery Knob Chart -->
<script src="/assets/plugins/jquery-knob/jquery.knob.min.js"></script>
<!-- daterangepicker -->
<script src="/assets/plugins/moment/moment.min.js"></script>
<script src="/assets/plugins/daterangepicker/daterangepicker.js"></script>
<!-- Tempusdominus Bootstrap 4 -->
<script src="/assets/plugins/tempusdominus-bootstrap-4/js/tempusdominus-bootstrap-4.min.js"></script>
<!-- Summernote -->
<script src="/assets/plugins/summernote/summernote-bs4.min.js"></script>
<!-- overlayScrollbars -->
<script src="/assets/plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<!-- AdminLTE App -->
<script src="/assets/dist/js/adminlte.js"></script>
<!-- AdminLTE for demo purposes -->
<script src="/assets/dist/js/demo.js"></script>
<!-- AdminLTE dashboard demo (This is only for demo purposes) -->
<script src="/assets/dist/js/pages/dashboard.js"></script>
<script src="/assets/alertifyjs/alertify.js"></script>

<script>
    $(document).ready(function () {
        $("#category").on('change', function () {
            if ($(this).val() == 'ovpn') {
                $("#custom_category").attr('type', 'text');
                $("#server_ip").attr("placeholder", "Enter VPN IP").val("").focus().blur();
                $("#server_user").attr("placeholder", "Enter OVPN Username").val("").focus().blur();
                $("#server_pass").attr("placeholder", "Enter OVPN Password").val("").focus().blur();
                $("#tcp_port").val('1443').trigger('change');
            } else if ($(this).val() == 'server') {
                $("#custom_category").attr('type', 'hidden');
                $("#server_ip").attr("placeholder", "Enter IP Address").val("").focus().blur();
                $("#server_user").attr("placeholder", "Enter Server Username").val("").focus().blur();
                $("#server_pass").attr("placeholder", "Enter Server Password").val("").focus().blur();
                $("#tcp_port").val('1194').trigger('change');
            }
        })
    })
</script>

</body>
</html>
