<?php

/*===============================================*\
|| ############################################# ||
|| # JAKWEB.CH / Version 2.1.3                 # ||
|| # ----------------------------------------- # ||
|| # Copyright 2023 JAKWEB All Rights Reserved # ||
|| ############################################# ||
\*===============================================*/

// Check if the file is accessed only via index.php if not stop the script from running
if (!defined('JAK_ADMIN_PREVENT_ACCESS')) die('You cannot access this file directly.');

// Check if the user has access to this file
if (!JAK_ADMINACCESS) jak_redirect(BASE_URL);

// Get the license file
require_once '../class/class.jaklic.php';
$jaklic = new JAKLicenseAPI();

// All the tables we need for this plugin
$errors = array();
$jaktable = 'user';
$jaktable1 = 'user_stats';
$jaktable2 = 'departments';
$jaktable3 = 'clients';
$jaktable4 = 'support_departments';
$jaktable5 = 'faq_categories';
$jaktable6 = 'customfields';
$jaktable7 = 'support_tickets';
$jaktable8 = 'ticket_answers';
$jaktable9 = 'customfields_data';
$jaktable10 = 'envato_codes';
$jaktable11 = 'envato_products';

$insert = '';
$updatepass = $addmuser = $addclient = false;
$newop = true;
$totalavops = (!empty($jakosub) ? $jakosub['operators'] + $jakosub['extraoperators'] : 0);
$totalclients = (!empty($jakosub) ? $jakosub['clients'] : 0);

use JAKWEB\JAKsql;

