<?php

/*===============================================*\
|| ############################################# ||
|| # JAKWEB.CH / Version 2.1.4                 # ||
|| # ----------------------------------------- # ||
|| # 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.');

//Import the PHPMailer class into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\OAuth;
//@see https://github.com/thephpleague/oauth2-google
use League\OAuth2\Client\Provider\Google;
//@see https://github.com/stevenmaguire/oauth2-microsoft
use Stevenmaguire\OAuth2\Client\Provider\Microsoft;
//@see https://github.com/greew/oauth2-azure-provider
use Greew\OAuth2\Client\Provider\Azure;
//@see https://packagist.org/packages/hayageek/oauth2-yahoo
use Hayageek\OAuth2\Client\Provider\Yahoo;

// All the tables we need for this plugin
$errors = $success = array();
$ss = false;

$jaktable = 'php_imap';
$jaktable1 = 'support_departments';
$jaktable2 = 'departments';
$jaktable3 = 'faq_categories';
$jaktable4 = 'cms_pages';
$jaktable5 = 'ticketpriority';
$jaktable6 = 'ticketoptions';
$jaktable7 = 'clients';
$jaktable8 = 'user';
$jaktable9 = 'chatwidget';

$addphpimap = false;
$totalphpimap = (!empty($jakosub) ? $jakosub['phpimap'] : 0);

switch ($page1) {
    case 'support':

        // Let's go on with the script
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $jkp = $_POST;
            
            if (isset($jkp['save'])) {

                if (jak_get_access("support", $jakuser->getVar("permissions"), JAK_MAIN_OP)) {

                    // Update the fields
                    $jakdb->update("settings", ["used_value" => $jkp['jak_ticket_close_r']], ["AND" => ["opid" => $opcacheid, "varname" => "ticket_close_r"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_ticket_inform']], ["AND" => ["opid" => $opcacheid, "varname" => "ticket_inform_r"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_ticket_guest']], ["AND" => ["opid" => $opcacheid, "varname" => "ticket_guest"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_ticket_guest_web']], ["AND" => ["opid" => $opcacheid, "varname" => "ticket_guest_web"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_ticket_account']], ["AND" => ["opid" => $opcacheid, "varname" => "ticket_account"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_ticket_rating']], ["AND" => ["opid" => $opcacheid, "varname" => "ticket_rating"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_ticket_limit']], ["AND" => ["opid" => $opcacheid, "varname" => "ticket_limit"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_ticket_reminder']], ["AND" => ["opid" => $opcacheid, "varname" => "ticket_reminder"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_ticket_close']], ["AND" => ["opid" => $opcacheid, "varname" => "ticket_close_c"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_ticket_reopen']], ["AND" => ["opid" => $opcacheid, "varname" => "ticket_reopen"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_ticket_attach']], ["AND" => ["opid" => $opcacheid, "varname" => "ticket_attach"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_private']], ["AND" => ["opid" => $opcacheid, "varname" => "ticket_private"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_private_show']], ["AND" => ["opid" => $opcacheid, "varname" => "ticket_private_show"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_priority']], ["AND" => ["opid" => $opcacheid, "varname" => "standard_ticket_priority"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_option']], ["AND" => ["opid" => $opcacheid, "varname" => "standard_ticket_option"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_ticket_duedate']], ["AND" => ["opid" => $opcacheid, "varname" => "ticket_duedate"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_ticket_duedate_format']], ["AND" => ["opid" => $opcacheid, "varname" => "ticket_duedate_format"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_ticket_duedate_preset']], ["AND" => ["opid" => $opcacheid, "varname" => "ticket_duedate_preset"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_ticket_similar']], ["AND" => ["opid" => $opcacheid, "varname" => "ticket_similar"]]);

                    // Now let us delete the define cache file
                    $cachestufffile = APP_PATH.JAK_CACHE_DIRECTORY.'/opcache'.$opcacheid.'.php';
                    if (file_exists($cachestufffile)) {
                        unlink($cachestufffile);
                    }

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

                    $_SESSION["successmsg"] = $jkl['g14'];
                    jak_redirect($_SESSION['LCRedirect']);

                }

            }

        }

        // Get all priorities
        $PRIORITY_ALL = $jakdb->select($jaktable5, ["id", "title", "credits"], ["AND" => ["opid" => $opcacheid, "depid" => 0]]);
        // Get all options
        $TOPTIONS_ALL = $jakdb->select($jaktable6, ["id", "title", "credits"], ["AND" => ["opid" => $opcacheid, "depid" => 0]]);

        // Title and Description
        $SECTION_TITLE = $jkl["hd91"];
        $SECTION_DESC = "";

        // Call the template
        $template = 'supportsetting.php';
        
    break;
    case 'faq':
        // Let's go on with the script
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $jkp = $_POST;
            
            if (isset($jkp['save'])) {

                if (jak_get_access("faq", $jakuser->getVar("permissions"), JAK_MAIN_OP)) {

                    // Update the fields
                    $jakdb->update("settings", ["used_value" => $jkp['jak_faq']], ["AND" => ["opid" => $opcacheid, "varname" => "faq_a"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_faq_home']], ["AND" => ["opid" => $opcacheid, "varname" => "faq_home"]]);
                    // $jakdb->update("settings", ["used_value" => $jkp['jak_faq_footer']], ["AND" => ["opid" => $opcacheid, "varname" => "faq_footer"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_faq_page']], ["AND" => ["opid" => $opcacheid, "varname" => "faq_page"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_faq_pagination']], ["AND" => ["opid" => $opcacheid, "varname" => "faq_pagination"]]);

                    // Now let us delete the define cache file
                    $cachestufffile = APP_PATH.JAK_CACHE_DIRECTORY.'/opcache'.$opcacheid.'.php';
                    if (file_exists($cachestufffile)) {
                        unlink($cachestufffile);
                    }

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

                    $_SESSION["successmsg"] = $jkl['g14'];
                    jak_redirect($_SESSION['LCRedirect']);

                }

            }

        }

        // Title and Description
        $SECTION_TITLE = $jkl["hd106"];
        $SECTION_DESC = "";

        // Call the template
        $template = 'faqsetting.php';
    break;
    case 'blog':
        // Let's go on with the script
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $jkp = $_POST;
            
            if (isset($jkp['save'])) {

                if (jak_get_access("blog", $jakuser->getVar("permissions"), JAK_MAIN_OP)) {

                    // Update the fields
                    $jakdb->update("settings", ["used_value" => $jkp['jak_blog']], ["AND" => ["opid" => $opcacheid, "varname" => "blog_a"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_blogc']], ["AND" => ["opid" => $opcacheid, "varname" => "blogpostapprove"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_blog_home']], ["AND" => ["opid" => $opcacheid, "varname" => "blog_home"]]);
                    // $jakdb->update("settings", ["used_value" => $jkp['jak_blog_footer']], ["AND" => ["opid" => $opcacheid, "varname" => "blog_footer"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_blog_page']], ["AND" => ["opid" => $opcacheid, "varname" => "blog_page"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_blog_pagination']], ["AND" => ["opid" => $opcacheid, "varname" => "blog_pagination"]]);

                    // Now let us delete the define cache file
                    $cachestufffile = APP_PATH.JAK_CACHE_DIRECTORY.'/opcache'.$opcacheid.'.php';
                    if (file_exists($cachestufffile)) {
                        unlink($cachestufffile);
                    }

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

                    $_SESSION["successmsg"] = $jkl['g14'];
                    jak_redirect($_SESSION['LCRedirect']);

                }

            }

        }

        // Title and Description
        $SECTION_TITLE = $jkl["hd107"];
        $SECTION_DESC = "";

        // Call the template
        $template = 'blogsetting.php';
    break;
    case 'email':

        if ($_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['code'])) {

            //If this automatic URL doesn't work, set it yourself manually to the URL of this script
            $redirectUri = JAK_rewrite::jakParseurl('settings', 'email');

            $params = [
                'clientId' => JAK_OAUTH_CLIENTID,
                'clientSecret' => JAK_OAUTH_SECRET,
                'redirectUri' => $redirectUri,
                'accessType' => 'offline'
            ];

            $options = [];
            $provider = null;

            switch (JAK_OAUTH_PROVIDER) {
                case 'Google':
                    $provider = new Google($params);
                    $options = [
                        'scope' => [
                            'https://mail.google.com/'
                        ]
                    ];
                    break;
                case 'Yahoo':
                    $provider = new Yahoo($params);
                    break;
                case 'Microsoft':
                    $provider = new Microsoft($params);
                    $options = [
                        'scope' => [
                            'wl.imap',
                            'wl.offline_access'
                        ]
                    ];
                    break;
                case 'Azure':
                    $params['tenantId'] = JAK_OAUTH_TENANTID;

                    $provider = new Azure($params);
                    $options = [
                        'scope' => [
                            'https://outlook.office.com/SMTP.Send',
                            'offline_access'
                        ]
                    ];
                    break;
            }

            if (null === $provider) {
                // Something went wrong, try again.
                $_SESSION["errormsg"] = $jkl['g116'];
                jak_redirect($_SESSION['LCRedirect']);
            }

            if (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
                unset($_SESSION['oauth2state']);
                unset($_SESSION['oauth_provider']);
                
                // Something went wrong, try again.
                $_SESSION["errormsg"] = $jkl['g116'];
                jak_redirect($_SESSION['LCRedirect']);

            } else {
                unset($_SESSION['oauth_provider']);
                //Try to get an access token (using the authorization code grant)
                $token = $provider->getAccessToken(
                    'authorization_code',
                    [
                        'code' => $_GET['code']
                    ]
                );

                $oauth_token = $token->getRefreshToken();

                // We received a token
                if (!empty($oauth_token)) $jakdb->update("settings", ["used_value" => $oauth_token], ["AND" => ["opid" => $opcacheid, "varname" => "oauth_refresh"]]);

                // Now let us delete the define cache file
                $cachestufffile = APP_PATH.JAK_CACHE_DIRECTORY.'/opcache'.$opcacheid.'.php';
                if (file_exists($cachestufffile)) {
                    unlink($cachestufffile);
                }

                $_SESSION["successmsg"] = $jkl['g14'];
                jak_redirect($redirectUri);
            }
        }

        // Let's go on with the script
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $jkp = $_POST;
            
            if (isset($jkp['save'])) {

                // First we check if it is the same as the settings email address
                if (!filter_var($jkp['jak_smtpsender'], FILTER_VALIDATE_EMAIL)) {
                    $errors['e'] = $jkl['e3'];
                }

                // Then we check the clients table
                if (empty($errors['e1']) && jak_field_not_exist(strtolower($jkp['jak_smtpsender']), $jaktable, "emailanswer")) {
                    $errors['e1'] = $jkl['e18'];
                }

                if (count($errors) == 0) {

                    if (jak_get_access("settings", $jakuser->getVar("permissions"), JAK_MAIN_OP)) {

                        // Update the fields
                        $jakdb->update("settings", ["used_value" => $jkp['jak_smtpsender']], ["AND" => ["opid" => $opcacheid, "varname" => "smtp_sender"]]);
                        $jakdb->update("settings", ["used_value" => $jkp['jak_smpt']], ["AND" => ["opid" => $opcacheid, "varname" => "smtp_mail"]]);
                        $jakdb->update("settings", ["used_value" => $jkp['jak_host']], ["AND" => ["opid" => $opcacheid, "varname" => "smtphost"]]);
                        $jakdb->update("settings", ["used_value" => $jkp['jak_port']], ["AND" => ["opid" => $opcacheid, "varname" => "smtpport"]]);
                        $jakdb->update("settings", ["used_value" => $jkp['jak_alive']], ["AND" => ["opid" => $opcacheid, "varname" => "smtp_alive"]]);
                        $jakdb->update("settings", ["used_value" => $jkp['jak_auth']], ["AND" => ["opid" => $opcacheid, "varname" => "smtp_auth"]]);
                        $jakdb->update("settings", ["used_value" => $jkp['jak_prefix']], ["AND" => ["opid" => $opcacheid, "varname" => "smtp_prefix"]]);
                        $jakdb->update("settings", ["used_value" => $jkp['jak_smtpusername']], ["AND" => ["opid" => $opcacheid, "varname" => "smtpusername"]]);
                        $jakdb->update("settings", ["used_value" => $jkp['jak_smtppassword']], ["AND" => ["opid" => $opcacheid, "varname" => "smtppassword"]]);

                        // OAuth
                        $jakdb->update("settings", ["used_value" => $jkp['jak_oauthprovider']], ["AND" => ["opid" => $opcacheid, "varname" => "oauth_provider"]]);
                        $jakdb->update("settings", ["used_value" => $jkp['jak_oauthclientid']], ["AND" => ["opid" => $opcacheid, "varname" => "oauth_clientid"]]);
                        $jakdb->update("settings", ["used_value" => $jkp['jak_oauthsecret']], ["AND" => ["opid" => $opcacheid, "varname" => "oauth_secret"]]);
                        $jakdb->update("settings", ["used_value" => $jkp['jak_oauthtenantid']], ["AND" => ["opid" => $opcacheid, "varname" => "oauth_tenantid"]]);

                        if (JAK_SUPERADMINACCESS) {

                            // We are the super operator
                            $jakdb->update("settings", ["used_value" => $jkp['jak_smtpsender']], ["AND" => ["opid" => 0, "varname" => "smtp_sender"]]);
                            $jakdb->update("settings", ["used_value" => $jkp['jak_smpt']], ["AND" => ["opid" => 0, "varname" => "smtp_mail"]]);
                            $jakdb->update("settings", ["used_value" => $jkp['jak_host']], ["AND" => ["opid" => 0, "varname" => "smtphost"]]);
                            $jakdb->update("settings", ["used_value" => $jkp['jak_port']], ["AND" => ["opid" => 0, "varname" => "smtpport"]]);
                            $jakdb->update("settings", ["used_value" => $jkp['jak_alive']], ["AND" => ["opid" => 0, "varname" => "smtp_alive"]]);
                            $jakdb->update("settings", ["used_value" => $jkp['jak_auth']], ["AND" => ["opid" => 0, "varname" => "smtp_auth"]]);
                            $jakdb->update("settings", ["used_value" => $jkp['jak_prefix']], ["AND" => ["opid" => 0, "varname" => "smtp_prefix"]]);
                            $jakdb->update("settings", ["used_value" => $jkp['jak_smtpusername']], ["AND" => ["opid" => 0, "varname" => "smtpusername"]]);
                            $jakdb->update("settings", ["used_value" => $jkp['jak_smtppassword']], ["AND" => ["opid" => 0, "varname" => "smtppassword"]]);

                            // Now let us delete the define cache file
                            $cachestufffile = APP_PATH.JAK_CACHE_DIRECTORY.'/define.php';
                            if (file_exists($cachestufffile)) {
                                unlink($cachestufffile);
                            }
                        }

                        // Now let us delete the define cache file
                        $cachestufffile = APP_PATH.JAK_CACHE_DIRECTORY.'/opcache'.$opcacheid.'.php';
                        if (file_exists($cachestufffile)) {
                            unlink($cachestufffile);
                        }

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

                        $_SESSION["successmsg"] = $jkl['g14'];
                        jak_redirect($_SESSION['LCRedirect']);

                    }

                // Output the errors
                } else {
                    $errors = $errors;
                }

            // We get the refresh token
            } elseif (isset($jkp['refreshToken'])) {

                // First we check if it is the same as the settings email address
                if (empty($jkp['jak_oauthclientid'])) {
                    $errors['e5'] = $jkl['e26'];
                }

                // First we check if it is the same as the settings email address
                if (empty($jkp['jak_oauthsecret'])) {
                    $errors['e6'] = $jkl['e26'];
                }

                // First we check if it is the same as the settings email address
                if ($jkp['jak_oauthprovider'] == 3 && empty($jkp['jak_oauthtenantid'])) {
                    $errors['e7'] = $jkl['e14'];
                }

                if (count($errors) == 0) {

                    // OAuth
                    $jakdb->update("settings", ["used_value" => $jkp['jak_oauthprovider']], ["AND" => ["opid" => $opcacheid, "varname" => "oauth_provider"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_oauthclientid']], ["AND" => ["opid" => $opcacheid, "varname" => "oauth_clientid"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_oauthsecret']], ["AND" => ["opid" => $opcacheid, "varname" => "oauth_secret"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_oauthtenantid']], ["AND" => ["opid" => $opcacheid, "varname" => "oauth_tenantid"]]);

                    // Let's try to get the refresh token

                    $_SESSION['oauth_provider'] = $jkp['jak_oauthprovider'];
                    $_SESSION['oauth_clientId'] = $jkp['jak_oauthclientid'];
                    $_SESSION['oauth_clientSecret'] = $jkp['jak_oauthsecret'];
                    $_SESSION['oauth_tenantId'] = $jkp['jak_oauthtenantid'];

                    //If this automatic URL doesn't work, set it yourself manually to the URL of this script
                    $redirectUri = JAK_rewrite::jakParseurl('settings', 'email');

                    $params = [
                        'clientId' => $jkp['jak_oauthclientid'],
                        'clientSecret' => $jkp['jak_oauthsecret'],
                        'redirectUri' => $redirectUri,
                        'accessType' => 'offline'
                    ];

                    $options = [];
                    $provider = null;

                    switch ($jkp['jak_oauthprovider']) {
                        case 'Google':
                            $provider = new Google($params);
                            $options = [
                                'scope' => [
                                    'https://mail.google.com/'
                                ]
                            ];
                            break;
                        case 'Yahoo':
                            $provider = new Yahoo($params);
                            break;
                        case 'Microsoft':
                            $provider = new Microsoft($params);
                            $options = [
                                'scope' => [
                                    'wl.imap',
                                    'wl.offline_access'
                                ]
                            ];
                            break;
                        case 'Azure':
                            $params['tenantId'] = $tenantId;

                            $provider = new Azure($params);
                            $options = [
                                'scope' => [
                                    'https://outlook.office.com/SMTP.Send',
                                    'offline_access'
                                ]
                            ];
                            break;
                    }

                    //If we don't have an authorization code then get one
                    $authUrl = $provider->getAuthorizationUrl($options);
                    $_SESSION['oauth2state'] = $provider->getState();

                    // Now let us delete the define cache file
                    $cachestufffile = APP_PATH.JAK_CACHE_DIRECTORY.'/opcache'.$opcacheid.'.php';
                    if (file_exists($cachestufffile)) {
                        unlink($cachestufffile);
                    }

                    jak_redirect($authUrl);

                // Output the errors
                } else {
                    $errors = $errors;
                }

            } else {
        
                $mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
            
                // Send email the smpt way or else the mail way
                if (JAK_SMTP_MAIL == 1) {
                    
                    try {
                        $mail->CharSet = 'UTF-8';
                        // $mail->SMTPDebug = SMTP::DEBUG_SERVER;
                        $mail->IsSMTP(); // telling the class to use SMTP
                        $mail->Host = JAK_SMTPHOST;
                        $mail->SMTPAuth = (JAK_SMTP_AUTH ? true : false); // enable SMTP authentication
                        $mail->SMTPSecure = JAK_SMTP_PREFIX; // sets the prefix to the server
                        $mail->SMTPAutoTLS = false;
                        $mail->SMTPKeepAlive = (JAK_SMTP_ALIVE ? true : false); // SMTP connection will not close after each email sent
                        $mail->Port = JAK_SMTPPORT; // set the SMTP port for the GMAIL server
                        $mail->Username = JAK_SMTPUSERNAME; // SMTP account username
                        $mail->Password = JAK_SMTPPASSWORD;        // SMTP account password
                        $mail->SetFrom(JAK_SMTP_SENDER);
                        $mail->AddReplyTo(JAK_EMAIL);
                        $mail->AddAddress(JAK_EMAIL);
                        $mail->AltBody = $jkl["g215"]; // optional, comment out and test
                        $mail->Subject = $jkl["g216"];
                        $mail->MsgHTML($jkl["g217"].'SMTP.');
                        $mail->Send();
                        $success['e'] = $jkl["g217"].'SMTP.';
                    } catch (phpmailerException $e) {
                        $errors['e'] = $e->errorMessage(); //Pretty error messages from PHPMailer
                    } catch (Exception $e) {
                        $errors['e'] = $e->getMessage(); //Boring error messages from anything else!
                    }

                    // Write the log file each time someone login after to show success
                    JAK_base::jakWhatslog('', $opcacheid, JAK_USERID, 0, 48, 0, (isset($_COOKIE['WIOgeoData']) ? $_COOKIE['WIOgeoData'] : ''), $jakuser->getVar("username"), $_SERVER['REQUEST_URI'], $ipa, $valid_agent);
                    
                } elseif (JAK_SMTP_MAIL == 2) {
                    // OAuth2 sending
                    jak_send_email(JAK_EMAIL, "", "", $jkl["g216"], $jkl["g217"].'SMTP - OAuth2.', "");

                    $_SESSION["successmsg"] = $jkl["g217"].'SMTP - OAuth2.';
                    jak_redirect($_SESSION['LCRedirect']);

                } else {
                
                    try {
                        $mail->SetFrom(JAK_SMTP_SENDER);
                        $mail->AddReplyTo(JAK_EMAIL);
                        $mail->AddAddress(JAK_EMAIL);
                        $mail->AltBody = $jkl["g215"]; // optional, comment out and test
                        $mail->Subject = $jkl["g216"];
                        $mail->MsgHTML($jkl["g217"].'Mail().');
                        $mail->Send();
                        $success['e'] = $jkl["g217"].'Mail().';
                    } catch (phpmailerException $e) {
                        $errors['e'] = $e->errorMessage(); //Pretty error messages from PHPMailer
                    } catch (Exception $e) {
                        $errors['e'] = $e->getMessage(); //Boring error messages from anything else!
                    }

                    // Write the log file each time someone login after to show success
                    JAK_base::jakWhatslog('', $opcacheid, JAK_USERID, 0, 47, 0, (isset($_COOKIE['WIOgeoData']) ? $_COOKIE['WIOgeoData'] : ''), $jakuser->getVar("username"), $_SERVER['REQUEST_URI'], $ipa, $valid_agent);
                
                }
            }
        }

        // Title and Description
        $SECTION_TITLE = $jkl["hd119"];
        $SECTION_DESC = "";

        // Include the javascript file for results
        $js_file_footer = 'js_email.php';

        // Call the template
        $template = 'emailsetting.php';
    break;
    case 'phpimap':

        // Check if the user has access to this file
        if (!jak_get_access("support", $jakuser->getVar("permissions"), JAK_MAIN_OP)) jak_redirect(BASE_URL);

        switch ($page2) {
            case 'edit':
                // Check if the user exists
                if (is_numeric($page3) && jak_row_exist($page3, $opcacheid, $jaktable)) {
                
                    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
                    $jkp = $_POST;

                    if (isset($jkp['save'])) {
                
                        if (empty($jkp['mailbox'])) {
                            $errors['e'] = $jkl['e'];
                        }

                        if (empty($jkp['usrphpimap'])) {
                            $errors['e1'] = $jkl['e7'];
                        }

                        if (!filter_var($jkp['email'], FILTER_VALIDATE_EMAIL)) {
                            $errors['e2'] = $jkl['e3'];
                        }

                        // Now we make sure the email address is not used elsewhere
                        if (empty($errors['e2'])) {

                            // First we check if it is the same as the settings email address
                            if (empty($errors['e2']) && $jkp['email'] == JAK_EMAIL) {
                                $errors['e2'] = $jkl['e18'];
                            }

                            // Then we check the php imap table
                            if (empty($errors['e2']) && jak_field_not_exist_id(strtolower($jkp['email']), $page3, $jaktable, "emailanswer")) {
                                $errors['e2'] = $jkl['e18'];
                            }

                            // Then we check the clients table
                            if (empty($errors['e2']) && jak_field_not_exist(strtolower($jkp['email']), $jaktable7, "email")) {
                                $errors['e2'] = $jkl['e18'];
                            }

                            // Then we check the user table
                            if (empty($errors['e2']) && jak_field_not_exist(strtolower($jkp['email']), $jaktable8, "email")) {
                                $errors['e2'] = $jkl['e18'];
                            }
                        }
                        
                        if (count($errors) == 0) {

                            $result = $jakdb->update($jaktable, ["depid" => $jkp['jak_depid'],
                              "mailbox" => $jkp['mailbox'],
                              "username" => $jkp['usrphpimap'],
                              "password" => $jkp['passphpimap'],
                              "encryption" => $jkp['encryption'],
                              "scanfolder" => $jkp['inbox'],
                              "emailanswer" => strtolower($jkp['email']),
                              "msgdel" => $jkp['jak_msgdel'],
                              "attachemail" => $jkp['jak_attachemail'],
                              "takeattach" => $jkp['jak_takeattach'],
                              "created" => $jakdb->raw("NOW()")], ["AND" => ["opid" => $opcacheid, "id" => $page3]]);
                    
                            if (!$result) {
                                $_SESSION["infomsg"] = $jkl['i'];
                                jak_redirect($_SESSION['LCRedirect']);
                            } else {

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

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

                    } else {

                        if (!file_exists(APP_PATH.'class/class.imap.php')) die('settings.php] class.imap.php not exist, test impossible.');
                        require_once APP_PATH.'class/class.imap.php';

                        // Test the imap connection
                        $imap = new Imap($jkp["mailbox"], $jkp["usrphpimap"], $jkp["passphpimap"], $jkp["encryption"]);

                        if ($imap->isConnected()) {

                            $success['e'] = $jkl['hd55'].' - '.$jkl['g14'];

                        } else {

                            $errors['e4'] = "Following error occured when trying to connect to the mailbox ".$jkp["mailbox"].", with username ".$jkp["usrphpimap"].": ".$imap->getError();

                            // close connection
                            $imap->close();

                        }

                    }
                
                }

                    // Get all departments
                    $JAK_DEPARTMENTS = $jakdb->select($jaktable1, ["id", "title"], ["opid" => $opcacheid, "ORDER" => ["dorder" => "ASC"]]);
                
                    $JAK_FORM_DATA = jak_get_data($page3, $opcacheid, $jaktable);
                    
                    // Title and Description
                    $SECTION_TITLE = $jkl["hd45"];
                    $SECTION_DESC = "";

                    // Include the javascript file for results
                    $js_file_footer = 'js_settings.php';
                    
                    // Call the template
                    $template = 'editphpimap.php';
                
                } else {
                    $_SESSION["infomsg"] = $jkl['i3'];
                    jak_redirect(JAK_rewrite::jakParseurl('settings', 'phpimap'));
                }
            break;
            case 'delete':
                // Check if user exists and can be deleted
                if (is_numeric($page3)) {
                        
                    // Now check how many languages are installed and do the dirty work
                    $result = $jakdb->delete($jaktable, ["AND" => ["opid" => $opcacheid, "id" => $page3]]);
                
                if (!$result) {
                    $_SESSION["infomsg"] = $jkl['i'];
                    jak_redirect($_SESSION['LCRedirect']);
                } else {

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

                    $_SESSION["successmsg"] = $jkl['g14'];
                    jak_redirect($_SESSION['LCRedirect']);
                }
                    
                } else {
                    $_SESSION["infomsg"] = $jkl['i2'];
                    jak_redirect($_SESSION['LCRedirect']);
                }
            break;
            case 'lock':
                // Check if user exists and can be deleted
                if (is_numeric($page3)) {

                    // Check what we have to do
                    $datausrac = $jakdb->get($jaktable, "active", ["AND" => ["opid" => $opcacheid, "id" => $page3]]);
                    // update the table
                    if ($datausrac) {
                        $result = $jakdb->update($jaktable, ["active" => 0], ["AND" => ["opid" => $opcacheid, "id" => $page3]]);
                    } else {
                        $result = $jakdb->update($jaktable, ["active" => 1], ["AND" => ["opid" => $opcacheid, "id" => $page3]]);
                    }
                    
                    if (!$result) {
                        $_SESSION["infomsg"] = $jkl['i'];
                        jak_redirect($_SESSION['LCRedirect']);
                    } else {
                        $_SESSION["successmsg"] = $jkl['g14'];
                        jak_redirect($_SESSION['LCRedirect']);
                    }
                
                } else {
                    $_SESSION["errormsg"] = $jkl['i3'];
                    jak_redirect($_SESSION['LCRedirect']);
                }
            break;
            
            default:

                // Let's check if we can add more users
                $totalphp = $jakdb->count($jaktable, ["opid" => JAK_USERID]);
                if ($totalphpimap > $totalphp) $addphpimap = true;

                // Add new PHP IMAP connection
                if ($_SERVER['REQUEST_METHOD'] == 'POST') {
                    $jkp = $_POST;
                    
                    // No more, so what you doing here?
                    if (!$addphpimap) jak_redirect(BASE_URL);
                    
                    if (isset($_POST['insert_phpimap'])) {
                    
                    if (empty($jkp['mailbox'])) {
                        $errors['e'] = $jkl['e'];
                    }

                    if (!filter_var($jkp['email'], FILTER_VALIDATE_EMAIL)) {
                        $errors['e2'] = $jkl['e3'];
                    }
                    
                    if (empty($jkp['usrphpimap'])) {
                        $errors['e1'] = $jkl['e7'];
                    }

                    // Now we make sure the email address is not used elsewhere
                    if (empty($errors['e2'])) {

                            // First we check if it is the same as the settings email address
                        if (empty($errors['e2']) && $jkp['email'] == JAK_EMAIL) {
                            $errors['e2'] = $jkl['e18'];
                        }

                        // Then we check the php imap table
                        if (empty($errors['e2']) && jak_field_not_exist(strtolower($jkp['email']), $jaktable, "emailanswer")) {
                            $errors['e2'] = $jkl['e18'];
                        }

                        // Then we check the clients table
                        if (empty($errors['e2']) && jak_field_not_exist(strtolower($jkp['email']), $jaktable7, "email")) {
                            $errors['e2'] = $jkl['e18'];
                        }

                        // Then we check the user table
                        if (empty($errors['e2']) && jak_field_not_exist(strtolower($jkp['email']), $jaktable8, "email")) {
                            $errors['e2'] = $jkl['e18'];
                        }
                    }
                        
                    if (count($errors) == 0) {

                        $result = $jakdb->insert($jaktable, ["opid" => $opcacheid,
                            "depid" => $jkp['jak_depid'],
                            "mailbox" => $jkp['mailbox'],
                            "username" => $jkp['usrphpimap'],
                            "password" => $jkp['passphpimap'],
                            "encryption" => $jkp['encryption'],
                            "scanfolder" => $jkp['inbox'],
                            "emailanswer" => strtolower($jkp['email']),
                            "created" => $jakdb->raw("NOW()")]);

                        $lastid = $jakdb->id();
                    
                        if (!$result) {
                            $_SESSION["infomsg"] = $jkl['i'];
                            jak_redirect($_SESSION['LCRedirect']);
                        } else {

                            // Write the log file each time someone login after to show success
                            JAK_base::jakWhatslog('', $opcacheid, JAK_USERID, 0, 45, $lastid, (isset($_COOKIE['WIOgeoData']) ? $_COOKIE['WIOgeoData'] : ''), $jakuser->getVar("username"), $_SERVER['REQUEST_URI'], $ipa, $valid_agent);

                            $_SESSION["successmsg"] = $jkl['g14'];
                            jak_redirect($_SESSION['LCRedirect']);
                        }
                    
                    // Output the errors
                    } else {
                    
                        $errors = $errors;
                    }
                 }
           
                 }
                 
                // Get all departments
                $JAK_DEPARTMENTS = $jakdb->select($jaktable1, ["id", "title"], ["opid" => $opcacheid, "ORDER" => ["dorder" => "ASC"]]);
        
                // Get all php imap connections from this user
                $PHPIMAP_ALL = jak_get_page_info($jaktable, ["opid" => $opcacheid]);

                // Get the totals
                $totalAll = $jakdb->count($jaktable, ["opid" => $opcacheid]);
                 
                // Title and Description
                $SECTION_TITLE = $jkl["hd44"];
                $SECTION_DESC = "";
                 
                // Call the template
                $template = 'phpimap.php';
            break;
        }
    break;
    
    default:

    // Check if the user has access to this file
    if (!jak_get_access("settings", $jakuser->getVar("permissions"), JAK_MAIN_OP) && !jak_get_access("blocklist", $jakuser->getVar("permissions"), JAK_MAIN_OP)) jak_redirect(BASE_URL);

    // Let's go on with the script
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $jkp = $_POST;
        
        if (isset($jkp['save'])) {

            if (jak_get_access("settings", $jakuser->getVar("permissions"), JAK_MAIN_OP)) {
        
                if ($jkp['jak_email'] == '' || !filter_var($jkp['jak_email'], FILTER_VALIDATE_EMAIL)) { 
                  $errors['e1'] = $jkl['e3'];
                }

                if (isset($jkp['jak_custom_domain']) && !empty($jkp['jak_custom_domain']) && $jakdb->has("subscriptions", ["AND" => ["opid[!]" => $opcacheid, "custom_domain" => trim($jkp['jak_custom_domain'])]])) {
                    $errors['e2'] = $jkl['i4'];
                }
                
                if ($jkp['jak_lang'] == '') { $errors['e6'] = $jkl['e29']; }

                if (count($errors) == 0) {

                    // Clean the dsgvo link
                    include_once '../include/htmlawed.php';
                    $htmlconfig = array('comment'=>0, 'cdata'=>1, 'elements'=>'a, strong'); 
                    $dsgvo_clean = htmLawed($_REQUEST['jak_dsgvo'], $htmlconfig);

                    // Update the fields
                    $jakdb->update("settings", ["used_value" => $jkp['jak_title']], ["AND" => ["opid" => $opcacheid, "varname" => "title"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_email']], ["AND" => ["opid" => $opcacheid, "varname" => "email"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_emailcc']], ["AND" => ["opid" => $opcacheid, "varname" => "emailcc"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_holidaym']], ["AND" => ["opid" => $opcacheid, "varname" => "holiday_mode"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_billing']], ["AND" => ["opid" => $opcacheid, "varname" => "billing_mode"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_trans']], ["AND" => ["opid" => $opcacheid, "varname" => "send_tscript"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_rating']], ["AND" => ["opid" => $opcacheid, "varname" => "crating"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_showip']], ["AND" => ["opid" => $opcacheid, "varname" => "show_ips"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_lang']], ["AND" => ["opid" => $opcacheid, "varname" => "lang"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_date']], ["AND" => ["opid" => $opcacheid, "varname" => "dateformat"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_time']], ["AND" => ["opid" => $opcacheid, "varname" => "timeformat"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_timezone_server']], ["AND" => ["opid" => $opcacheid, "varname" => "timezoneserver"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_ringtone']], ["AND" => ["opid" => $opcacheid, "varname" => "ring_tone"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_msgtone']], ["AND" => ["opid" => $opcacheid, "varname" => "msg_tone"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_register']], ["AND" => ["opid" => $opcacheid, "varname" => "register"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['showalert']], ["AND" => ["opid" => $opcacheid, "varname" => "pro_alert"]]);

                    $jakdb->update("settings", ["used_value" => $jkp['jak_emailtpllogo']], ["AND" => ["opid" => $opcacheid, "varname" => "emailtpllogo"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_emailtplcopy']], ["AND" => ["opid" => $opcacheid, "varname" => "emailtplcopy"]]);

                    $jakdb->update("settings", ["used_value" => $jkp['ip_block']], ["AND" => ["opid" => $opcacheid, "varname" => "ip_block"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['email_block']], ["AND" => ["opid" => $opcacheid, "varname" => "email_block"]]);
                    
                    $jakdb->update("settings", ["used_value" => $jkp['jak_twilio_nexmo']], ["AND" => ["opid" => $opcacheid, "varname" => "twilio_nexmo"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_tw_phone']], ["AND" => ["opid" => $opcacheid, "varname" => "tw_phone"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_tw_msg']], ["AND" => ["opid" => $opcacheid, "varname" => "tw_msg"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_tw_sid']], ["AND" => ["opid" => $opcacheid, "varname" => "tw_sid"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_tw_token']], ["AND" => ["opid" => $opcacheid, "varname" => "tw_token"]]);
                    
                    $jakdb->update("settings", ["used_value" => $jkp['jak_client_push_not']], ["AND" => ["opid" => $opcacheid, "varname" => "client_push_not"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_engage_sound']], ["AND" => ["opid" => $opcacheid, "varname" => "engage_sound"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_client_sound']], ["AND" => ["opid" => $opcacheid, "varname" => "client_sound"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_engage_icon']], ["AND" => ["opid" => $opcacheid, "varname" => "engage_icon"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_chat_upload_standard']], ["AND" => ["opid" => $opcacheid, "varname" => "chat_upload_standard"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_template']], ["AND" => ["opid" => $opcacheid, "varname" => "front_template"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_chatwidget_id']], ["AND" => ["opid" => $opcacheid, "varname" => "chatwidget_id"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['api_profile']], ["AND" => ["opid" => $opcacheid, "varname" => "api_profile"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_facebookid']], ["AND" => ["opid" => $opcacheid, "varname" => "facebook_app_id"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_offline_page']], ["AND" => ["opid" => $opcacheid, "varname" => "offline_cms_page"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_stripe_publish']], ["AND" => ["opid" => $opcacheid, "varname" => "stripe_publish_key"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_stripe_secret']], ["AND" => ["opid" => $opcacheid, "varname" => "stripe_secret_key"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_paypal_client']], ["AND" => ["opid" => $opcacheid, "varname" => "paypal_client"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_paypal_secret']], ["AND" => ["opid" => $opcacheid, "varname" => "paypal_secret"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_sandbox']], ["AND" => ["opid" => $opcacheid, "varname" => "sandbox_mode"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_yookassa_id']], ["AND" => ["opid" => $opcacheid, "varname" => "yookassa_id"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_yookassa_secret']], ["AND" => ["opid" => $opcacheid, "varname" => "yookassa_secret"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_paystack_secret']], ["AND" => ["opid" => $opcacheid, "varname" => "paystack_secret"]]);
                    // $jakdb->update("settings", ["used_value" => $jkp['jak_twoco']], ["AND" => ["opid" => $opcacheid, "varname" => "twoco"]]);
                    // $jakdb->update("settings", ["used_value" => $jkp['jak_twoco_secret']], ["AND" => ["opid" => $opcacheid, "varname" => "twoco_secret"]]);
                    // $jakdb->update("settings", ["used_value" => $jkp['jak_authorize_id']], ["AND" => ["opid" => $opcacheid, "varname" => "authorize_id"]]);
                    // $jakdb->update("settings", ["used_value" => $jkp['jak_authorize_key']], ["AND" => ["opid" => $opcacheid, "varname" => "authorize_key"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_calendar_tickets']], ["AND" => ["opid" => $opcacheid, "varname" => "calendar_tickets"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_calendar_chats']], ["AND" => ["opid" => $opcacheid, "varname" => "calendar_chats"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_calendar_offline']], ["AND" => ["opid" => $opcacheid, "varname" => "calendar_offline"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_calendar_purchases']], ["AND" => ["opid" => $opcacheid, "varname" => "calendar_purchases"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_openop']], ["AND" => ["opid" => $opcacheid, "varname" => "openop"]]);
                    $jakdb->update("settings", ["used_value" => trim($dsgvo_clean)], ["varname" => "dsgvo_contact"]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_chatgptbot']], ["AND" => ["opid" => $opcacheid, "varname" => "openai_chatgpt"]]);
                    $jakdb->update("settings", ["used_value" => $jkp['jak_openaiapikey']], ["AND" => ["opid" => $opcacheid, "varname" => "openai_apikey"]]);

                    // Custom Domain Settings
                    if (JAK_SUPERADMINACCESS || JAK_MAIN_OP) {
                        if (!$jakdb->has("subscriptions", ["AND" => ["opid[!]" => $opcacheid, "custom_domain" => trim($jkp['jak_custom_domain'])]])) {
                            $jakdb->update("subscriptions", ["custom_domain" => trim($jkp['jak_custom_domain'])], ["opid" => $opcacheid]);
                        }
                    }

                    if (JAK_SUPERADMINACCESS) {
                        $jakdb->update("settings", ["used_value" => $jkp['jak_email']], ["AND" => ["opid" => 0, "varname" => "email"]]);
                        $jakdb->update("settings", ["used_value" => $jkp['allowed_files']], ["AND" => ["opid" => 0, "varname" => "allowed_files"]]);
                        $jakdb->update("settings", ["used_value" => $jkp['allowedo_files']], ["AND" => ["opid" => 0, "varname" => "allowedo_files"]]);
                        $jakdb->update("settings", ["used_value" => $jkp['jak_avatwidth']], ["AND" => ["opid" => 0, "varname" => "useravatwidth"]]);
                        $jakdb->update("settings", ["used_value" => $jkp['jak_avatheight']], ["AND" => ["opid" => 0, "varname" => "useravatheight"]]);
                        $jakdb->update("settings", ["used_value" => $jkp['jak_user_expired']], ["AND" => ["opid" => 0, "varname" => "client_expired"]]);
                        $jakdb->update("settings", ["used_value" => $jkp['jak_user_left']], ["AND" => ["opid" => 0, "varname" => "client_left"]]);
                        $jakdb->update("settings", ["used_value" => $jkp['jak_pushrem']], ["AND" => ["opid" => 0, "varname" => "push_reminder"]]);
                        $jakdb->update("settings", ["used_value" => $jkp['jak_proactive_time']], ["AND" => ["opid" => 0, "varname" => "proactive_time"]]);
                        $jakdb->update("settings", ["used_value" => trim($jkp['jak_nativtok'])], ["AND" => ["opid" => 0, "varname" => "native_app_token"]]);
                        $jakdb->update("settings", ["used_value" => trim($jkp['jak_nativkey'])], ["AND" => ["opid" => 0, "varname" => "native_app_key"]]);
                        $jakdb->update("settings", ["used_value" => $jkp['jak_recapclient']], ["AND" => ["opid" => 0, "varname" => "recap_client"]]);
                        $jakdb->update("settings", ["used_value" => $jkp['jak_recapserver']], ["AND" => ["opid" => 0, "varname" => "recap_server"]]);
                        $jakdb->update("settings", ["used_value" => $jkp['jak_live_online_status']], ["AND" => ["opid" => 0, "varname" => "live_online_status"]]);
                        $jakdb->update("settings", ["used_value" => trim($jkp['envato_token'])], ["AND" => ["opid" => 0, "varname" => "envato_api_token"]]);
                    }

                    // 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']);
                    }

                    // Update the standard departments
                    $jakdb->update("settings", ["used_value" => $depa], ["AND" => ["opid" => $opcacheid, "varname" => "standard_chat_dep"]]);
                    $jakdb->update("settings", ["used_value" => $depas], ["AND" => ["opid" => $opcacheid, "varname" => "standard_support_dep"]]);
                    $jakdb->update("settings", ["used_value" => $depaf], ["AND" => ["opid" => $opcacheid, "varname" => "standard_faq_cat"]]);


                    $ss = true;

                } else {
        
                    $errors['e'] = $jkl['e'];
                    $errors = $errors;
                }


            } elseif (jak_get_access("blocklist", $jakuser->getVar("permissions"), JAK_MAIN_OP)) {
                $jakdb->update("settings", ["used_value" => $jkp['ip_block']], ["AND" => ["opid" => $opcacheid, "varname" => "ip_block"]]);
                $jakdb->update("settings", ["used_value" => $jkp['email_block']], ["AND" => ["opid" => $opcacheid, "varname" => "email_block"]]);
                $ss = true;
            }

            if ($ss) {
            
                if (JAK_SUPERADMINACCESS) {
                    // Now let us delete the all the cache file
                    $cacheallfiles = APP_PATH.JAK_CACHE_DIRECTORY.'/';
                    $msfi = glob($cacheallfiles."*.php");
                    if ($msfi) foreach ($msfi as $filen) {
                        if (file_exists($filen)) unlink($filen);
                    }
                } else {

                    // Now let us delete the user cache file
                    $cachestufffile = APP_PATH.JAK_CACHE_DIRECTORY.'/opcache'.$opcacheid.'.php';
                    if (file_exists($cachestufffile)) {
                        unlink($cachestufffile);
                    }

                }

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

                $_SESSION["successmsg"] = $jkl['g14'];
                jak_redirect($_SESSION['LCRedirect']);

            }
        }
    }

    // Get the unique api key
    $api_key = hash_hmac('md5', FULL_SITE_DOMAIN.JAK_O_NUMBER, DB_PASS_HASH);
    $api_key1 = hash_hmac('md5', JAK_O_NUMBER.FULL_SITE_DOMAIN, DB_PASS_HASH);

    // Call the settings function
    $lang_files = jak_get_lang_files();

    // Get all sound files
    $sound_files = jak_get_sound_files();

    // Get all templates
    $templates = jak_get_templates();

    // Get all departments / categories
    $JAK_DEPARTMENTS = $jakdb->select($jaktable2, ["id", "title"], ["opid" => $opcacheid, "ORDER" => ["dorder" => "ASC"]]);
    $JAK_DEP_SUPPORT = $jakdb->select($jaktable1, ["id", "title"], ["opid" => $opcacheid, "ORDER" => ["dorder" => "ASC"]]);
    $JAK_CAT_FAQ = $jakdb->select($jaktable3, ["id", "title"], ["opid" => $opcacheid, "ORDER" => ["dorder" => "ASC"]]);
    $JAK_CMS_PAGES = $jakdb->select($jaktable4, ["id", "title"], ["opid" => $opcacheid, "ORDER" => ["dorder" => "ASC"]]);
    // Get all chat widgets
    $CHATWIDGET_ALL = $jakdb->select($jaktable9, ["id", "title"], ["opid" => $opcacheid, "ORDER" => ["title" => "ASC"]]);
    // Get the custom domain if any
    $custom_domain = $jakdb->get("subscriptions", "custom_domain", ["opid" => $opcacheid]);

    // Title and Description
    $SECTION_TITLE = $jkl["m5"];
    $SECTION_DESC = "";

    // Include the javascript file for results
    $js_file_footer = 'js_settings.php';

    // Call the template
    if (jak_get_access("settings", $jakuser->getVar("permissions"), JAK_MAIN_OP)) {
        $template = 'setting.php';
    } else {
        $template = 'blockvisitors.php';
    }

}
?>
