<?php
/**
 *  Copyright (C) 2021  Double Bastion LLC
 *
 *  This file is part of Roundpin, which is licensed under the
 *  GNU Affero General Public License Version 3.0. The license terms
 *  are detailed in the "LICENSE.txt" file located in the root directory.
 */

session_start();

 // header('Set-Cookie: PHPSESSID= ' . session_id() . '; SameSite=strict; Secure=true; HttpOnly=true;');

if (isset($_POST['s_ajax_call']) && ($_POST['s_ajax_call'] == $_SESSION['validate_s_access'])) {


    define('ACCESSCONST', TRUE);

    require('db-connect.php');

    $username = $_POST['username'];
    $wssServer = $_POST['wss_server'];
    $webSocketPort = $_POST['web_socket_port'];
    $serverPath = $_POST['server_path'];
    $profileName = $_POST['profile_name'];
    $sipUsername = $_POST['sip_username'];
    $sipPasswordPre = $_POST['sip_password'];
    $stunServer = $_POST['stun_server'];
    $audioOutputId = $_POST['audio_output_id'];
    $videoSrcId = $_POST['video_src_id'];
    $videoHeight = $_POST['video_height'];
    $frameRate = $_POST['frame_rate'];
    $aspectRatio = $_POST['aspect_ratio'];
    $videoOrientation = $_POST['video_orientation'];
    $ringTone = $_POST['ringtone'];
    $audioSrcId = $_POST['audio_src_id'];
    $autoGainControl = $_POST['auto_gain_control'];
    $echoCancellation = $_POST['echo_cancellation'];
    $noiseSuppression = $_POST['noise_suppression'];
    $ringOutputId = $_POST['ring_output_id'];
    $videoConfWindowWidth = $_POST['video_conf_window_width'];
    $profilePicture = $_POST['profile_picture'];
    $language = $_POST['language'];
    $notifications = $_POST['notifications'];
    $showVconfNames = $_POST['show_vconf_usernames'];
    $displayVconfUser = $_POST['display_vconf_user'];
    $useEmail = $_POST['use_email'];
    $rcDomain = $_POST['rcdomain'];
    $rcBasicAuthUser = $_POST['rcbasicauthuser'];
    $rcBasicAuthPass = $_POST['rcbasicauthpass'];
    $rcUser = $_POST['rcuser'];
    $rcPassword = $_POST['rcpassword'];
    $loadGroups = $_POST['load_groups'];
    $voicenmb = $_POST['voicenmb'];
    $voicedefnmb = $_POST['voicedefnmb'];
    $smsnmb = $_POST['smsnmb'];
    $smsdefnmb = $_POST['smsdefnmb'];
    $telsecretkey = $_POST['telsecretkey'];
    $telfaxappid = $_POST['telfaxappid'];
    $telrecwhurl = $_POST['telrecwhurl'];
    $phaxapikey = $_POST['phaxapikey'];
    $phaxapisecret = $_POST['phaxapisecret'];
    $phaxwebhooktoken = $_POST['phaxwebhooktoken'];
    $phaxreceiveurl = $_POST['phaxreceiveurl'];
    $faxnotification = $_POST['faxnotification'];
    $faxnotifyemail = $_POST['faxnotifyemail'];
    $faxnmb = $_POST['faxnmb'];
    $faxdefnmb = $_POST['faxdefnmb'];

    $messageupdata5 = 'success';
    $messageupdata6 = 'success';
    $messageupdata7 = 'success';
    $messageupdata8 = 'success';
    $messageupdata9 = 'success';
    $messageupdata10 = 'success';
    $messageupdata11 = 'success';
    $messageupdata12 = 'success';


    // Get the id of the current user from the 'app_users' table
    $queryselid = $mysqli->prepare("SELECT id, username FROM app_users WHERE BINARY username = ?");
    $queryselid->bind_param("s", $username);
    $queryselid->execute(); 
    $queryselid = $queryselid->get_result()->fetch_assoc();
    $userid = $queryselid['id'];


    // Remove the directories for temporary files from the 'src/email-to-fax/tmp' folder, for the current user, if any
    $queryfaxwhurl = $mysqli->prepare("SELECT userid, tel_recwh_url, phax_receive_url FROM fax_settings WHERE userid = ?");
    $queryfaxwhurl->bind_param("i", $userid);
    $queryfaxwhurl->execute(); 
    $queryfxurlres = $queryfaxwhurl->get_result()->fetch_assoc();
    $telnyxurl = $queryfxurlres['tel_recwh_url'];
    $phaxiourl = $queryfxurlres['phax_receive_url'];

    if ($queryfxurlres) {

        if ($telnyxurl) {

            // Remove the directory for temporary files from the 'src/email-to-fax/tmp' folder, for the current user, for Telnyx, if any
            $usertmpdirtxarr = explode("/", $telnyxurl);
            $usertmpdirtxpre = array_reverse($usertmpdirtxarr);
            $usertmpdirtx = substr($usertmpdirtxpre[0], 8, 20);
            if (is_dir(dirname(__FILE__) . '/email-to-fax/tmp/' . $usertmpdirtx)) {
                array_map('unlink', glob(dirname(__FILE__) . '/email-to-fax/tmp/' . $usertmpdirtx . "/*"));
                rmdir(dirname(__FILE__) . '/email-to-fax/tmp/' . $usertmpdirtx);
            }


            if ($telrecwhurl) {

                // Remove the files with random alphanumeric strings as names, that were previously created to receive webhook requests from Telnyx
                foreach (glob(dirname(__FILE__) . "/telnyxfaxwh-*.php") as $flnametx) { unlink($flnametx); }

                // Create a new file having a random alphanumeric string as name, to prevent unwanted access, since its name will be part of the webhook URL for Telnyx
                $telrecwhurlarr = explode("/", $telrecwhurl);
                $telrecwhfile = end($telrecwhurlarr);
                // The atypical indentation that follows is intentional
                $texttosavetx = "<?php
/**
 *  Copyright (C) 2021  Double Bastion LLC
 *
 *  This file is part of Roundpin, which is licensed under the
 *  GNU Affero General Public License Version 3.0. The license terms
 *  are detailed in the 'LICENSE.txt' file located in the root directory.
 */

include(dirname(__FILE__) . '/receive-telnyx-fax-webhooks.php');
?>";
                file_put_contents(dirname(__FILE__) . "/" . $telrecwhfile, $texttosavetx);
            }   
        }

        if ($phaxiourl) {

            // Remove the directory for temporary files from the 'src/email-to-fax/tmp' folder, for the current user, for Phaxio, if any
            $usertmpdirpharr = explode("/", $phaxiourl);
            $usertmpdirphpre = array_reverse($usertmpdirpharr);
            $usertmpdirph = substr($usertmpdirphpre[0], 9, 20);
            if (is_dir(dirname(__FILE__) . '/email-to-fax/tmp/' . $usertmpdirph)) {
                array_map('unlink', glob(dirname(__FILE__) . '/email-to-fax/tmp/' . $usertmpdirph . "/*"));
                rmdir(dirname(__FILE__) . '/email-to-fax/tmp/' . $usertmpdirph);
            }


            if ($phaxreceiveurl) {

                // Remove the files with random alphanumeric strings as names, that were previously created to receive webhook requests from Phaxio
                foreach (glob(dirname(__FILE__) . "/phaxiofaxwh-*.php") as $flnameph) { unlink($flnameph); }

                // Create a new file having a random alphanumeric string as name, to prevent unwanted access, since its name will be part of the webhook URL for Phaxio
                $phaxrecwhurlarr = explode("/", $phaxreceiveurl);
                $phaxrecwhfile = end($phaxrecwhurlarr);
                // The atypical indentation that follows is intentional
                $texttosaveph = "<?php
/**
 *  Copyright (C) 2021  Double Bastion LLC
 *
 *  This file is part of Roundpin, which is licensed under the
 *  GNU Affero General Public License Version 3.0. The license terms
 *  are detailed in the 'LICENSE.txt' file located in the root directory.
 */

include(dirname(__FILE__) . '/receive-phaxio-fax-webhooks.php');
?>";
                file_put_contents(dirname(__FILE__) . "/" . $phaxrecwhfile, $texttosaveph);
            }
        }
    }


    // Encrypt the SIP password, the keys from the Fax and SMS sections (if any), Roundcube password (if any) and Roundcube basic auth password (if any), before inserting them into the database

    if ($sipPasswordPre != '' && $sipPasswordPre != "%20%20%20%20%20%20%20") {

        $keypass = substr(sha1((string) mt_rand()), 0, 32);
        $keysalt = openssl_random_pseudo_bytes(12);
        $generated_key = openssl_pbkdf2($keypass, $keysalt, 40, 100, 'sha256');
        $psswdadded = bin2hex($generated_key);

        if (!is_dir('../restr')) {
            mkdir('../restr', 0700);
        }

        if (!is_dir('../restr/' . $username . '')) {
            mkdir('../restr/' . $username . '', 0700);
        }

        if (file_put_contents('../restr/' . $username . '/pwdkey', $psswdadded)) { $messageupdatasippwd1 = 'success'; } else { $messageupdatasippwd1 = 'failure'; }
        if (chmod('../restr/' . $username . '/pwdkey', 0600)) { $messageupdatasippwd2 = 'success'; } else { $messageupdatasippwd2 = 'failure'; }
        if ($messageupdatasippwd1 == 'success' && $messageupdatasippwd2 == 'success') { $messageupdata5 = 'success'; } else { $messageupdata5 = 'failure'; }

        $iv = substr(sha1((string) mt_rand()), 0, 16);
        $encpwdin = openssl_encrypt($sipPasswordPre, 'AES-256-CBC', $psswdadded, false, $iv);
        $sipPasswordEnc = $encpwdin.':'.$iv;

    } elseif ($sipPasswordPre == "%20%20%20%20%20%20%20") {

              $queryselsippass = $mysqli->prepare("SELECT username, sip_password FROM app_users WHERE BINARY username = ?");
              $queryselsippass->bind_param("s", $username);
              $queryselsippass->execute();
              $sippassarr = $queryselsippass->get_result()->fetch_assoc();
              $sipPasswordEnc = $sippassarr['sip_password'];

    } elseif ($sipPasswordPre == '') {
              $sipPasswordEnc = '';

    } else { $sipPasswordEnc = ''; }


    if ($telsecretkey != '' && $telsecretkey != "%20%20%20%20%20%20%20") {

        $keypasstelkey = substr(sha1((string) mt_rand()), 0, 32);
        $keysalttelkey = openssl_random_pseudo_bytes(12);
        $generated_keytelkey = openssl_pbkdf2($keypasstelkey, $keysalttelkey, 40, 100, 'sha256');
        $psswdaddedtelkey = bin2hex($generated_keytelkey);

        if (!is_dir('../restr')) {
            mkdir('../restr', 0700);
        }

        if (!is_dir('../restr/' . $username . '')) {
            mkdir('../restr/' . $username . '', 0700);
        }

        if (file_put_contents('../restr/' . $username . '/pwdtelnyxkey', $psswdaddedtelkey)) { $messageupdatatelkey1 = 'success'; } else { $messageupdatatelkey1 = 'failure'; }
        if (chmod('../restr/' . $username . '/pwdtelnyxkey', 0600)) { $messageupdatatelkey2 = 'success'; } else { $messageupdatatelkey2 = 'failure'; }
        if ($messageupdatatelkey1 == 'success' && $messageupdatatelkey2 == 'success') { $messageupdata11 = 'success'; } else { $messageupdata11 = 'failure'; }

        $iv8 = substr(sha1((string) mt_rand()), 0, 16);
        $enctelkey = openssl_encrypt($telsecretkey, 'AES-256-CBC', $psswdaddedtelkey, false, $iv8);
        $telsecretkeyEnc = $enctelkey.':'.$iv8;

    } elseif ($telsecretkey == "%20%20%20%20%20%20%20") {
              $queryseltelkeypass = $mysqli->prepare("SELECT userid, tel_secret_key FROM fax_settings WHERE userid = ?");
              $queryseltelkeypass->bind_param("i", $userid);
              $queryseltelkeypass->execute();
              $telkeypassarr = $queryseltelkeypass->get_result()->fetch_assoc();
              $telsecretkeyEnc = $telkeypassarr['tel_secret_key'];

    } elseif ($telsecretkey == '') {
              $telsecretkeyEnc = '';

    } else { $telsecretkeyEnc = ''; }


    if ($telfaxappid != '' && $telfaxappid != "%20%20%20%20%20%20%20") {

        $keypasstelappid = substr(sha1((string) mt_rand()), 0, 32);
        $keysalttelappid = openssl_random_pseudo_bytes(12);
        $generated_keytelappid = openssl_pbkdf2($keypasstelappid, $keysalttelappid, 40, 100, 'sha256');
        $psswdaddedtelappid = bin2hex($generated_keytelappid);

        if (!is_dir('../restr')) {
            mkdir('../restr', 0700);
        }

        if (!is_dir('../restr/' . $username . '')) {
            mkdir('../restr/' . $username . '', 0700);
        }

        if (file_put_contents('../restr/' . $username . '/pwdtelnyxappid', $psswdaddedtelappid)) { $messageupdatatelappid1 = 'success'; } else { $messageupdatatelappid1 = 'failure'; }
        if (chmod('../restr/' . $username . '/pwdtelnyxappid', 0600)) { $messageupdatatelappid2 = 'success'; } else { $messageupdatatelappid2 = 'failure'; }
        if ($messageupdatatelappid1 == 'success' && $messageupdatatelappid2 == 'success') { $messageupdata12 = 'success'; } else { $messageupdata12 = 'failure'; }

        $iv9 = substr(sha1((string) mt_rand()), 0, 16);
        $enctelappid = openssl_encrypt($telfaxappid, 'AES-256-CBC', $psswdaddedtelappid, false, $iv9);
        $telfaxappidEnc = $enctelappid.':'.$iv9;

    } elseif ($telfaxappid == "%20%20%20%20%20%20%20") {
              $queryseltelappidpass = $mysqli->prepare("SELECT userid, tel_fax_app_id FROM fax_settings WHERE userid = ?");
              $queryseltelappidpass->bind_param("i", $userid);
              $queryseltelappidpass->execute();
              $telappidpassarr = $queryseltelappidpass->get_result()->fetch_assoc();
              $telfaxappidEnc = $telappidpassarr['tel_fax_app_id'];

    } elseif ($telfaxappid == '') {
              $telfaxappidEnc = '';

    } else { $telfaxappidEnc = ''; }


    if ($phaxapikey != '' && $phaxapikey != "%20%20%20%20%20%20%20") {

        $keypassphkey = substr(sha1((string) mt_rand()), 0, 32);
        $keysaltphkey = openssl_random_pseudo_bytes(12);
        $generated_keyphkey = openssl_pbkdf2($keypassphkey, $keysaltphkey, 40, 100, 'sha256');
        $psswdaddedphkey = bin2hex($generated_keyphkey);

        if (!is_dir('../restr')) {
            mkdir('../restr', 0700);
        }

        if (!is_dir('../restr/' . $username . '')) {
            mkdir('../restr/' . $username . '', 0700);
        }

        if (file_put_contents('../restr/' . $username . '/pwdphaxiokey', $psswdaddedphkey)) { $messageupdataphkey1 = 'success'; } else { $messageupdataphkey1 = 'failure'; }
        if (chmod('../restr/' . $username . '/pwdphaxiokey', 0600)) { $messageupdataphkey2 = 'success'; } else { $messageupdataphkey2 = 'failure'; }
        if ($messageupdataphkey1 == 'success' && $messageupdataphkey2 == 'success') { $messageupdata6 = 'success'; } else { $messageupdata6 = 'failure'; }

        $iv2 = substr(sha1((string) mt_rand()), 0, 16);
        $encphkey = openssl_encrypt($phaxapikey, 'AES-256-CBC', $psswdaddedphkey, false, $iv2);
        $phaxapikeyEnc = $encphkey.':'.$iv2;

    } elseif ($phaxapikey == "%20%20%20%20%20%20%20") {
              $queryselphkeypass = $mysqli->prepare("SELECT userid, phax_api_key FROM fax_settings WHERE userid = ?");
              $queryselphkeypass->bind_param("i", $userid);
              $queryselphkeypass->execute();
              $phkeypassarr = $queryselphkeypass->get_result()->fetch_assoc();
              $phaxapikeyEnc = $phkeypassarr['phax_api_key'];

    } elseif ($phaxapikey == '') {
              $phaxapikeyEnc = '';

    } else { $phaxapikeyEnc = ''; }


    if ($phaxapisecret != '' && $phaxapisecret != "%20%20%20%20%20%20%20") {

        $keypassphsecret = substr(sha1(string) (mt_rand()), 0, 32);
        $keysaltphsecret = openssl_random_pseudo_bytes(12);
        $generated_keyphsecret = openssl_pbkdf2($keypassphsecret, $keysaltphsecret, 40, 100, 'sha256');
        $psswdaddedphsecret = bin2hex($generated_keyphsecret);

        if (!is_dir('../restr')) {
            mkdir('../restr', 0700);
        }

        if (!is_dir('../restr/' . $username . '')) {
            mkdir('../restr/' . $username . '', 0700);
        }

        if (file_put_contents('../restr/' . $username . '/pwdphaxiosecret', $psswdaddedphsecret)) { $messageupdataphsec1 = 'success'; } else { $messageupdataphsec1 = 'failure'; }
        if (chmod('../restr/' . $username . '/pwdphaxiosecret', 0600)) { $messageupdataphsec2 = 'success'; } else { $messageupdataphsec2 = 'failure'; }
        if ($messageupdataphsec1 == 'success' && $messageupdataphsec2 == 'success') { $messageupdata7 = 'success'; } else { $messageupdata7 = 'failure'; }

        $iv3 = substr(sha1((string) mt_rand()), 0, 16);
        $encphsecret = openssl_encrypt($phaxapisecret, 'AES-256-CBC', $psswdaddedphsecret, false, $iv3);
        $phaxapisecretEnc = $encphsecret.':'.$iv3;

    } elseif ($phaxapisecret == "%20%20%20%20%20%20%20") {
              $queryselphsecretpass = $mysqli->prepare("SELECT userid, phax_api_secret FROM fax_settings WHERE userid = ?");
              $queryselphsecretpass->bind_param("i", $userid);
              $queryselphsecretpass->execute();
              $phsecretpassarr = $queryselphsecretpass->get_result()->fetch_assoc();
              $phaxapisecretEnc = $phsecretpassarr['phax_api_secret'];

    } elseif ($phaxapisecret == '') {
              $phaxapisecretEnc = '';

    } else { $phaxapisecretEnc = ''; }


    if ($phaxwebhooktoken != '' && $phaxwebhooktoken != "%20%20%20%20%20%20%20") {

        $keypassphwhtoken = substr(sha1((string) mt_rand()), 0, 32);
        $keysaltphwhtoken = openssl_random_pseudo_bytes(12);
        $generated_keyphwhtoken = openssl_pbkdf2($keypassphwhtoken, $keysaltphwhtoken, 40, 100, 'sha256');
        $psswdaddedphwhtoken = bin2hex($generated_keyphwhtoken);

        if (!is_dir('../restr')) {
            mkdir('../restr', 0700);
        }

        if (!is_dir('../restr/' . $username . '')) {
            mkdir('../restr/' . $username . '', 0700);
        }

        if (file_put_contents('../restr/' . $username . '/pwdphaxiowhtoken', $psswdaddedphwhtoken)) { $messageupdataphwht1 = 'success'; } else { $messageupdataphwht1 = 'failure'; }
        if (chmod('../restr/' . $username . '/pwdphaxiowhtoken', 0600)) { $messageupdataphwht2 = 'success'; } else { $messageupdataphwht2 = 'failure'; }
        if ($messageupdataphwht1 == 'success' && $messageupdataphwht2 == 'success') { $messageupdata8 = 'success'; } else { $messageupdata8 = 'failure'; }

        $iv4 = substr(sha1((string) mt_rand()), 0, 16);
        $encphwhtoken = openssl_encrypt($phaxwebhooktoken, 'AES-256-CBC', $psswdaddedphwhtoken, false, $iv4);
        $phaxapiwhtokenEnc = $encphwhtoken.':'.$iv4;

    } elseif ($phaxwebhooktoken == "%20%20%20%20%20%20%20") {
              $queryselphwhtpass = $mysqli->prepare("SELECT userid, phax_webhook_token FROM fax_settings WHERE userid = ?");
              $queryselphwhtpass->bind_param("i", $userid);
              $queryselphwhtpass->execute();
              $phwhtpassarr = $queryselphwhtpass->get_result()->fetch_assoc();
              $phaxapiwhtokenEnc = $phwhtpassarr['phax_webhook_token'];

    } elseif ($phaxwebhooktoken == '') {
              $phaxapiwhtokenEnc = '';

    } else { $phaxapiwhtokenEnc = ''; }


    if ($rcBasicAuthPass != '' && $rcBasicAuthPass != "%20%20%20%20%20%20%20") {

        $keypassrcba = substr(sha1((string) mt_rand()), 0, 32);
        $keysaltrcba = openssl_random_pseudo_bytes(12);
        $generated_keyrcba = openssl_pbkdf2($keypassrcba, $keysaltrcba, 40, 100, 'sha256');
        $psswdaddedrcba = bin2hex($generated_keyrcba);

        if (!is_dir('../restr')) {
            mkdir('../restr', 0700);
        }

        if (!is_dir('../restr/' . $username . '')) {
            mkdir('../restr/' . $username . '', 0700);
        }

        if (file_put_contents('../restr/' . $username . '/pwdkeyrcba', $psswdaddedrcba)) { $messageupdatarcba1 = 'success'; } else { $messageupdatarcba1 = 'failure'; }
        if (chmod('../restr/' . $username . '/pwdkeyrcba', 0600)) { $messageupdatarcba2 = 'success'; } else { $messageupdatarcba2 = 'failure'; }
        if ($messageupdatarcba1 == 'success' && $messageupdatarcba2 == 'success') { $messageupdata9 = 'success'; } else { $messageupdata9 = 'failure'; }

        $iv6 = substr(sha1((string) mt_rand()), 0, 16);
        $encRcBasicAuthPass = openssl_encrypt($rcBasicAuthPass, 'AES-256-CBC', $psswdaddedrcba, false, $iv6);
        $rcBasicAuthPassEnc = $encRcBasicAuthPass.':'.$iv6;

    } elseif ($rcBasicAuthPass == "%20%20%20%20%20%20%20") {
              $queryselrcbapass = $mysqli->prepare("SELECT userid, rcbasicauthpass FROM email_conf WHERE userid = ?");
              $queryselrcbapass->bind_param("i", $userid);
              $queryselrcbapass->execute();
              $rcbapassarr = $queryselrcbapass->get_result()->fetch_assoc();
              $rcBasicAuthPassEnc = $rcbapassarr['rcbasicauthpass'];

    } elseif ($rcBasicAuthPass == '') {
              $rcBasicAuthPassEnc = '';

    } else { $rcBasicAuthPassEnc = ''; }


    if ($rcPassword != '' && $rcPassword != "%20%20%20%20%20%20%20") {

        $keypassrc = substr(sha1((string) mt_rand()), 0, 32);
        $keysaltrc = openssl_random_pseudo_bytes(12);
        $generated_keyrc = openssl_pbkdf2($keypassrc, $keysaltrc, 40, 100, 'sha256');
        $psswdaddedrc = bin2hex($generated_keyrc);

        if (!is_dir('../restr')) {
            mkdir('../restr', 0700);
        }

        if (!is_dir('../restr/' . $username . '')) {
            mkdir('../restr/' . $username . '', 0700);
        }

        if (file_put_contents('../restr/' . $username . '/pwdkeyrc', $psswdaddedrc)) { $messageupdatarcp1 = 'success'; } else { $messageupdatarcp1 = 'failure'; }
        if (chmod('../restr/' . $username . '/pwdkeyrc', 0600)) { $messageupdatarcp2 = 'success'; } else { $messageupdatarcp2 = 'failure'; }
        if ($messageupdatarcp1 == 'success' && $messageupdatarcp2 == 'success') { $messageupdata10 = 'success'; } else { $messageupdata10 = 'failure'; }

        $iv7 = substr(sha1((string) mt_rand()), 0, 16);
        $encRcPassword = openssl_encrypt($rcPassword, 'AES-256-CBC', $psswdaddedrc, false, $iv7);
        $rcPasswordEnc = $encRcPassword.':'.$iv7;

    } elseif ($rcPassword == "%20%20%20%20%20%20%20") {
              $queryselrcpass = $mysqli->prepare("SELECT userid, rcpassword FROM email_conf WHERE userid = ?");
              $queryselrcpass->bind_param("i", $userid);
              $queryselrcpass->execute(); 
              $queryselres = $queryselrcpass->get_result()->fetch_assoc();
              $rcPasswordEnc = $queryselres['rcpassword'];

    } elseif ($rcPassword == '') { 
              $rcPasswordEnc = '';

    } else { $rcPasswordEnc = ''; }


    // Insert account data for the current user in the 'app_users' table
    $crrntTime = date("Y-m-d H:i:s");

    $query1 = $mysqli->prepare("UPDATE `app_users` SET `wss_server`=?, `web_socket_port`=?, `server_path`=?, `profile_name`=?, `sip_username`=?, `sip_password`=?, `stun_server`=?,
                               `audio_output_id`=?, `video_src_id`=?, `video_height`=?, `frame_rate`=?, `aspect_ratio`=?, `video_orientation`=?, `ringtone`=?, `audio_src_id`=?, 
                               `auto_gain_control`=?, `echo_cancellation`=?, `noise_suppression`=?, `ring_output_id`=?, `video_conf_window_width`=?, `profile_picture`=?, 
                               `language`=?, `notifications`=?, `show_vconf_usernames`=?, `display_vconf_user`=?, `use_email`=?, `load_groups`=?, `date_modified`=? 
                                WHERE BINARY `username`=?");
    $query1->bind_param("sissssssssisssssssssssiiiisss", $wssServer, $webSocketPort, $serverPath, $profileName, $sipUsername, $sipPasswordEnc, $stunServer, $audioOutputId,
                         $videoSrcId, $videoHeight, $frameRate, $aspectRatio, $videoOrientation, $ringTone, $audioSrcId, $autoGainControl, $echoCancellation, $noiseSuppression,
                         $ringOutputId, $videoConfWindowWidth, $profilePicture, $language, $notifications, $showVconfNames, $displayVconfUser, $useEmail, $loadGroups, 
                         $crrntTime, $username);
    if ($query1->execute()) { $messageupdata1 = 'success'; } else { $messageupdata1 = 'failure'; }


    // Check if the fax settings for the current user are already in the `fax_settings` table
    $queryfaxck = $mysqli->prepare("SELECT id, userid FROM fax_settings WHERE userid = ?");
    $queryfaxck->bind_param("i", $userid);
    $queryfaxck->execute(); 
    $queryfaxckres = $queryfaxck->get_result()->fetch_assoc();

    if ($queryfaxckres) {

        // Update the fax settings for the current user in the `fax_settings` table
        $queryupfax = $mysqli->prepare("UPDATE `fax_settings` SET `tel_secret_key`=?, `tel_fax_app_id`=?, `tel_recwh_url`=?, `phax_api_key`=?, `phax_api_secret`=?, 
                                       `phax_webhook_token`=?, `phax_receive_url`=?, `get_notification`=?, `notification_email`=? WHERE `userid`=?");
        $queryupfax->bind_param("sssssssisi", $telsecretkeyEnc, $telfaxappidEnc, $telrecwhurl, $phaxapikeyEnc, $phaxapisecretEnc, $phaxapiwhtokenEnc, $phaxreceiveurl, 
                                 $faxnotification, $faxnotifyemail, $userid);
        if ($queryupfax->execute()) { $messageupdata2 = 'success'; } else { $messageupdata2 = 'failure'; }

    } else {

        // Insert the fax settings for the current user in the `fax_settings` table
        $queryinsfax = $mysqli->prepare("INSERT INTO `fax_settings` (userid, tel_secret_key, tel_fax_app_id, tel_recwh_url, phax_api_key, phax_api_secret, phax_webhook_token, 
                                         phax_receive_url, get_notification, notification_email) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $queryinsfax->bind_param("isssssssis", $userid, $telsecretkeyEnc, $telfaxappidEnc, $telrecwhurl, $phaxapikeyEnc, $phaxapisecretEnc, $phaxapiwhtokenEnc, $phaxreceiveurl, 
                                  $faxnotification, $faxnotifyemail);
        if ($queryinsfax->execute()) { $messageupdata2 = 'success'; } else { $messageupdata2 = 'failure'; }
    }


    // Check if the voice/sms/fax numbers for the current user are already in the `phone_numbers` table
    $queryphck = $mysqli->prepare("SELECT id, userid FROM phone_numbers WHERE userid = ?");
    $queryphck->bind_param("i", $userid);
    $queryphck->execute(); 
    $queryphckres = $queryphck->get_result()->fetch_assoc();

    if ($queryphckres) {

        // Update voice/sms/fax numbers for the current user in the `phone_numbers` table
        $queryuphnb = $mysqli->prepare("UPDATE `phone_numbers` SET `voice_numbers`=?, `default_voice_number`=?, `sms_numbers`=?, `default_sms_number`=?, `fax_numbers`=?, 
                                       `default_fax_number`=? WHERE `userid`=?");
        $queryuphnb->bind_param("ssssssi", $voicenmb, $voicedefnmb, $smsnmb, $smsdefnmb, $faxnmb, $faxdefnmb, $userid);
        if ($queryuphnb->execute()) { $messageupdata3 = 'success'; } else { $messageupdata3 = 'failure'; }

    } else {

        // Insert voice/sms/fax numbers for the current user in the `phone_numbers` table
        $queryinsnb = $mysqli->prepare("INSERT INTO `phone_numbers` (userid, voice_numbers, default_voice_number, sms_numbers, default_sms_number, fax_numbers, default_fax_number) 
                                        VALUES (?, ?, ?, ?, ?, ?, ?)");
        $queryinsnb->bind_param("issssss", $userid, $voicenmb, $voicedefnmb, $smsnmb, $smsdefnmb, $faxnmb, $faxdefnmb);
        if ($queryinsnb->execute()) { $messageupdata3 = 'success'; } else { $messageupdata3 = 'failure'; }
    }


    // Check if the email configuration data is already in the `email_conf` table
    $query2 = $mysqli->prepare("SELECT id, userid FROM email_conf WHERE userid = ?");
    $query2->bind_param("s", $userid);
    $query2->execute(); 
    $querychck = $query2->get_result()->fetch_assoc();

    if ($querychck) {

        // Update email configuration data in the 'email_conf' table
        $query3 = $mysqli->prepare("UPDATE `email_conf` SET `rcdomain`=?, `rcuser`=?, `rcpassword`=?, `rcbasicauthuser`=?, `rcbasicauthpass`=? WHERE `userid`=?");
        $query3->bind_param("sssssi", $rcDomain, $rcUser, $rcPasswordEnc, $rcBasicAuthUser, $rcBasicAuthPassEnc, $userid);
        if ($query3->execute()) { $messageupdata4 = 'success'; } else { $messageupdata4 = 'failure'; }

    } else {

        // Insert email configuration data in the 'email_conf' table
        $query4 = $mysqli->prepare("INSERT INTO `email_conf` (userid, rcdomain, rcuser, rcpassword, rcbasicauthuser, rcbasicauthpass) VALUES (?, ?, ?, ?, ?, ?)");
        $query4->bind_param("isssss", $userid, $rcDomain, $rcUser, $rcPasswordEnc, $rcBasicAuthUser, $rcBasicAuthPassEnc);
        if ($query4->execute()) { $messageupdata4 = 'success'; } else { $messageupdata4 = 'failure'; }
    }


    // Update profile picture in the 'contacts' table
    if ($profilePicture != '') {

              $queryselextno = $mysqli->prepare("SELECT id, extension_number FROM contacts WHERE extension_number = ?");
              $queryselextno->bind_param("s", $sipUsername);
              $queryselextno->execute(); 
              $totextensions = $queryselextno->get_result();
              $errchck = 0;
              while ($foundextensions = $totextensions->fetch_assoc()) {
                     $querypics = $mysqli->prepare("UPDATE `contacts` SET `profile_picture_c`=? WHERE `extension_number`=?");
                     $querypics->bind_param("ss", $profilePicture, $sipUsername);
                     if (!$querypics->execute()) { ++$errchck; }
              }
              if ($errchck == 0) { $messageuppicture = 'success'; } else { $messageuppicture = 'failure'; }

    } else { $messageuppicture = 'success'; }


    if ($messageupdata1 == 'success' && $messageupdata2 == 'success' && $messageupdata3 == 'success' && $messageupdata4 == 'success' &&
        $messageupdata5 == 'success' && $messageupdata6 == 'success' && $messageupdata7 == 'success' && $messageupdata8 == 'success' &&
        $messageupdata9 == 'success' && $messageupdata10 == 'success' && $messageupdata11 == 'success' && $messageupdata12 == 'success') {
        $messageupdata = 'success';
    } else { 
        $messageupdata = 'failure';
    }

    $response = array('resultupdata' => $messageupdata, 'resultuppicture' => $messageuppicture, 'indivresults' => [$messageupdata1, $messageupdata2, $messageupdata3,
                       $messageupdata4, $messageupdata5, $messageupdata6, $messageupdata7, $messageupdata8, $messageupdata9, $messageupdata10, $messageupdata11, $messageupdata12]);
    echo json_encode($response);

} else {
    header("Location: ../login.php");
}

?>
