<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include('extension/connect.php');
include('extension/check-login.php');
include('extension/function.php');
// The rest of your code...
$admin_data = data_records($con);
$fast_loading = fast_loading($con);
$fastpro_loading = fastpro_loading($con);
$userid = $_SESSION['userid'];
$search = $userid;
$active='create_user';
$status = '';
$status2 = '';
?>

<?php
if(isset($_POST['register'])){
  $user_name = mysqli_real_escape_string($con,$_POST['username']);
  $user_pass = mysqli_real_escape_string($con,$_POST['password']);
  $auth_pass = md5($user_pass);
  $validity = mysqli_real_escape_string($con,$_POST['duration']);
  $create = 0;
  
  $query = mysqli_query($con,"select * from users where user_id='$userid'");
  $row=mysqli_fetch_array($query);
  $my_credits = $row['user_credits'];

$kwery = mysqli_query($con,"select maintenance from admin");
$rows_kwery = mysqli_fetch_array($kwery);      
$maintenance_mode = $rows_kwery['maintenance'];
if($maintenance_mode == 0){ 
    
    if((preg_match('/^([a-z-A-Z-0-9])+$/i', $user_name)) !== 0){    
        if($user_name!='' && $user_pass!=''){
        
            if(username_check($user_name)){
                
                if($validity == 1){
                    $user_credits = 1;
                    $duration = 43200;
                    $descript = 'deducted 1 credit for creating user';
                }elseif($validity == 3){
                    $user_credits = 3;
                    $duration = 129600;
                    $descript = 'deducted 3 credit for creating user';
                }elseif($validity == 6){
                    $user_credits = 6;
                    $duration = 259200;
                    $descript = 'deducted 6 credit for creating user';
                }elseif($validity == 9){
                    $user_credits = 9;
                    $duration = 388800;
                    $descript = 'deducted 9 credit for creating user';
                }elseif($validity == 12){
                    $user_credits = 12;
                    $duration = 518400;
                    $descript = 'deducted 12 credit for creating user';
                }elseif($validity == 999){
                    $user_credits = 0;
                    $duration = 1440;
                    $descript = 'deducted 0 credit for creating trial user';
                }
                
                if($my_credits>$user_credits-1){
            
                    $query = mysqli_query($con,"insert into users(`full_name`,`user_name`,`user_pass`,`user_encryptedPass`,`user_duration`,`user_upline`,`user_rank`) 
                                        values('$user_name','$user_name','$user_pass','$auth_pass','$duration','$userid','normal')");
                    $query2 = mysqli_query($con,"insert into radcheck(`username`,`attribute`,`op`,`value`) values('$user_name','Cleartext-Password',':=','$user_pass')");     
                        if($query && $query2){
                            $qry = mysqli_query($con, "UPDATE users set user_credits = user_credits-'$user_credits' where user_id='$userid'");
                                if($qry){
                                    $update = mysqli_query($con,"insert into credit_log(`user_id`,`description`) values('$userid','$descript')");
                                        if($update){
                                            $copy = 'username:'.$user_name.' | password:'.$user_pass.'';
                                            $status = '<input type="text" value="'.$copy.'" id="myInput" style="position: absolute; top: -9999px; left: -9999px; opacity: 0;">
                                                        <div class="alert alert-success alert-dismissible" role="alert">
                                                            Account created successfully <button class="btn btn-warning btn-sm" onclick="myFunction()">copy</button>
                                                            <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">
                                                            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">
                                                    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">
                                            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">
                                    Not enough credits
                                    <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">
                                Username is taken
                                <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>';
        
        }
    }else{
        $status = '<div class="alert alert-danger alert-dismissible" role="alert">
                        Username is not valid.<br>
                        Only alphabets are allowed.
                        <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">
                    Site maintenance ongoing <br>
                    Try again later.
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>';
}
}elseif(isset($_POST['multiregister'])){
  $count = mysqli_real_escape_string($con,$_POST['count']);
  $prefix = mysqli_real_escape_string($con,$_POST['prefix']);
  $validity = mysqli_real_escape_string($con,$_POST['duration']);
  $create = 0;
  $num = 0;
  
  $query = mysqli_query($con,"select * from users where user_id='$userid'");
  $row=mysqli_fetch_array($query);
  $my_credits = $row['user_credits'];
  
  $descript2 = 'deducted '.$count.' credits for creating multi user';
  
  $sql = mysqli_query($con,"select * from users where user_name LIKE '$prefix%' ORDER BY user_name DESC LIMIT 1");
    
  $row_check = mysqli_fetch_array($sql) ;
  $kwery = mysqli_query($con,"select maintenance from admin");
  $rows_kwery = mysqli_fetch_array($kwery);      
  $maintenance_mode = $rows_kwery['maintenance'];
  if($maintenance_mode == 0){     
          if((preg_match('/^([a-z])+$/i', $prefix)) !== 0){   
          if($count!='' && $prefix!=''){
                
                if($my_credits>$count-1){
                    
                    $str = $row_check["user_name"];//"IVISA250532";
                    $int = preg_replace('/[^0-9]/', '',$str);//to get the Int from string '250532'
                    if (mysqli_num_rows($sql)>0) {
                        $pure_str = str_replace($int, "", $str);// tog get only the string word 'IVISA'
                    }else{
                        $pure_str = $prefix;
                    }
                    
                    while($num<$count)
                    {
                        $num++;
                        $user_credits = $count;
                        $ran_name = rand(0,999919);
                        $ran_name2 = rand(0,9999199);
                        $user_name = $prefix.$ran_name;
                        $user_pass	= $ran_name2;
                        $authpass = md5($user_pass);
                        $duration = 43200;
                        $int++;
                        $next_user_name = $pure_str.($int+1);
                    $query = mysqli_query($con,"insert into users(`full_name`,`user_name`,`user_pass`,`user_encryptedPass`,`user_duration`,`user_upline`,`user_rank`) values('$user_name','$user_name','$user_pass','$authpass','$duration','$userid','export')");
                    $query2 = mysqli_query($con,"insert into radcheck(`username`,`attribute`,`op`,`value`) values('$user_name','Cleartext-Password',':=','$user_pass')");
                    }
                    if($query && $query2){
                        $qry = mysqli_query($con, "UPDATE users set user_credits = user_credits-'$user_credits' where user_id='$userid'");
                            if($qry){
                                $update = mysqli_query($con,"insert into credit_log(`user_id`,`description`) values('$userid','$descript2')");
                                    if($update){
                                        $status2 = '<div class="alert alert-success alert-dismissible" role="alert">
                                                        '.$count.' accounts registered successfully!
                                                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                                            <span aria-hidden="true">×</span>
                                                        </button>
                                                    </div>';
                                    }else{
                                        $status2 = '<div class="alert alert-danger alert-dismissible" role="alert">
                                                        Something went wrong
                                                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                                            <span aria-hidden="true">×</span>
                                                        </button>
                                                    </div>';
                                    }
                            }else{
                                $status2 = '<div class="alert alert-danger alert-dismissible" role="alert">
                                                Something went wrong
                                                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                                    <span aria-hidden="true">×</span>
                                                </button>
                                            </div>';
                            }
                    }else{
                        $status2 = '<div class="alert alert-danger alert-dismissible" role="alert">
                                        Something went wrong
                                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                            <span aria-hidden="true">×</span>
                                        </button>
                                    </div>';
                    }
                }else{
        
                    $status2 = '<div class="alert alert-danger alert-dismissible" role="alert">
                                    Not enough credits
                                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                        <span aria-hidden="true">×</span>
                                    </button>
                                </div>';
                  }
        
          }
          else{
        
            $status2 = '<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>';
        
          }
          }else{
             $status2 = '<div class="alert alert-danger alert-dismissible" role="alert">
                            Prefix is not valid.<br>
                            Only alphabets are allowed.
                            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                <span aria-hidden="true">×</span>
                            </button>
                        </div>'; 
          }
}else{
    $status2 = '<div class="alert alert-danger alert-dismissible" role="alert">
                    Site maintenance ongoing <br>
                    Try again later.
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>';
}
}
?>

<?php 
function username_check($user_name){
  global $con;
  
  $query =mysqli_query($con,"select * from users where user_name='$user_name'");
  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'); ?> | Create User</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
    $query = mysqli_query($con,"select * from users where user_id='$userid'");
    $result = mysqli_fetch_array($query);
    
    //Total Users
    if($result['user_rank']=='superadmin'){
        $que = mysqli_query($con,"select user_name from users where user_rank='normal' || user_rank='export'");
    }else{
        $que = mysqli_query($con,"select user_name from users where (user_rank='normal' || user_rank='export') and user_upline='$userid'");
    }
    $client = mysqli_num_rows($que);
    
    if($client == 0){
        $desc = 'You have no users!';
    }else{
        $desc = 'View User(s)';
    }
    
    //Total Bulks
    if($result['user_rank']=='superadmin'){
        $que2 = mysqli_query($con,"select user_name from users where user_rank='export'");
    }else{
        $que2 = mysqli_query($con,"select user_name from users where user_rank='export' and user_upline='$userid'");
    }
    $client2 = mysqli_num_rows($que2);
    
    if($client2 == 0){
        $desc2 = 'You have no bulks!';
    }else{
        $desc2 = 'View Bulks(s)';
    }

    //Credits
    if($result['user_rank'] == 'superadmin'){
        $credits = '&#8734;';
        $cred_details = 'Unlimited Credits';
    }else{
        $credits = $result['user_credits'];
        $cred_details = 'Available Credit(s)';
    }
    
    if($result['user_credits'] > 0){
        $icon = 'text-success';
    }else{
        $icon = 'text-danger';
    }
    
?>
<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">Create User</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">Create User</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 $client; ?></h3>

                <p>Total users</p>
              </div>
              <div class="icon">
                <i class="fas fa-user-plus"></i>
              </div>
            </div>
          </div>
          <!-- ./col -->
          
          <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 $credits; ?></h3>

                <p>Credits</p>
              </div>
              <div class="icon">
                <i class="fas fa-coins"></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">Create Single User</h3>
              </div>
              <!-- /.card-header -->
              <!-- form start -->
              <form method="post" id="createSingleUserForm">
                <div class="card-body">
                  <?php echo $status; ?>
                  <div class="form-group">
                    <label for="username">Username</label>
                    <input pattern="[a-zA-Z0-9]+" title="only letters" name="username" type="text" class="form-control" id="username" placeholder="Enter Username">
                  </div>
                  <div class="form-group">
                    <label for="password">Password</label>
                    <input pattern="[a-zA-Z0-9]+" title="only letters" name="password" type="text" class="form-control" id="password" placeholder="Enter Password">
                  </div>
                  <div class="form-group">
                  <label for="duration">Duration</label>
                  <select name="duration" class="custom-select form-control" id="duration">
                    <option value="1" selected>1 Month</option>
                    <option value="3" selected>3 Month</option>
                    <option value="6" selected>6 Month</option>
                    <option value="12" selected>12 Month</option>
                    <option value="1" selected>1 Month</option>
                    <option value="999" selected>1 Day Trial</option>
                    <!-- option value="999">Trial</option -->
                  </select>
                  </div>
                </div>
                <!-- /.card-body -->
                <div class="card-footer">
                  <button type="submit" name="register" class="btn" style="color: <?php include('extension/theme_text.php'); ?>; background-color: <?php include('extension/theme.php'); ?>;">Create Account</button>
                </div>
              </form>
            </div>
            <!-- /.card -->
            </div>
          <!--/.col (left) -->
          
          <!-- right 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">Create Multiple User</h3>
              </div>
              <!-- /.card-header -->
              <!-- form start -->
              <form method="post" id="createSingleUserForm">
                <div class="card-body">
                  <?php echo $status2; ?>
                  <div class="form-group">
                    <label for="count">No. Of Users</label>
                    <input pattern="[0-9]+" min="2" max="1000" title="only numbers" name="count" type="number" class="form-control" id="count" placeholder="Enter number of users">
                  </div>
                  <div class="form-group">
                    <label for="prefix">Username Prefix</label>
                    <input pattern="[a-zA-Z]+" title="only letters" name="prefix" type="text" class="form-control" id="prefix" placeholder="Enter username prefix">
                  </div>
                  <div class="form-group">
                  <label for="duration">Duration</label>
                  <select name="duration" class="custom-select form-control" id="duration">
                    <option value="12" selected>12 Month</option>
                    <option value="9" selected>9 Month</option>
                    <option value="6" selected>6 Month</option>
                    <option value="3" selected>3 Month</option>
                    <option value="1" selected>1 Month</option>
                  </select>
                  </div>
                </div>
                <!-- /.card-body -->
                <div class="card-footer">
                  <button type="submit" name="multiregister" class="btn" style="color: <?php include('extension/theme_text.php'); ?>; background-color: <?php include('extension/theme.php'); ?>;">Create Multi</button>
                </div>
              </form>
            </div>
            <!-- /.card -->
            </div>
          <!--/.col (right) -->
        </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>
function generate_user(length) {
    var chars = '0123456789',
        r1="",
        result=""
    for (var i = length; i > 0; --i)
        r1 += chars[Math.round(Math.random() * (chars.length - 1))],
        result = r1
    return result
}

$(document).ready( function () {
$('#username').val(generate_user(7));
$('#password').val(generate_user(7));
});

function myFunction() {
  /* Get the text field */
  var copyText = document.getElementById("myInput");

  /* Select the text field */
  copyText.select();
  copyText.setSelectionRange(0, 99999); /* For mobile devices */

  /* Copy the text inside the text field */
  document.execCommand("copy");

  /* Alert the copied text */
  alert("Copied: " + copyText.value);
}
</script>
</body>
</html>