// Now start with the plugin use a switch to access all pages
switch ($page1) {

  case 'clients':
    // No permission to clients
    if (!jak_get_access("client", $jakuser->getVar("permissions"), JAK_MAIN_OP)) jak_redirect(BASE_URL);

    switch ($page2) {
      case 'new':

        // Let's check if we can add more users
        $totalcl = $jakdb->count($jaktable3, ["opid" => JAK_USERID]);
        if ($totalclients > $totalcl) $addclient = true;
        
        // No special access, so what you doing here?
        if (!$addclient) jak_redirect(BASE_URL);
        
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $jkp = $_POST;
        
            if (empty($jkp['jak_name'])) {
                $errors['e1'] = $jkl['e7'];
            }
            
            if ($jkp['jak_email'] == '' || !filter_var($jkp['jak_email'], FILTER_VALIDATE_EMAIL)) {
                $errors['e2'] = $jkl['e3'];
            }

            if (jak_field_not_exist(strtolower($jkp['jak_email']), $jaktable3, "email")) {
                $errors['e2'] = $jkl['e18'];
            }
             
            if ($jkp['jak_password'] != $jkp['jak_confirm_password']) {
              $errors['e5'] = $jkl['e10'];
            } elseif (strlen($jkp['jak_password']) <= '7') {
              $errors['e6'] = $jkl['e11'];
            }
            
            if (count($errors) == 0) {
            
            // Chat departments
            if (!isset($jkp['jak_depid'])) {
              $depa = 0;
            } else {
              $depa = join(',', $jkp['jak_depid']);
            }

            // Support Departments
            if (!isset($jkp['jak_depids'])) {
              $depas = 0;
            } else {
              $depas = join(',', $jkp['jak_depids']);
            }

            // FAQ Categories
            if (!isset($jkp['jak_depidf'])) {
              $depaf = 0;
            } else {
              $depaf = join(',', $jkp['jak_depidf']);
            }

          $jakdb->insert($jaktable3, ["opid" => $opcacheid,
            "chat_dep" => $depa,
            "support_dep" => $depas,
            "faq_cat" => $depaf,
            "name" => $jkp['jak_name'],
            "email" => $jkp['jak_email'],
            "password" => hash_hmac('sha256', $jkp['jak_password'], DB_PASS_HASH),
            "canupload" => ($jakosub['files'] ? $jkp['jak_upload'] : 0),
            "language" => $jkp['jak_lang'],
            "access" => 1,
            "time" => $jakdb->raw("NOW()")]);

          $lastid = $jakdb->id();
        
          if (!$lastid) {
              $_SESSION["errormsg"] = $jkl['i4'];
              jak_redirect($_SESSION['LCRedirect']);
          } else {
            $newuserpath = APP_PATH.JAK_FILES_DIRECTORY.'/clients/'.$lastid;
            
            if (!is_dir($newuserpath)) {
              mkdir($newuserpath, 0755);
                copy(APP_PATH.JAK_FILES_DIRECTORY."/index.html", $newuserpath."/index.html");
            }

            // Now send the email to the customer if we wish so.
            if (isset($jkp['send_email']) && $jkp['send_email'] == 1) {

              // Change fake vars into real ones.
              if (!empty($HD_ANSWERS) && is_array($HD_ANSWERS)) foreach ($HD_ANSWERS as $v) {
                if ($v["msgtype"] == 14 && $v["lang"] == JAK_LANG) {
                  $phold = array('{url}', '{title}', '{cname}', '{cemail}', '{cpassword}', '{email}');
                  $replace   = array(BASE_URL_ORIG, JAK_TITLE, $jkp['jak_name'], $jkp['jak_email'], $jkp['jak_password'], JAK_EMAIL);
                  $regtext = str_replace($phold, $replace, $v["message"]);
                  break;
                }
              }

              // Get the email template
                      $nlhtml = file_get_contents(APP_PATH.'template/'.JAK_FRONT_TEMPLATE.'/email/index.html');
                    
                      // Change fake vars into real ones.
                      $cssAtt = array('{emailcontent}', '{weburl}', '{title}', '{emailtpllogo}', '{emailtplcopy}');
                      $cssUrl   = array($regtext, BASE_URL_ORIG, JAK_TITLE, JAK_EMAILTPLLOGO, JAK_EMAILTPLCOPY);
                      $nlcontent = str_replace($cssAtt, $cssUrl, $nlhtml);
              
                      $body = str_ireplace("[\]", "", $nlcontent);

              // Ok, we send the email // email address, cc email address, reply to, subject, message, attachment
                  if (jak_send_email($jkp['jak_email'], "", "", JAK_TITLE.' - '.$jkl['g247'], $body, "")) $_SESSION["infomsg"] = $jkl['hd134'];

            }

            // Last but not least add the client id to the already opened chat sessions.
            $jakdb->update("sessions", ["clientid" => $lastid], ["email" => $jkp['jak_email']]);

            // Write the log file each time
              JAK_base::jakWhatslog('', $opcacheid, JAK_USERID, $lastid, 12, $lastid, (isset($_COOKIE['WIOgeoData']) ? $_COOKIE['WIOgeoData'] : ''), $jkp['jak_email'], $_SERVER['REQUEST_URI'], $ipa, $valid_agent);

            // Output the success message
            $_SESSION["successmsg"] = $jkl['g14'];
              jak_redirect(JAK_rewrite::jakParseurl('users', 'clients', 'edit', $lastid));
           }
         
         } else {
            
             $errors['e'] = $jkl['e'];
            $errors = $errors;
         }
        }

        // Get all departments
        $JAK_DEPARTMENTS = $jakdb->select($jaktable2, ["id", "title"], ["opid" => $opcacheid, "ORDER" => ["dorder" => "ASC"]]);
        $JAK_DEP_SUPPORT = $jakdb->select($jaktable4, ["id", "title"], ["opid" => $opcacheid, "ORDER" => ["dorder" => "ASC"]]);
        $JAK_CAT_FAQ = $jakdb->select($jaktable5, ["id", "title"], ["opid" => $opcacheid, "ORDER" => ["dorder" => "ASC"]]);

        // Ok we have an id from the chat
        if ($page3 = "chat" && is_numeric($page4)) {

          // Get the data
          $datasett = $jakdb->get("sessions", ["name", "email"], ["AND" => ["id" => $page4, "opid" => $opcacheid]]);

          // Write it into the vars if not set already
          if (empty($_POST["jak_name"])) $_POST["jak_name"] = $datasett["name"];
          if (empty($_POST["jak_email"])) $_POST["jak_email"] = $datasett["email"];

        }
        
        // Call the settings function
        $lang_files = jak_get_lang_files();
        
        // Title and Description
        $SECTION_TITLE = $jkl["hd112"];
        $SECTION_DESC = "";
        
        // Include the javascript file for results
        $js_file_footer = 'js_client.php';
        
        // Call the template
        $template = 'newclient.php';
      break;
      case 'edit':

        if (isset($page3) && is_numeric($page3) && $jakdb->has($jaktable3, ["AND" => ["id" => $page3, "opid" => $opcacheid]])) {


        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $jkp = $_POST;
        
            if (empty($jkp['jak_name'])) {
                $errors['e1'] = $jkl['e7'];
            }
            
            if ($jkp['jak_email'] == '' || !filter_var($jkp['jak_email'], FILTER_VALIDATE_EMAIL)) {
                $errors['e2'] = $jkl['e3'];
            }

            if (jak_field_not_exist_id($jkp['jak_email'], $page3, $jaktable3, "email")) {
                $errors['e2'] = $jkl['e18'];
            }
             
            if (!empty($jkp['jak_password']) || !empty($jkp['jak_confirm_password'])) {    
              if ($jkp['jak_password'] != $jkp['jak_confirm_password']) {
                $errors['e5'] = $jkl['e10'];
              } elseif (strlen($jkp['jak_password']) <= '7') {
                $errors['e6'] = $jkl['e11'];
              } else {
                $updatepass = true;
              }
            }
            
            if (count($errors) == 0) {
            
              // Chat departments
              if (!isset($jkp['jak_depid'])) {
                $depa = 0;
              } else {
                $depa = join(',', $jkp['jak_depid']);
              }

              // Support Departments
              if (!isset($jkp['jak_depids'])) {
                $depas = 0;
              } else {
                $depas = join(',', $jkp['jak_depids']);
              }

              // FAQ Categories
              if (!isset($jkp['jak_depidf'])) {
                $depaf = 0;
              } else {
                $depaf = join(',', $jkp['jak_depidf']);
              }

            $result = $jakdb->update($jaktable3, ["chat_dep" => $depa,
              "support_dep" => $depas,
              "faq_cat" => $depaf,
              "name" => $jkp['jak_name'],
              "email" => $jkp['jak_email'],
              "credits" => $jkp['jak_credits'],
              "paid_until" => trim($jkp['jak_validtill']),
              "custom_price" => trim($jkp['custom_price']),
              "canupload" => $jkp['jak_upload'],
              "language" => $jkp['jak_lang'],
              "frontendadmin" => $jkp['jak_frontendadmin']], ["AND" => ["id" => $page3, "opid" => $opcacheid]]);
          
            if (!$result) {
                $_SESSION["errormsg"] = $jkl['i4'];
                jak_redirect($_SESSION['LCRedirect']);
            } else {
              // Finally we update the password
              if ($updatepass) $jakdb->update($jaktable3, ["password" => hash_hmac('sha256', $jkp['jak_password'], DB_PASS_HASH)], ["id" => $page3]);

              // And we complete the custom fields
              jak_save_custom_fields($opcacheid, $page3, 0, 0, $jkp, 1);

              $_SESSION["successmsg"] = $jkl['g14'];
                jak_redirect($_SESSION['LCRedirect']);
             }
         
          } else {
              
               $errors['e'] = $jkl['e'];
              $errors = $errors;
          }
        }

        // Get all departments
        $JAK_DEPARTMENTS = $jakdb->select($jaktable2, ["id", "title"], ["opid" => $opcacheid, "ORDER" => ["dorder" => "ASC"]]);
        $JAK_DEP_SUPPORT = $jakdb->select($jaktable4, ["id", "title"], ["opid" => $opcacheid, "ORDER" => ["dorder" => "ASC"]]);
        $JAK_CAT_FAQ = $jakdb->select($jaktable5, ["id", "title"], ["opid" => $opcacheid, "ORDER" => ["dorder" => "ASC"]]);
        
        // Call the settings function
        $lang_files = jak_get_lang_files(JAK_LANG);

        // Get the data
        $JAK_FORM_DATA = jak_get_data($page3, $opcacheid, $jaktable3);

        // Get the custom fields
        $custom_fields = jak_get_custom_fields($page3, 0, 1, $opcacheid, false, $JAK_FORM_DATA["language"], false, true, false, false, false);

        // Load the registered licenses
        if (JAK_BILLING_MODE == 3) {
        $allLics = $jakdb->select($jaktable10, ["[>]".$jaktable11 => ["productid" => "envato_item_id"]], ["envato_codes.id", "envato_codes.purchase_name", "envato_codes.purchase_code", "envato_codes.purchased", "envato_codes.support_expires", "envato_products.product_name"], ["AND" => ["envato_codes.opid" => $opcacheid, "envato_codes.clientid" => $page3], "ORDER" => ["envato_codes.support_expires" => "ASC"]]);
        }
        
        // Title and Description
        $SECTION_TITLE = $jkl["g287"];
        $SECTION_DESC = "";
        
        // Include the javascript file for results
        $js_file_footer = 'js_client.php';
        
        // Call the template
        $template = 'editclient.php';

        } else {
          $_SESSION["errormsg"] = $jkl['i3'];
            jak_redirect(JAK_rewrite::jakParseurl('users', 'clients'));
        }
      break;
      case 'lic':

        if (!JAK_SUPERADMINACCESS) jak_redirect(BASE_URL);

        # code...
        // Check if user exists and can be deleted
        if (JAK_BILLING_MODE == 3 && is_numeric($page3)) {
                
          // If you took $code from user input it's a good idea to trim it
          $code = $jakdb->get($jaktable10, ["clientid", "purchase_code"], ["AND" => ["id" => $page3, "opid" => $opcacheid], "LIMIT" => 1]);

             // Verify the key
          $purchase_data = verify_envato_purchase_code($code["purchase_code"]);

          if (isset($purchase_data['item']['name'])) {

            // Now we will update the client table for the support expire if older
            if ($jakdb->has($jaktable3, ["AND" => ["id" => $code["clientid"], "support_until[<]" => $purchase_data['supported_until']]])) {

              $jakdb->update($jaktable3, ["support_until" => $purchase_data['supported_until']], ["id" => $code["clientid"]]);
            }

          }
          
            $_SESSION["successmsg"] = $jkl['g14'];
            jak_redirect(JAK_rewrite::jakParseurl('users', 'clients', 'edit', $code["clientid"]));
            
        } else {
            
             $_SESSION["errormsg"] = $jkl['i3'];
            jak_redirect(JAK_rewrite::jakParseurl('users', 'clients', 'edit', $code["clientid"]));
        }

      break;
      case 'licdel':

        if (!JAK_SUPERADMINACCESS) jak_redirect(BASE_URL);

        # code...
        // Check if user exists and can be deleted
        if (JAK_BILLING_MODE == 3 && is_numeric($page3)) {

          $clientid = $jakdb->get($jaktable10, "clientid", ["AND" => ["id" => $page3, "opid" => $opcacheid], "LIMIT" => 1]);
                
          // Now let's delete the entry
          $result = $jakdb->delete($jaktable10, ["AND" => ["id" => $page3, "opid" => $opcacheid]]);
        
        if ($result->rowCount() != 1) {
            $_SESSION["infomsg"] = $jkl['i'];
            jak_redirect(JAK_rewrite::jakParseurl('users', 'clients', 'edit', $clientid));
        } else {
          
          // Now let us delete the define cache file
          $cachestufffile = APP_PATH.JAK_CACHE_DIRECTORY.'/stuff.php';
          if (file_exists($cachestufffile)) {
            unlink($cachestufffile);
          }

          // Write the log file each time someone tries to login before
                JAK_base::jakWhatslog('', $opcacheid, JAK_USERID, 0, 104, $page3, (isset($_COOKIE['WIOgeoData']) ? $_COOKIE['WIOgeoData'] : ''), $jakuser->getVar("username"), $_SERVER['REQUEST_URI'], $ipa, $valid_agent);
          
            $_SESSION["successmsg"] = $jkl['g14'];
            jak_redirect(JAK_rewrite::jakParseurl('users', 'clients', 'edit', $clientid));
        }
            
        } else {
            
             $_SESSION["errormsg"] = $jkl['i3'];
            jak_redirect(JAK_rewrite::jakParseurl('users', 'clients', 'edit', $clientid));
        }

      break;
      case 'newpass':

        // Now send the email to the customer if we wish so.
        if (isset($page3) && is_numeric($page3) && $jakdb->has($jaktable3, ["AND" => ["id" => $page3, "opid" => $opcacheid]])) {

          // Get the client data
          $JAK_FORM_DATA = jak_get_data($page3, $opcacheid, $jaktable3);

          // create new password
            $password = jak_password_creator();
            $passcrypt = hash_hmac('sha256', $password, DB_PASS_HASH);
            
            // update table
              $result = $jakdb->update($jaktable3, ["password" => $passcrypt, "forgot" => 0], ["AND" => ["id" => $page3, "opid" => $opcacheid]]);

          // Get the email template
                  $nlhtml = file_get_contents(APP_PATH.'template/'.JAK_FRONT_TEMPLATE.'/email/index.html');
                
                  // Change fake vars into real ones.
                  $cssAtt = array('{emailcontent}', '{weburl}', '{title}', '{emailtpllogo}', '{emailtplcopy}');
                  $cssUrl   = array(sprintf($jkl['l16'], $JAK_FORM_DATA["name"], $password, JAK_TITLE), BASE_URL_ORIG, JAK_TITLE, JAK_EMAILTPLLOGO, JAK_EMAILTPLCOPY);
                  $nlcontent = str_replace($cssAtt, $cssUrl, $nlhtml);
      
              $body = str_ireplace("[\]", "", $nlcontent);

              // Ok, we send the email // email address, cc email address, reply to, subject, message, attachment
          if (jak_send_email($JAK_FORM_DATA["email"], "", "", JAK_TITLE.' - '.$jkl['l15'], $body, "")) {

            $_SESSION["successmsg"] = $jkl['hd348'];

            // Write the log file each time someone tries to login before
                  JAK_base::jakWhatslog('', JAK_USERID, 0, 108, $page3, (isset($_COOKIE['WIOgeoData']) ? $_COOKIE['WIOgeoData'] : ''), $jakuser->getVar("username"), $_SERVER['REQUEST_URI'], $ipa, $valid_agent);

                  // Redirect
                  jak_redirect(JAK_rewrite::jakParseurl('users', 'clients', 'edit', $page3));

                }

        }

      break;
      default:
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {

          if (isset($_POST['jak_delock_all'])) {
            $jkp = $_POST;
            
            if (isset($jkp['action']) && $jkp['action'] == "lock") {
              
                $lockuser = $jkp['jak_delock_all'];
                $useridarray = explode(',', JAK_SUPERADMIN);
            
                for ($i = 0; $i < count($lockuser); $i++) {
                    $locked = $lockuser[$i];
                    // Get the userid / access token
                    $uidacc = explode(":#:", $locked);
                    if ($uidacc[1] == 1) {
                      $query = $jakdb->update($jaktable3, ["access" => 0], ["AND" => ["id" => $uidacc[0], "opid" => $opcacheid]]);
                    } else {
                      $query = $jakdb->update($jaktable3, ["access" => 1], ["AND" => ["id" => $uidacc[0], "opid" => $opcacheid]]);
                    }
                }
                
                if ($query) {
                  $_SESSION["successmsg"] = $jkl['g14'];
                  jak_redirect($_SESSION['LCRedirect']);
                }
            
             $_SESSION["infomsg"] = $jkl['i1'];
              jak_redirect($_SESSION['LCRedirect']);
            
            }
            
            if (isset($jkp['action']) && $jkp['action'] == "delete") {
            
                $lockuser = $jkp['jak_delock_all'];
            
                for ($i = 0; $i < count($lockuser); $i++) {
                    $locked = $lockuser[$i];
                    // Get the userid / access token
                    $uidacc = explode(":#:", $locked);
                    $query = $jakdb->delete($jaktable3, ["AND" => ["id" => $uidacc[0], "opid" => $opcacheid]]);

                    // Delete Avatar and folder
                $targetPath = APP_PATH.JAK_FILES_DIRECTORY.'/clients/'.$uidacc[0].'/';
                $removedouble =  str_replace("//","/",$targetPath);
                foreach(glob($removedouble.'*.*') as $jak_unlink) {
                  
                  // Delete the files
                  @unlink($jak_unlink);
                
                }

                // Delete the directory
                @rmdir($targetPath);

                // Find tickets from this user and set to 0
                $jakdb->update($jaktable7, ["clientid" => 0], ["AND" => ["clientid" => $uidacc[0], "opid" => $opcacheid]]);
                $jakdb->update($jaktable8, ["clientid" => 0], ["clientid" => $uidacc[0]]);
                }
                    
                if ($query) {
                  $_SESSION["successmsg"] = $jkl['g14'];
                  jak_redirect($_SESSION['LCRedirect']);
                }
          
             $_SESSION["infomsg"] = $jkl['i1'];
              jak_redirect($_SESSION['LCRedirect']);
            
            }

        }

            $_SESSION["infomsg"] = $jkl['i'];
            jak_redirect($_SESSION['LCRedirect']);
            
        }

        // Total client's
        $totalAll = 0;

          // Get the totals
          $totalAll = $jakdb->count($jaktable3, ["opid" => $opcacheid]);

          // Let's check if we can add more users
        if ($totalclients > $totalAll) $addclient = true;

        // Check and validate
        if (!JAK_WILDCARD_SUBDOMAIN) {
            $verify_response = $jaklic->verify_license(true);
            if ($verify_response['status'] != true) {
                if (JAK_SUPERADMINACCESS) {
                    jak_redirect(JAK_rewrite::jakParseurl('maintenance'));
                } else {
                    $_SESSION["errormsg"] = $jkl['e27'];
                    jak_redirect(BASE_URL);
                }
            }
        }
        
        // Title and Description
        $SECTION_TITLE = $jkl["hd6"];
        $SECTION_DESC = "";
        
        // Include the javascript file for results
        $js_file_footer = 'js_clients.php';
        
        // Call the template
        $template = 'clients.php';
      break;
    }
  break;

  // Create new user
  case 'new':
    
    // No special access, so what you doing here?
    if (!jak_get_access("usrmanage", $jakuser->getVar("permissions"), JAK_MAIN_OP)) jak_redirect(BASE_URL);

    // Let's check if we can add more users
    $totalops = $jakdb->count($jaktable, ["opid" => JAK_USERID]);
    if ($totalavops > $totalops) $addmuser = true;
    
    // No special access, so what you doing here?
    if (!$addmuser) jak_redirect(BASE_URL);
    
    // Get all departments
    $JAK_DEPARTMENTS = $jakdb->select($jaktable2, ["id", "title"], ["opid" => $opcacheid, "ORDER" => ["dorder" => "ASC"]]);
    $JAK_DEP_SUPPORT = $jakdb->select($jaktable4, ["id", "title"], ["opid" => $opcacheid, "ORDER" => ["dorder" => "ASC"]]);
    
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $jkp = $_POST;
    
        if (empty($jkp['jak_name'])) {
            $errors['e1'] = $jkl['e7'];
        }
        
        if ($jkp['jak_email'] == '' || !filter_var($jkp['jak_email'], FILTER_VALIDATE_EMAIL)) {
            $errors['e2'] = $jkl['e3'];
        }

        if (jak_field_not_exist(strtolower($jkp['jak_email']), $jaktable, "email")) {
            $errors['e2'] = $jkl['e18'];
        }
        
        if (!preg_match('/^([a-zA-Z0-9\-_])+$/', $jkp['jak_username'])) {
          $errors['e3'] = $jkl['e8'];
        }
        
        if (jak_field_not_exist(strtolower($jkp['jak_username']), $jaktable, "username")) {
            $errors['e4'] = $jkl['e9'];
        }
         
        if ($jkp['jak_password'] != $jkp['jak_confirm_password']) {
          $errors['e5'] = $jkl['e10'];
        } elseif (strlen($jkp['jak_password']) <= '7') {
          $errors['e6'] = $jkl['e11'];
        } else {
          $updatepass = true;
        }
        
        if (count($errors) == 0) {
        
        // Chat departments
        if (!isset($jkp['jak_depid'])) {
          $depa = 0;
        } else {
          $depa = join(',', $jkp['jak_depid']);
        }

        // Support Departments
        if (!isset($jkp['jak_depids'])) {
          $depas = 0;
        } else {
          $depas = join(',', $jkp['jak_depids']);
        }
        
        $tw_roles = '';
        if (JAK_SUPERADMINACCESS && !empty($jkp['jak_roles'])) $tw_roles = join(',', $jkp['jak_roles']);

        if (isset($jakhs['hostactive']) && $jakhs['hostactive']) {
        $jkp['jak_files'] = $jakhs['files'];
      }

      // Reset
        $validtill = '1980-05-06 00:00:00';
        // what we have to add for the operator
        if ($addmuser) {
        $totaleops = $jakdb->count($jaktable, ["AND" => ["opid" => $opcacheid, "extraop" => 1]]);
        
        if ($totaleops < $jakosub['extraoperators']) {
          $date = new DateTime();
          // Modify the date
          $date->modify('+1 month');
          $validtill = $date->format('Y-m-d H:i:s');
          $extraop = 1;
        } else {
          $validtill = $jakosub['paidtill'];
          $extraop = 0;
        }
      }
        
        $tw_roles = '';
        if (($addmuser) && isset($jkp['jak_roles']) && !empty($jkp['jak_roles'])) $tw_roles = join(',', $jkp['jak_roles']);

      $jakdb->insert($jaktable, ["opid" => $opcacheid,
        "chat_dep" => $depa,
        "support_dep" => $depas,
        "password" => hash_hmac('sha256', $jkp['jak_password'], DB_PASS_HASH),
        "username" => trim($jkp['jak_username']),
        "name" => trim($jkp['jak_name']),
        "email" => filter_var($jkp['jak_email'], FILTER_SANITIZE_EMAIL),
        "responses" => $jkp['jak_responses'],
        "files" => $jkp['jak_files'],
        "operatorchat" => $jkp['jak_chat'],
        "operatorchatpublic" => $jkp['jak_chatpublic'],
        "operatorlist" => $jkp['jak_chatlist'],
        "transferc" => $jkp['jak_transfer'],
        "chat_latency" => $jkp['jak_latency'],
        "useronlinelist" => $jkp['jak_uolist'],
        "sound" => $jkp['jak_sound'],
        "ringing" => $jkp['jak_ringing'],
        "language" => $jkp['jak_lang'],
        "invitationmsg" => $jkp['jak_inv'],
        "navsidebar" => $jkp['jak_navside'],
        "permissions" => $tw_roles,
        "validtill" => $validtill,
        "extraop" => $extraop,
        "access" => $jkp['jak_access'],
        "time" => $jakdb->raw("NOW()")]);

      $lastid = $jakdb->id();
    
      if (!$lastid) {
          $_SESSION["errormsg"] = $jkl['i4'];
          jak_redirect($_SESSION['LCRedirect']);
      } else {
        $newuserpath = APP_PATH.JAK_FILES_DIRECTORY.'/'.$lastid;
        
        if (!is_dir($newuserpath)) {
          mkdir($newuserpath, 0755);
            copy(APP_PATH.JAK_FILES_DIRECTORY."/index.html", $newuserpath."/index.html");
        }

        // Write the log file each time someone login after to show success
          JAK_base::jakWhatslog('', $opcacheid, JAK_USERID, 0, 13, $lastid, (isset($_COOKIE['WIOgeoData']) ? $_COOKIE['WIOgeoData'] : ''), trim($jkp['jak_username']), $_SERVER['REQUEST_URI'], $ipa, $valid_agent);

        $_SESSION["successmsg"] = $jkl['g14'];
          jak_redirect(JAK_rewrite::jakParseurl('users', 'edit', $lastid, $opcacheid));
       }
     
     } else {
        
         $errors['e'] = $jkl['e'];
        $errors = $errors;
     }
    }
    
    // Call the settings function
    $lang_files = jak_get_lang_files();
    
    // Title and Description
    $SECTION_TITLE = $jkl["m7"];
    $SECTION_DESC = "";
    
    // Include the javascript file for results
    $js_file_footer = 'js_edituser.php';
    
    // Call the template
    $template = 'newuser.php';
    
  break;
  case 'stats':
  
    // Let's go on with the script
      if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['email_feedback'])) {
          $jkp = $_POST;
          
          // Errors in Array
          $errors = array();
          
          if ($jkp['email'] == '' || !filter_var($jkp['email'], FILTER_VALIDATE_EMAIL)) {
              $errors['email'] = $jkl['e3'];
          }
          
          if (count($errors) > 0) {
          
          /* Outputtng the error messages */
            if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
            
              header('Cache-Control: no-cache');
              die('{"status":0, "errors":'.json_encode($errors).'}');
              
            } else {
            
              $errors = $errors;
            }
            
          } else {

            $result = $jakdb->select($jaktable1, "*", ["userid" => $page2, "ORDER" => ["id" => "ASC"]]);

            $total_vote = $jakdb->sum($jaktable1, "vote", ["userid" => $page2]);
            $total_support = $jakdb->sum($jaktable1, "support_time", ["userid" => $page2]);
            
            $subject = $jkl["g81"].' '.$page3;
            
            $mailchat = '<div style="margin:10px 0px 0px 0px;padding:10px;border:1px solid #A8B9CB;font-family: Verdana, sans-serif;font-size: 13px;
            font-weight: 500;letter-spacing: normal;line-height: 1.5em;"><h2>'.$subject.'</h2><ul style="list-style:none;">';
            
            // Reset var
            $count = 0;
            if (isset($result) && !empty($result) && is_array($result)) foreach ($result as $row) {
              // collect each record into $_data
                $mailchat .= '<li style="border-bottom:1px solid #333"><span style="font-size:11px">'.$row['time'].' - '.$jkl['g86'].':</span><br /><span style="color:#c92e2e">'.$jkl['g85'].': </span>'.$row['vote'].'/5<br />'.$jkl['g54'].': '.$row['name'].'<br />'.$jkl['stat_s12'].': '.$row['comment'].'<br />'.$jkl['l5'].': '.$row['email'].'<br />'.$jkl['g87'].': '.gmdate('H:i:s', $row['support_time']).'</li>';
                      
               $count++;
            }
                
            $mailchat .= '</ul>';
            
            $mailchat .= '<h2>'.$jkl["g89"].'</h2>
            <p><strong>'.$jkl["g90"].':</strong> '.gmdate('H:i:s', $total_support).'<br /><strong>'.$jkl["g91"].':</strong> '.round(($total_vote / $count), 2).'/5</p></div>';

            // Ok, we send the email // email address, cc email address, reply to, subject, message, attachment
              if (jak_send_email($jkp['email'], "", "", $subject, $mailchat, "")) {
            
            // Ajax Request
            if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
            
              header('Cache-Control: no-cache');
              die(json_encode(array('status' => 1, 'html' => $jkl["g14"])));
              
            } else {
            
                  jak_redirect($_SERVER['HTTP_REFERER']);
              
              }
          } 
          
      }
    }
  
    // Check if the user exists
    if (is_numeric($page2) && ($page2 == JAK_USERID || $page4 == $opcacheid)) {
      
      // Reset some vars
      $USER_FEEDBACK = array();
      $ufcount = 0;
      $USER_VOTES = $USER_SUPPORT = $USER_SUPPORT_TICKET_N = $USER_SUPPORT_TICKET = $USER_SUPPORT_TICKETS = 0;

      // Get all chat feedbacks
      $USER_FEEDBACK = $jakdb->select($jaktable1, "*", ["userid" => $page2, "ORDER" => ["id" => "DESC"]]);
      // Let's check which one have vote 0 and exlcude them
      if (isset($USER_FEEDBACK) && !empty($USER_FEEDBACK)) foreach ($USER_FEEDBACK as $uf) {
        # code...
        if ($uf["vote"] != 0) {
          $ufcount++;
        }
      }

      // Calculate the votes and support time for the chat
      $USER_VOTES = $jakdb->sum($jaktable1, "vote", ["AND" => ["userid" => $page2, "vote[!]" => "0"]]);
      $USER_SUPPORT = $jakdb->sum($jaktable1, "support_time", ["userid" => $page2]);

      // Calculate the response time for the tickets (average)
      $USER_SUPPORT_TICKET_N = $jakdb->count("support_tickets_response", ["AND" => ["opid" => $opcacheid, "operatorid" => $page2, "newticket" => 1]]);
          $USER_SUPPORT_TIME_N = $jakdb->sum("support_tickets_response", "responsetime", ["AND" => ["opid" => $opcacheid, "operatorid" => $page2, "newticket" => 1]]);

          $USER_SUPPORT_TICKET = $jakdb->count("support_tickets_response", ["AND" => ["opid" => $opcacheid, "operatorid" => $page2]]);
          $USER_SUPPORT_TIME = $jakdb->sum("support_tickets_response", "responsetime", ["AND" => ["opid" => $opcacheid, "operatorid" => $page2]]);

          // Average time spent on a ticket
          $USER_SUPPORT_TICKETS = $jakdb->count("support_tickets", ["AND" => ["opid" => $opcacheid, "operatorid" => $page2, "ended[!]" => 0]]);
          $USER_TICKETS_INI = $jakdb->sum("support_tickets", "initiated", ["AND" => ["opid" => $opcacheid, "operatorid" => $page2, "ended[!]" => 0]]);
          $USER_TICKETS_ENDED = $jakdb->sum("support_tickets", "ended", ["AND" => ["opid" => $opcacheid, "operatorid" => $page2], "ended[!]" => 0]);
    
    }
  
    // Call the template
    $template = 'userstats.php';
         
  break;
  case 'edit':
    
    // No special access and not your userid, what you up to?
    if (!jak_get_access("usrmanage", $jakuser->getVar("permissions"), JAK_MAIN_OP) && ($page2 != JAK_USERID || $page3 != $opcacheid)) jak_redirect(BASE_URL);
  
    // Check if the user exists
    if (is_numeric($page2) && ($page2 == JAK_USERID || $page3 == $opcacheid)) {
    
      // Get all departments
      $JAK_DEPARTMENTS = $jakdb->select($jaktable2, ["id", "title"], ["opid" => $opcacheid, "ORDER" => ["dorder" => "ASC"]]);
      $JAK_DEP_SUPPORT = $jakdb->select($jaktable4, ["id", "title"], ["opid" => $opcacheid, "ORDER" => ["dorder" => "ASC"]]);
    
      if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $jkp = $_POST;
    
        if (empty($jkp['jak_name'])) {
            $errors['e1'] = $jkl['e7'];
        }
        
        if ($jkp['jak_email'] == '' || !filter_var($jkp['jak_email'], FILTER_VALIDATE_EMAIL)) {
            $errors['e2'] = $jkl['e3'];
        }

        if (jak_field_not_exist_id($jkp['jak_email'], $page2, $jaktable, "email")) {
            $errors['e2'] = $jkl['e18'];
        }
        
        if (!preg_match('/^([a-zA-Z0-9\-_])+$/', $jkp['jak_username'])) {
          $errors['e3'] = $jkl['e8'];
        }
        
        if (jak_field_not_exist_id($jkp['jak_username'], $page2, $jaktable, "username")) {
            $errors['e4'] = $jkl['e9'];
        }
        
        if (!empty($jkp['jak_password']) || !empty($jkp['jak_confirm_password'])) {    
        if ($jkp['jak_password'] != $jkp['jak_confirm_password']) {
          $errors['e5'] = $jkl['e10'];
        } elseif (strlen($jkp['jak_password']) <= '7') {
          $errors['e6'] = $jkl['e11'];
        } else {
          $updatepass = true;
        }
        }
        
        // Delete Avatar if yes
        if (!empty($jkp['jak_delete_avatar'])) {
          $avatarpi = APP_PATH.JAK_FILES_DIRECTORY.'/index.html';
          $avatarpid =  str_replace("//","/",$avatarpi);
          $targetPath = APP_PATH.JAK_FILES_DIRECTORY.'/'.$page2.'/';
          $removedouble =  str_replace("//","/",$targetPath);
          foreach(glob($removedouble.'*.*') as $jak_unlink){
              unlink($jak_unlink);
              copy($avatarpid, $targetPath . "/index.html");
          }
          
          $jakdb->update($jaktable, ["picture" => "/standard.jpg"], ["id" => $page2]);
        
        }
        
        if (!empty($_FILES['uploadpp']['name'])) {
        
          if ($_FILES['uploadpp']['name'] != '') {
          
          $filename = $_FILES['uploadpp']['name']; // original filename
          // Fix explode when upload in 3.3
          $ls_xtension = pathinfo($filename);
          
          if ($ls_xtension['extension'] == "jpg" || $ls_xtension['extension'] == "jpeg" || $ls_xtension['extension'] == "png" || $ls_xtension['extension'] == "gif") {

          // Get the maximum upload or set to 2
        $postmax = (ini_get('post_max_size') ? filter_var(ini_get('post_max_size'), FILTER_SANITIZE_NUMBER_INT) : "2");
          
          if ($_FILES['uploadpp']['size'] <= ($postmax * 1000000)) {
          
          list($width, $height, $type, $attr) = getimagesize($_FILES['uploadpp']['tmp_name']);
          $mime = image_type_to_mime_type($type);
          
          if (($mime == "image/jpeg") || ($mime == "image/pjpeg") || ($mime == "image/png") || ($mime == "image/gif")) {
          
          // first get the target path
          $targetPathd = APP_PATH.JAK_FILES_DIRECTORY.'/'.$page2.'/';
          $targetPath =  str_replace("//","/",$targetPathd);

          // Create the target path
          if (!is_dir($targetPath)) {
            mkdir($targetPath, 0755);
              copy(APP_PATH.JAK_FILES_DIRECTORY."/index.html", $targetPath . "/index.html");
          
          }

          // if old avatars exist delete it
          foreach(glob($targetPath.'*.*') as $jak_unlink){
              unlink($jak_unlink);
              copy(APP_PATH.JAK_FILES_DIRECTORY."/index.html", $targetPath . "/index.html");
          }
          
          $tempFile = $_FILES['uploadpp']['tmp_name'];
          $origName = substr($_FILES['uploadpp']['name'], 0, -4);
          $name_space = strtolower($_FILES['uploadpp']['name']);
          $middle_name = str_replace(" ", "_", $name_space);
          $middle_name = str_replace(".jpeg", ".jpg", $name_space);
          $glnrrand = rand(10, 99);
          $bigPhoto = str_replace(".", "_" . $glnrrand . ".", $middle_name);
          $smallPhoto = str_replace(".", "_t.", $bigPhoto);
              
          $targetFile =  str_replace('//','/',$targetPath) . $bigPhoto;
          $origPath = '/'.$page2.'/';
          $dbSmall = $origPath.$smallPhoto;
          
          require_once '../include/functions_thumb.php';
          // Move file and create thumb     
          move_uploaded_file($tempFile,$targetFile);
               
          create_thumbnail($targetPath, $targetFile, $smallPhoto, JAK_USERAVATWIDTH, JAK_USERAVATHEIGHT, 80);
                 
          // SQL update
          $jakdb->update($jaktable, ["picture" => $dbSmall], ["id" => $page2]);
                   
          } else {
            $errors['e7'] = $jkl['e24'].'<br>';
            $errors = $errors;
          }
          
          } else {
            $errors['e7'] = $jkl['e46'].'<br>';
            $errors = $errors;
          }
          
          } else {
            $errors['e7'] = $jkl['e24'].'<br>';
            $errors = $errors;
          }
          
          } else {
            $errors['e7'] = $jkl['e24'].'<br>';
            $errors = $errors;
          }
        
        }
        
        if (count($errors) == 0) {
        
        if (!isset($jkp['jak_access'])) $jkp['jak_access'] = '1';
        
        // We cant deny access for superadmin
        $useridarray = explode(',', JAK_SUPERADMIN);
        
        if (!in_array($page2, $useridarray)) {

          $result = $jakdb->update($jaktable, ["access" => $jkp['jak_access']], ["id" => $page2]);
        }
        
        // Chat departments
        if (!isset($jkp['jak_depid'])) {
          $depa = 0;
        } else {
          $depa = join(',', $jkp['jak_depid']);
        }

        // Support Departments
        if (!isset($jkp['jak_depids'])) {
          $depas = 0;
        } else {
          $depas = join(',', $jkp['jak_depids']);
        }
        
        $bhours = '';
        $bhours = trim($_REQUEST["bhours"]);
        
        // Reset the hours if they not set.
        if ($bhours == '[{"isActive":false,"timeFrom":null,"timeTill":null,"timeFroma":null,"timeTilla":null},{"isActive":false,"timeFrom":null,"timeTill":null,"timeFroma":null,"timeTilla":null},{"isActive":false,"timeFrom":null,"timeTill":null,"timeFroma":null,"timeTilla":null},{"isActive":false,"timeFrom":null,"timeTill":null,"timeFroma":null,"timeTilla":null},{"isActive":false,"timeFrom":null,"timeTill":null,"timeFroma":null,"timeTilla":null},{"isActive":false,"timeFrom":null,"timeTill":null,"timeFroma":null,"timeTilla":null},{"isActive":false,"timeFrom":null,"timeTill":null,"timeFroma":null,"timeTilla":null}]') $bhours = '';

        // No sibling update
        $siblingupd = false;

        $smsphone = '';
      if (isset($jkp['jak_phone'])) $smsphone = $jkp['jak_phone'];

      $whatsphone = '';
      if (isset($jkp['jak_whatsphone'])) $whatsphone = $jkp['jak_whatsphone'];
        
        if (jak_get_access("usrmanage", $jakuser->getVar("permissions"), JAK_MAIN_OP)) {
        
        $result = $jakdb->update($jaktable, ["chat_dep" => $depa,
        "support_dep" => $depas,
        "username" => trim($jkp['jak_username']),
        "name" => trim($jkp['jak_name']),
        "aboutme" => trim($jkp['jak_aboutme']),
        "phonenumber" => $smsphone,
        "whatsappnumber" => $whatsphone,
        "pusho_tok" => $jkp['jak_pushot'],
        "pusho_key" => $jkp['jak_pushok'],
        "responses" => $jkp['jak_responses'],
        "files" => $jkp['jak_files'],
        "operatorchat" => $jkp['jak_chat'],
        "operatorchatpublic" => $jkp['jak_chatpublic'],
        "operatorlist" => $jkp['jak_chatlist'],
        "transferc" => $jkp['jak_transfer'],
        "chat_latency" => $jkp['jak_latency'],
        "useronlinelist" => $jkp['jak_uolist'],
        "sound" => $jkp['jak_sound'],
        "ringing" => $jkp['jak_ringing'],
        "alwaysnot" => $jkp['jak_alwaysnot'],
        "alwaysonline" => $jkp['jak_alwaysonline'],
        "emailnot" => $jkp['jak_emailnot'],
        "language" => $jkp['jak_lang'],
        "invitationmsg" => $jkp['jak_inv'],
        "hours_array" => $bhours,
        "navsidebar" => $jkp['jak_navside'],
        "themecolour" => $jkp['jak_themecolour'],
        "menubg" => $jkp['jak_menubg'],
        "email" => filter_var($jkp['jak_email'], FILTER_SANITIZE_EMAIL)], ["id" => $page2]);
      
      } else {

        $result = $jakdb->update($jaktable, ["username" => trim($jkp['jak_username']),
        "name" => trim($jkp['jak_name']),
        "aboutme" => trim($jkp['jak_aboutme']),
        "phonenumber" => $smsphone,
        "whatsappnumber" => $whatsphone,
        "pusho_tok" => $jkp['jak_pushot'],
        "pusho_key" => $jkp['jak_pushok'],
        "chat_latency" => $jkp['jak_latency'],
        "useronlinelist" => $jkp['jak_uolist'],
        "sound" => $jkp['jak_sound'],
        "ringing" => $jkp['jak_ringing'],
        "alwaysnot" => $jkp['jak_alwaysnot'],
        "alwaysonline" => $jkp['jak_alwaysonline'],
        "emailnot" => $jkp['jak_emailnot'],
        "language" => $jkp['jak_lang'],
        "invitationmsg" => $jkp['jak_inv'],
        "hours_array" => $bhours,
        "navsidebar" => $jkp['jak_navside'],
        "themecolour" => $jkp['jak_themecolour'],
        "menubg" => $jkp['jak_menubg'],
        "email" => filter_var($jkp['jak_email'], FILTER_SANITIZE_EMAIL)], ["id" => $page2]);
      
      }

      // Table to update usually the one belongs to the operator // Sibling update
      if (isset($page3) && !empty($page3) && is_numeric($page3) && $jakdb->has($jaktable, ["AND" => ["id" => $page2, "opid" => $opcacheid]])) $siblingupd = true;

      // Finally we update the password
      if ($updatepass) $jakdb->update($jaktable, ["password" => hash_hmac('sha256', $jkp['jak_password'], DB_PASS_HASH)], ["id" => $page2]);

      // Finally update the user permission
      if (jak_get_access("usrmanage", $jakuser->getVar("permissions"), JAK_MAIN_OP)) {
        
            if (!isset($jkp['jak_roles'])) {
              $tw_roles = '';
            } else {
              $tw_roles = join(',', $jkp['jak_roles']);
            }

            $jakdb->update($jaktable, ["permissions" => $tw_roles], ["id" => $page2]);
            
        }
    
    if (!$result) {
        $_SESSION["infomsg"] = $jkl['i'];
        jak_redirect($_SESSION['LCRedirect']);
    } else {
      // We have a username change reset the sessions or we get logged out
      if ($jkp['jak_username'] != $jkp['jak_username_old']) {

        // Set the session
        $_SESSION['jak_username'] = $jkp['jak_username'];

        // Check if cookies are set previous (wrongly) and delete
        if (isset($_COOKIE['jak_lcp_cookname'])) {
          JAK_base::jakCookie('jak_lcp_cookname', $jkp['jak_username'], JAK_COOKIE_TIME, JAK_COOKIE_PATH);
        }
      }

      if (!$siblingupd) {

        // Now if we have multi site please update the main database.
        if (!empty(JAKDB_MAIN_NAME) && JAK_MAIN_LOC) {

          // Database connection to the main site
            $jakdb1 = new JAKsql([
              // required
                 'database_type' => JAKDB_MAIN_DBTYPE,
                'database_name' => JAKDB_MAIN_NAME,
                'server' => JAKDB_MAIN_HOST,
                'username' => JAKDB_MAIN_USER,
                'password' => JAKDB_MAIN_PASS,
                'charset' => 'utf8',
                'port' => JAKDB_MAIN_PORT,
                'prefix' => JAKDB_MAIN_PREFIX,
                 
                // [optional] driver_option for connection, read more from http://www.php.net/manual/en/pdo.setattribute.php
                'option' => [PDO::ATTR_CASE => PDO::CASE_NATURAL]
                ]);

          $jakdb1->update("users", [ 
            "email" => filter_var($jkp['jak_email'], FILTER_SANITIZE_EMAIL),
            "username" => trim($jkp['jak_username']),
            "lastedit" => $jakdb->raw("NOW()")], ["AND" => ["locationid" => JAK_MAIN_LOC, "opid" => $opcacheid]]);

            if ($updatepass) $jakdb1->update("users", ["password" => hash_hmac('sha256', $jkp['jak_password'], DB_PASS_HASH)], ["AND" => ["locationid" => JAK_MAIN_LOC, "opid" => $opcacheid]]);
        }
      } // end siblings update

        $_SESSION["successmsg"] = $jkl['g14'];
        jak_redirect($_SESSION['LCRedirect']);
    }
    
    // Output the errors
    } else {
        
         $errors['e'] = $jkl['e'];
        $errors = $errors;
    }
    }
    
      // Call the settings function
      $lang_files = jak_get_lang_files();

      $JAK_FORM_DATA = $jakdb->get($jaktable, "*", ["AND" => ["id" => $page2]]);
      
      // Title and Description
      $SECTION_TITLE = $jkl["m11"];
      $SECTION_DESC = "";
      
      // Include the javascript file for results
      $js_file_footer = 'js_edituser.php';
      
      $template = 'edituser.php';
    
    } else {
      $_SESSION["errormsg"] = $jkl['i3'];
        jak_redirect(JAK_rewrite::jakParseurl('users'));
    }
    
    break;

    case 'resethours':
      // Check if the user exists
      if (is_numeric($page2) && ($page2 == JAK_USERID || $page3 == $opcacheid)) {

        $result = $jakdb->update($jaktable, ["hours_array" => ""], ["id" => $page2]);

        $_SESSION["successmsg"] = $jkl['g14'];
          jak_redirect(JAK_rewrite::jakParseurl('users', 'edit', $page2, $page3));

      } else {
        $_SESSION["errormsg"] = $jkl['i2'];
          jak_redirect(JAK_rewrite::jakParseurl('users'));
      }
    break;
    default:
    
      if ($_SERVER['REQUEST_METHOD'] == 'POST') {

        if (isset($_POST['jak_delock_all'])) {
          $jkp = $_POST;
          
          if (isset($jkp['action']) && $jkp['action'] == "lock") {
            
              $lockuser = $jkp['jak_delock_all'];
              $useridarray = explode(',', JAK_SUPERADMIN);
          
              for ($i = 0; $i < count($lockuser); $i++) {
                  $locked = $lockuser[$i];
                  // Get the userid / access token
                  $uidacc = explode(":#:", $locked);
                  if (!in_array($uidacc[0], $useridarray)) {
                    if ($uidacc[1] == 1) {
                      $query = $jakdb->update($jaktable, ["access" => 0], ["id" => $uidacc[0]]);
                    } else {
                      $query = $jakdb->update($jaktable, ["access" => 1], ["id" => $uidacc[0]]);
                    }
                }
              }
              
              if ($query) {
                $_SESSION["successmsg"] = $jkl['g14'];
                jak_redirect($_SESSION['LCRedirect']);
              }
          
           $_SESSION["infomsg"] = $jkl['i1'];
            jak_redirect($_SESSION['LCRedirect']);
          
          }
          
          if (isset($jkp['delete']) && $jkp['action'] == "delete") {
          
              $lockuser = $jkp['jak_delock_all'];
              $useridarray = explode(',', JAK_SUPERADMIN);
          
              for ($i = 0; $i < count($lockuser); $i++) {
                  $locked = $lockuser[$i];
                  // Get the userid / access token
                  $uidacc = explode(":#:", $locked);
                  if (!in_array($uidacc[0], $useridarray)) {
                    $query = $jakdb->delete($jaktable, ["id" => $uidacc[0]]);

                    // Delete Avatar and folder
                $targetPath = APP_PATH.JAK_FILES_DIRECTORY.'/'.$uidacc[0].'/';
                $removedouble =  str_replace("//","/",$targetPath);
                foreach(glob($removedouble.'*.*') as $jak_unlink) {
                          
                  // Delete the files
                  @unlink($jak_unlink);
                        
                }

                @rmdir($targetPath);
                }
              }
                  
              if ($query) {
                $_SESSION["successmsg"] = $jkl['g14'];
                jak_redirect($_SESSION['LCRedirect']);
              }
        
           $_SESSION["infomsg"] = $jkl['i1'];
            jak_redirect($_SESSION['LCRedirect']);
          
          }

      }

          $_SESSION["infomsg"] = $jkl['i'];
          jak_redirect($_SESSION['LCRedirect']);
          
      }

      if (jak_get_access("usrmanage", $jakuser->getVar("permissions"), JAK_MAIN_OP)) {
        $JAK_USER_ALL = jak_get_user_all($jaktable, $opcacheid, "meandsibling");

        // Let's check if we can add more users
        $totalAll = count($JAK_USER_ALL);
        if ($totalavops > $totalAll) $addmuser = true;

      } else {
        $JAK_USER_ALL = jak_get_user_all($jaktable, JAK_USERID, false);
      }
      
      // Title and Description
      $SECTION_TITLE = $jkl["hd5"];
      $SECTION_DESC = "";
      
      // Include the javascript file for results
      $js_file_footer = 'js_user.php';
      
      // Call the template
      $template = 'user.php';
}
?>
