<?php
    /*
    Plugin Name: Expenses Book
    Plugin URI:
    Description: A WordPress plugin to record your expenses including recurring expenses. After plugin activation, go to the "Settings" menu to find the plugin admin page. By default, when you activate this plugin, it will automatically create an expenses landing page for you. For some themes, if it does not automatically create an expenses landing page for you, add this plugin root folder template-expenses.php file to your template folder. For example, if you are using theme twentytwenty, then add the template-expenses.php file to this folder: wordpress\wp-content\themes\twentytwenty\templates. Then you can create a new page (not a new post) using this template. When you use the template method to create a new expense page, do not set the page title to "expenses".  If you set the page title to "expenses", it could conflict with the page automatically created when you activate this plugin. Please read documents in the admin plugin setting page before using this software.
    Author: Ming's IT Services Ltd.
    Year: 2020-05-07
    Version: 1.1.3
    License: GPLv2 or later
    All rights reserved.
    Author URI: https://www.mingsitservices.ca/
    Disclaimer: While Ming's IT Services Ltd. makes every effort to deliver high quality products, we do not 
                guarantee that our products are free from defects. Our software is provided “as is," and you use the 
                software at your own risk.
                We make no warranties as to performance, merchantability, fitness for a particular purpose, or any 
                other warranties whether expressed or implied.
                No oral or written communication from or information provided by Ming's IT Services Ltd. 
                shall create a warranty.
                Under no circumstances shall Ming's IT Services Ltd. be liable for direct, indirect, special, 
                incidental, or consequential damages resulting from the use, misuse, or inability to use this software, 
                even if Ming's IT Services Ltd. has been advised of the possibility of such damages.
    */
if(!defined('ABSPATH')) exit; // Exit if accessed directly
global $wpdb; global $dragon_expense_dbResult;
$dragon_expense_dbResult = '';
//$timezone=get_option('timezone_string');
//if(!empty($timezone)){date_default_timezone_set($timezone);}
$wp_expenseszyx987_table_name = 'wp_expenseszyx987';
$charset_collate = $wpdb->get_charset_collate();

function expenseszyx987_getOneUser($userid = 0) {
    global $wpdb; global $dragon_visit_dbResult; $results;global $wp_expenseszyx987_table_name;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = $wp_expenseszyx987_table_name . "_users";
    $results = array();
    if(intval($userid) > 0) {
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                echo "Connection failed: " . esc_html($wpdb->dbh->connect_error);
                exit;
            }
            $stmt = $wpdb->dbh->prepare("SELECT * FROM $table_name WHERE status = 1 and userid = ?");
            $stmt->bind_param("i", intval($userid));
            $stmt->execute();
            $myresult = $stmt->get_result();
            $results = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            foreach($results as $result) {
                foreach($result as $key => $value) {
                    $result[$key] = deslash($value);
                }
            }

        } else {
            echo 'Mysqli is not supported by your system. ';
            exit;
        }
    }
    return $results;
}

function expenseszyx987_wp_expenseszyx987_users_already_has_admin_user() {
    global $wpdb;global $wp_expenseszyx987_table_name;
    $table_name = $wp_expenseszyx987_table_name . "_users";
    $results = $wpdb->get_results("SELECT userid FROM $table_name WHERE status = 1");
    if(count($results) > 0){
        $has_admin_user = false;
        foreach($results as $result) {
            if(intval($result->userid) > 0 ){
                if(expenseszyx987_user_has_role(intval($result->userid), 'administrator')) {
                    $has_admin_user = true;
                    break;
                }
            }
        }
        return $has_admin_user;
    } else {
        return false;
    }
}

function expenseszyx987_createFirstAdminUser()
{
    global $wpdb;global $wp_expenseszyx987_table_name;
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        echo "Invalid User.";exit;
    }
    $userdetails = expenseszyx987_getOneUser(intval($current_user->data->ID));
    if(count($userdetails) !== 1) {
        if(intval($current_user->data->ID) > 0 && in_array( 'administrator', (array) $current_user->roles )) {
            //if wp_expenseszyx987_users table does not have an admin user yet, add this user to wp_expenseszyx987_users table automatically
            if(!expenseszyx987_wp_expenseszyx987_users_already_has_admin_user()) {
                require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
                $table_name = $wp_expenseszyx987_table_name . "_users";
                $firstname = 'admin';
                $lastname = 'admin';
                $userid = intval($current_user->data->ID);
                $canreadinadminpage = 1;
                $cancreateinadminpage = 1;
                $caneditinadminpage = 1;
                $canactivateinadminpage = 1;
                $candeactivateinadminpage = 1;
                $reportto = intval($current_user->data->ID);

                $role_table_name = $wp_expenseszyx987_table_name . "_role";
                $admin_role_id = $wpdb->get_var("SELECT id FROM " . $role_table_name . " WHERE name = 'admin' LIMIT 1");
                $role = intval($admin_role_id);
                if($role <= 0) {$role = null;}

                $department = null;
                $status = 1;
                $email = null;
                $phone = null;
                $address = null;
                $address2 = null;
                $city = null;
                $province = null;
                $country = null;
                $zip = null;
                $description = null;

                if($userid <= 0 || $reportto <= 0) {
                    echo 'Create a new user: User id, and report to id are required.';
                    exit;
                }

                if($wpdb->use_mysqli) {
                    if($wpdb->dbh->connect_error) {
                        echo "Connection failed: " . esc_html($wpdb->dbh->connect_error);
                        exit;
                    }
                    $stmt = $wpdb->dbh->prepare("SELECT COUNT(*) countresult FROM $table_name WHERE userid = ?");
                    $stmt->bind_param("i", $userid);
                    $stmt->execute();
                    $myresult = $stmt->get_result();
                    $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
                    $stmt->close();

                    if(count($result) === 1) {
                        $temp_row = $result[0];
                        $temp_result = $temp_row["countresult"];
                        $dbcount = $temp_result === null ? 0 : intval($temp_result);
                        if($dbcount !== 0) {
                            echo "Create a new user: your user id " . intval($userid) . " already exists in the table.";
                            exit;
                        }
                    } else {
                        echo "Create a new user: user id " . intval($userid) . " query has error. Not saved.";
                        exit;
                    }

                    $query = "INSERT INTO $table_name (`userid`,`firstname`,`lastname`,`phone`,`address`,`address2`,`city`,`province`,`country`,`zip`,`reportto`,`email`,`description`,`departmentid`,`roleid`,`canreadinadminpage`,`cancreateinadminpage`,`caneditinadminpage`,`canactivateinadminpage`,`candeactivateinadminpage`,`status`,`createtimeutc`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,1,UTC_TIMESTAMP())";
                    $stmt = $wpdb->dbh->prepare($query);
                    $types = '';
                    $parameterArray = array('');

                    $types .= 'i';
                    $parameterArray[] = &$userid;

                    $types .= 's';
                    $parameterArray[] = &$firstname;

                    $types .= 's';
                    $parameterArray[] = &$lastname;

                    $types .= 's';
                    $parameterArray[] = &$phone;

                    $types .= 's';
                    $parameterArray[] = &$address;

                    $types .= 's';
                    $parameterArray[] = &$address2;

                    $types .= 's';
                    $parameterArray[] = &$city;

                    $types .= 's';
                    $parameterArray[] = &$province;

                    $types .= 's';
                    $parameterArray[] = &$country;

                    $types .= 's';
                    $parameterArray[] = &$zip;

                    $types .= 'i';
                    $parameterArray[] = &$reportto;

                    $types .= 's';
                    $parameterArray[] = &$email;

                    $types .= 's';
                    $parameterArray[] = &$description;

                    $types .= 'i';
                    $parameterArray[] = &$departmentid;

                    $types .= 'i';
                    $parameterArray[] = &$role;

                    $types .= 'i';
                    $parameterArray[] = &$canreadinadminpage;

                    $types .= 'i';
                    $parameterArray[] = &$cancreateinadminpage;

                    $types .= 'i';
                    $parameterArray[] = &$caneditinadminpage;

                    $types .= 'i';
                    $parameterArray[] = &$canactivateinadminpage;

                    $types .= 'i';
                    $parameterArray[] = &$candeactivateinadminpage;

                    $parameterArray[0] = $types;
                    call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                    $stmt->execute();
                    $myresult = $stmt->insert_id;
                    $stmt->close();

                    if($myresult <= 0) {
                        echo 'Error adding a user into table ' . $table_name . ". ";
                        exit;
                    }
                    $userdetails = expenseszyx987_getOneUser(intval($current_user->data->ID));
                } else {
                    echo 'Mysqli is not supported by your system. ';
                    exit;
                }
            }
        } else {
            echo "Invalid User. Please contact web admin to add you to this plugin's user list: wp_expenseszyx987_users table. You need to enter your first name, last name, and createtimeutc (e.g. ‘2022-01-01’). You also need to set canreadinadminpage, cancreateinadminpage, caneditinadminpage, canactivateinadminpage, candeactivateinadminpage to 1. You can also set reportto to your supervisor’s ID in the wp_users table. Then add this record to wp_expenseszyx987_users table. See the root folder, documentation_dragonvisit.pdf file for details.";
            exit;
        }
    }
}

function expenseszyx987_additional_creation() {
}

function expenseszyx987_createStoredProcedure() {
    require_once __DIR__ . '/expenseszyx987_storedprocedures.php';
}

function expenseszyx987_createTable_constant() {
    global $wp_expenseszyx987_table_name;global $charset_collate;global $wpdb;
    $sql = "CREATE TABLE IF NOT EXISTS " . $wp_expenseszyx987_table_name . "_constant (
          `id` BIGINT unsigned NOT NULL AUTO_INCREMENT,
          `name` varchar(255) NOT NULL,
          `value` text NOT NULL,
          `status` tinyint(1) NOT NULL DEFAULT 1,
          `createtimeutc` DATETIME NOT NULL,
          `updatetimeutc` DATETIME,
          PRIMARY KEY (`id`)
    ) $charset_collate;";
    dbDelta($sql);

    $constant_name = 'AMOUNT_PER_PAGE';
    $constant_description = '10';
    $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $wp_expenseszyx987_table_name . "_constant (`name`,`value`,`status`,`createtimeutc`) SELECT * FROM (SELECT '" . $constant_name . "' as name,'" . $constant_description . "' as value,1 as status,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_constant WHERE `name`= '" . $constant_name . "') LIMIT 1;"));
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_constant (`name`,`value`,`status`,`createtimeutc`) SELECT * FROM (SELECT 'DBBACKUP_FREQUENCY' as name,'' as value,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_constant WHERE `name`= 'DBBACKUP_FREQUENCY') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_constant (`name`,`value`,`status`,`createtimeutc`) SELECT * FROM (SELECT 'DBBACKUP_LOCALTIME' as name,'' as value,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_constant WHERE `name`= 'DBBACKUP_LOCALTIME') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_constant (`name`,`value`,`status`,`createtimeutc`) SELECT * FROM (SELECT 'DBBACKUP_DETAILS' as name,'' as value,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_constant WHERE `name`= 'DBBACKUP_DETAILS') LIMIT 1;";
    dbDelta($sql);
    //$sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_constant (`name`,`value`,`status`,`createtimeutc`) SELECT * FROM (SELECT 'COMPANY_TIMEZONE' as name, 'America/New_York' as value,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_constant WHERE `name`= 'COMPANY_TIMEZONE') LIMIT 1;";
    //dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_constant (`name`,`value`,`status`,`createtimeutc`) SELECT * FROM (SELECT 'LANGUAGE' as name, 'en' as value,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_constant WHERE `name`= 'LANGUAGE') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_constant (`name`,`value`,`status`,`createtimeutc`) SELECT * FROM (SELECT 'COMPANY_NAME' as name,'' as value,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_constant WHERE `name`= 'COMPANY_NAME') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_constant (`name`,`value`,`status`,`createtimeutc`) SELECT * FROM (SELECT 'COMPANY_ADDRESS' as name,'' as value,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_constant WHERE `name`= 'COMPANY_ADDRESS') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_constant (`name`,`value`,`status`,`createtimeutc`) SELECT * FROM (SELECT 'USE_BOOTSTRAP_JS' as name,'1' as value,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_constant WHERE `name`= 'USE_BOOTSTRAP_JS') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_constant (`name`,`value`,`status`,`createtimeutc`) SELECT * FROM (SELECT 'USE_BOOTSTRAP_CSS' as name,'1' as value,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_constant WHERE `name`= 'USE_BOOTSTRAP_CSS') LIMIT 1;";
    dbDelta($sql);
}

function expenseszyx987_createTable_department() {
    global $wp_expenseszyx987_table_name;global $charset_collate;global $wpdb;
    $sql = "CREATE TABLE IF NOT EXISTS " . $wp_expenseszyx987_table_name . "_department (
          `id` BIGINT unsigned NOT NULL AUTO_INCREMENT,
          `name` varchar(255) NOT NULL,
          `description` varchar(255) NOT NULL,
          `status` tinyint(1) NOT NULL DEFAULT 1,
          `createtimeutc` DATETIME NOT NULL,
          `updatetimeutc` DATETIME,
          PRIMARY KEY (`id`)
    ) $charset_collate;";
    dbDelta($sql);
    $department_name = 'admin';
    $department_description = 'admin';
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $wp_expenseszyx987_table_name . "_department WHERE name = '" . $department_name . "'");
    if(intval($dbmyid) > 0) {
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $wp_expenseszyx987_table_name . "_department (`id`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 1 as 'id', %s as 'name', %s as 'description', 1 as 'status', UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_department WHERE `name`= '" . $department_name . "') LIMIT 1", array($department_name, $department_description)));
    }
}

function expenseszyx987_createTable_log() {
    global $wp_expenseszyx987_table_name;global $charset_collate;
    $sql = "CREATE TABLE IF NOT EXISTS " . $wp_expenseszyx987_table_name . "_log (
        id INTEGER NOT NULL AUTO_INCREMENT,
        processname TEXT CHARSET utf8,
        type TEXT CHARSET utf8,
        userid INTEGER,
        description TEXT CHARSET utf8,
        createtimeutc DATETIME NOT NULL,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
}

function expenseszyx987_createTable_role() {
    global $wp_expenseszyx987_table_name;global $charset_collate;global $wpdb;
    $sql = "CREATE TABLE IF NOT EXISTS " . $wp_expenseszyx987_table_name . "_role (
          `id` BIGINT unsigned NOT NULL AUTO_INCREMENT,
          `name` varchar(255) NOT NULL,
          `description` varchar(255) NOT NULL,
          `status` tinyint(1) NOT NULL DEFAULT 1,
          `createtimeutc` DATETIME NOT NULL,
          `updatetimeutc` DATETIME,
          PRIMARY KEY (`id`)
    ) $charset_collate;";
    dbDelta($sql);
    $role_name = 'admin';
    $role_description = 'admin';
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $wp_expenseszyx987_table_name . "_role WHERE name = '" . $role_name . "'");
    if(intval($dbmyid) > 0) {
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $wp_expenseszyx987_table_name . "_role (`id`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 1 as 'id', %s as 'name', %s as 'description', 1 as 'status', UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_role WHERE `name`= '" . $role_name . "') LIMIT 1", array($role_name, $role_description)));
    }

    $role_name = 'superuser';
    $role_description = 'superuser';
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $wp_expenseszyx987_table_name . "_role WHERE name = '" . $role_name . "'");
    if(intval($dbmyid) > 0) {
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $wp_expenseszyx987_table_name . "_role (`id`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 2 as 'id', %s as 'name', %s as 'description', 1 as 'status', UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_role WHERE `name`= '" . $role_name . "') LIMIT 1", array($role_name, $role_description)));
    }

    $role_name = 'manager';
    $role_description = 'manager';
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $wp_expenseszyx987_table_name . "_role WHERE name = '" . $role_name . "'");
    if(intval($dbmyid) > 0) {
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $wp_expenseszyx987_table_name . "_role (`id`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 3 as 'id', %s as 'name', %s as 'description', 1 as 'status', UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_role WHERE `name`= '" . $role_name . "') LIMIT 1", array($role_name, $role_description)));
    }

    $role_name = 'user';
    $role_description = 'user';
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $wp_expenseszyx987_table_name . "_role WHERE name = '" . $role_name . "'");
    if(intval($dbmyid) > 0) {
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $wp_expenseszyx987_table_name . "_role (`id`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 4 as 'id', %s as 'name', %s as 'description', 1 as 'status', UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_role WHERE `name`= '" . $role_name . "') LIMIT 1", array($role_name, $role_description)));
    }
}

function expenseszyx987_createTable_recurringpaymentfrequency() {
    global $wp_expenseszyx987_table_name;global $charset_collate;global $wpdb;
    $sql = "CREATE TABLE IF NOT EXISTS " . $wp_expenseszyx987_table_name . "_recurringpaymentfrequency (
          `id` BIGINT unsigned NOT NULL AUTO_INCREMENT,
          `name` varchar(45) not null,
          `description` varchar(250),
          `status` tinyint(1) NOT NULL DEFAULT 1,
          `createtimeutc` DATETIME NOT NULL,
          `updatetimeutc` DATETIME,
          PRIMARY KEY (`id`)
    ) $charset_collate;";
    dbDelta( $sql );

    $recurringpaymentfrequency_name = 'Daily';
    $recurringpaymentfrequency_description = 'Daily';
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $wp_expenseszyx987_table_name . "_recurringpaymentfrequency WHERE name = '" . $recurringpaymentfrequency_name . "'");
    if(intval($dbmyid) > 0) {
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $wp_expenseszyx987_table_name . "_recurringpaymentfrequency (`id`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 1 as 'id', %s as 'name', %s as 'description', 1 as 'status', UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_recurringpaymentfrequency WHERE `name`= '" . $recurringpaymentfrequency_name . "') LIMIT 1", array($recurringpaymentfrequency_name, $recurringpaymentfrequency_description)));
    }

    $recurringpaymentfrequency_name = 'Weekly';
    $recurringpaymentfrequency_description = 'Weekly';
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $wp_expenseszyx987_table_name . "_recurringpaymentfrequency WHERE name = '" . $recurringpaymentfrequency_name . "'");
    if(intval($dbmyid) > 0) {
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $wp_expenseszyx987_table_name . "_recurringpaymentfrequency (`id`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 2 as 'id', %s as 'name', %s as 'description', 1 as 'status', UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_recurringpaymentfrequency WHERE `name`= '" . $recurringpaymentfrequency_name . "') LIMIT 1", array($recurringpaymentfrequency_name, $recurringpaymentfrequency_description)));
    }

    $recurringpaymentfrequency_name = 'Biweekly';
    $recurringpaymentfrequency_description = 'Biweekly';
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $wp_expenseszyx987_table_name . "_recurringpaymentfrequency WHERE name = '" . $recurringpaymentfrequency_name . "'");
    if(intval($dbmyid) > 0) {
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $wp_expenseszyx987_table_name . "_recurringpaymentfrequency (`id`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 3 as 'id', %s as 'name', %s as 'description', 1 as 'status', UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_recurringpaymentfrequency WHERE `name`= '" . $recurringpaymentfrequency_name . "') LIMIT 1", array($recurringpaymentfrequency_name, $recurringpaymentfrequency_description)));
    }

    $recurringpaymentfrequency_name = 'Monthly';
    $recurringpaymentfrequency_description = 'Monthly';
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $wp_expenseszyx987_table_name . "_recurringpaymentfrequency WHERE name = '" . $recurringpaymentfrequency_name . "'");
    if(intval($dbmyid) > 0) {
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $wp_expenseszyx987_table_name . "_recurringpaymentfrequency (`id`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 4 as 'id', %s as 'name', %s as 'description', 1 as 'status', UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_recurringpaymentfrequency WHERE `name`= '" . $recurringpaymentfrequency_name . "') LIMIT 1", array($recurringpaymentfrequency_name, $recurringpaymentfrequency_description)));
    }

    $recurringpaymentfrequency_name = 'Quarterly';
    $recurringpaymentfrequency_description = 'Quarterly';
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $wp_expenseszyx987_table_name . "_recurringpaymentfrequency WHERE name = '" . $recurringpaymentfrequency_name . "'");
    if(intval($dbmyid) > 0) {
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $wp_expenseszyx987_table_name . "_recurringpaymentfrequency (`id`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 5 as 'id', %s as 'name', %s as 'description', 1 as 'status', UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_recurringpaymentfrequency WHERE `name`= '" . $recurringpaymentfrequency_name . "') LIMIT 1", array($recurringpaymentfrequency_name, $recurringpaymentfrequency_description)));
    }

    $recurringpaymentfrequency_name = 'Yearly';
    $recurringpaymentfrequency_description = 'Yearly';
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $wp_expenseszyx987_table_name . "_recurringpaymentfrequency WHERE name = '" . $recurringpaymentfrequency_name . "'");
    if(intval($dbmyid) > 0) {
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $wp_expenseszyx987_table_name . "_recurringpaymentfrequency (`id`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 6 as 'id', %s as 'name', %s as 'description', 1 as 'status', UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_recurringpaymentfrequency WHERE `name`= '" . $recurringpaymentfrequency_name . "') LIMIT 1", array($recurringpaymentfrequency_name, $recurringpaymentfrequency_description)));
    }
}

function expenseszyx987_createTable_currency() {
    global $wp_expenseszyx987_table_name;global $charset_collate;global $wpdb;
    $sql = "CREATE TABLE IF NOT EXISTS " . $wp_expenseszyx987_table_name . "_currency (
        id BIGINT unsigned NOT NULL AUTO_INCREMENT,
        name TEXT CHARSET utf8 NOT NULL,        
        sign TEXT CHARSET utf8 NOT NULL,
        isocurrencycode TEXT CHARSET utf8 NOT NULL,
        description TEXT CHARSET utf8,
        priority INT,
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
    $currency_name = 'USD';
    $currency_sign = 'USD$';
    //https://www2.1010data.com/documentationcenter/beta/1010dataReferenceManual/DataTypesAndFormats/currencyUnitCodes.html
    $iso_currency_code = 'USD';
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $wp_expenseszyx987_table_name . "_currency WHERE name = '" . $currency_name . "'");
    if(intval($dbmyid) > 0) {
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`priority`,`createtimeutc`) SELECT * FROM (SELECT %s as 'name', %s as 'sign', %s as 'isocurrencycode', 999, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= '" . $currency_name . "') LIMIT 1", array($currency_name, $currency_sign, $iso_currency_code)));
    }
    $currency_name = 'CAD';
    $currency_sign = 'CAD$';
    $iso_currency_code = 'CAD';
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $wp_expenseszyx987_table_name . "_currency WHERE name = '" . $currency_name . "'");
    if(intval($dbmyid) > 0) {
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`priority`,`createtimeutc`) SELECT * FROM (SELECT %s as 'name', %s as 'sign', %s as 'isocurrencycode', 998, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= '" . $currency_name . "') LIMIT 1", array($currency_name, $currency_sign, $iso_currency_code)));
    }
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`priority`,`createtimeutc`) SELECT * FROM (SELECT 'EUR' as 'name', '€' as 'sign', 'EUR' as 'isocurrencycode', 'Euro' as 'description', 997 as `priority`,UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'EUR') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`priority`,`createtimeutc`) SELECT * FROM (SELECT 'GBP' as 'name', '£' as 'sign', 'GBP' as 'isocurrencycode', 'Pound Sterling' as 'description', 996 as `priority`,UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'GBP') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`priority`,`createtimeutc`) SELECT * FROM (SELECT 'INR' as 'name', 'INR₹' as 'sign', 'INR' as 'isocurrencycode', 'Indian Rupee' as 'description', 995 as `priority`,UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'INR') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`priority`,`createtimeutc`) SELECT * FROM (SELECT 'RUB' as 'name', '₽' as 'sign', 'RUB' as 'isocurrencycode', 'Russian Ruble' as 'description', 994 as `priority`,UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'RUB') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'AFN' as 'name', 'AFN؋' as 'sign', 'AFN' as 'isocurrencycode', 'Afghani' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'AFN') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'ALL' as 'name', 'Albanian lek L' as 'sign', 'ALL' as 'isocurrencycode', 'Lek' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'ALL') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'DZD' as 'name', 'DZDدج' as 'sign', 'DZD' as 'isocurrencycode', 'Algerian Dinar' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'DZD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'AOA' as 'name', 'Kz' as 'sign', 'AOA' as 'isocurrencycode', 'Kwanza' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'AOA') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'XCD' as 'name', 'XCD$' as 'sign', 'XCD' as 'isocurrencycode', 'East Caribbean Dollar' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'XCD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'ARS' as 'name', 'ARS$' as 'sign', 'ARS' as 'isocurrencycode', 'Argentine Peso' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'ARS') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'AMD' as 'name', 'AMD֏' as 'sign', 'AMD' as 'isocurrencycode', 'Armenian Dram' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'AMD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'AWG' as 'name', 'Afl.' as 'sign', 'AWG' as 'isocurrencycode', 'Aruban Florin' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'AWG') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'AUD' as 'name', 'AUD$' as 'sign', 'AUD' as 'isocurrencycode', 'Australian Dollar' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'AUD') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'AZN' as 'name', 'AZN₼' as 'sign', 'AZN' as 'isocurrencycode', 'Azerbaijanian Manat' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'AZN') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'BSD' as 'name', 'B$' as 'sign', 'BSD' as 'isocurrencycode', 'Bahamian Dollar' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'BSD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'BHD' as 'name', 'BD' as 'sign', 'BHD' as 'isocurrencycode', 'Bahraini Dinar' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'BHD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'BDT' as 'name', 'BDT৳'  as 'sign', 'BDT' as 'isocurrencycode', 'Taka' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'BDT') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'BBD' as 'name', 'Bds $' as 'sign', 'BBD' as 'isocurrencycode', 'Barbados Dollar' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'BBD') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'BYR' as 'name', 'BYN' as 'sign', 'BYR' as 'isocurrencycode', 'Belarussian Ruble' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'BYR') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'BZD' as 'name', 'BZ$' as 'sign', 'BZD' as 'isocurrencycode', 'Belize Dollar' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'BZD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'XOF' as 'name', 'CFA' as 'sign', 'XOF' as 'isocurrencycode', 'CFA Franc BCEAO' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'XOF') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'BMD' as 'name', 'BMD$' as 'sign', 'BMD' as 'isocurrencycode', 'Bermudian Dollar' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'BMD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'BTN' as 'name', 'Nu.' as 'sign', 'BTN' as 'isocurrencycode', 'Ngultrum' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'BTN') LIMIT 1;";
    dbDelta($sql);


    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'BOB' as 'name', 'Bs' as 'sign', 'BOB' as 'isocurrencycode', 'Boliviano' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'BOB') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'BOV' as 'name', 'BOV' as 'sign', 'BOV' as 'isocurrencycode', 'Mvdol' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'BOV') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'BAM' as 'name', 'KM' as 'sign', 'BAM' as 'isocurrencycode', 'Convertible Mark' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'BAM') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'BWP' as 'name', 'P' as 'sign', 'BWP' as 'isocurrencycode', 'Pula' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'BWP') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'NOK' as 'name', 'NOK kr' as 'sign', 'NOK' as 'isocurrencycode', 'Norwegian Krone' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'NOK') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'BRL' as 'name', 'R$' as 'sign', 'BRL' as 'isocurrencycode', 'Brazilian Real' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'BRL') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'BND' as 'name', 'B$' as 'sign', 'BND' as 'isocurrencycode', 'Brunei Dollar' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'BND') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'BGN' as 'name', 'Лв.' as 'sign', 'BGN' as 'isocurrencycode', 'Bulgarian Lev' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'BGN') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'BIF' as 'name', 'FBu' as 'sign', 'BIF' as 'isocurrencycode', 'Burundi Franc' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'BIF') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'KHR' as 'name', 'KHR៛' as 'sign', 'KHR' as 'isocurrencycode', 'Riel' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'KHR') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'XAF' as 'name', 'FCFA' as 'sign', 'XAF' as 'isocurrencycode', 'CFA Franc BEAC' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'XAF') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'CVE' as 'name', 'CVE$' as 'sign', 'CVE' as 'isocurrencycode', 'Cabo Verde Escudo' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'CVE') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'KYD' as 'name', 'CI$' as 'sign', 'KYD' as 'isocurrencycode', 'Cayman Islands Dollar' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'KYD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'CLF' as 'name', 'UF' as 'sign', 'CLF' as 'isocurrencycode', 'Unidad de Fomento' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'CLF') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'CLP' as 'name', 'CLP$' as 'sign', 'CLP' as 'isocurrencycode', 'Chilean Peso' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'CLP') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'CNY' as 'name', 'CN¥' as 'sign', 'CNY' as 'isocurrencycode', 'Yuan Renminbi' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'CNY') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'COP' as 'name', 'COP$' as 'sign', 'COP' as 'isocurrencycode', 'Colombian Peso' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'COP') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'COU' as 'name', 'COU' as 'sign', 'COU' as 'isocurrencycode', 'Unidad de Valor Real' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'COU') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'KMF' as 'name', 'Comoro Franc' as 'sign', 'KMF' as 'isocurrencycode', 'Comoro Franc' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'KMF') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'CDF' as 'name', 'FC' as 'sign', 'CDF' as 'isocurrencycode', 'Congolese Franc' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'CDF') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'NZD' as 'name', 'NZD$' as 'sign', 'NZD' as 'isocurrencycode', 'New Zealand Dollar' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'NZD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'CRC' as 'name', 'CRC₡' as 'sign', 'CRC' as 'isocurrencycode', 'Costa Rican Colon' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'CRC') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'HRK' as 'name', 'kn' as 'sign', 'HRK' as 'isocurrencycode', 'Croatian Kuna' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'HRK') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'CUC' as 'name', 'CUC$' as 'sign', 'CUC' as 'isocurrencycode', 'Peso Convertible' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'CUC') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'CUP' as 'name', 'CUP₱' as 'sign', 'CUP' as 'isocurrencycode', 'Cuban Peso' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'CUP') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'ANG' as 'name', 'NAf' as 'sign', 'ANG' as 'isocurrencycode', 'Netherlands Antillean Guilder' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'ANG') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'CZK' as 'name', 'Kč' as 'sign', 'CZK' as 'isocurrencycode', 'Czech Koruna' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'CZK') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'DKK' as 'name', 'DKK Kr.' as 'sign', 'DKK' as 'isocurrencycode', 'Danish Krone' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'DKK') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'DJF' as 'name', 'Fdj' as 'sign', 'DJF' as 'isocurrencycode', 'Djibouti Franc' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'DJF') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'DOP' as 'name', 'RD$' as 'sign', 'DOP' as 'isocurrencycode', 'Dominican Peso' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'DOP') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'EGP' as 'name', 'E£' as 'sign', 'EGP' as 'isocurrencycode', 'Egyptian Pound' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'EGP') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'SVC' as 'name', 'SVC' as 'sign', 'SVC' as 'isocurrencycode', 'El Salvador Colon' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'SVC') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'ERN' as 'name', 'Nkf' as 'sign', 'ERN' as 'isocurrencycode', 'Nakfa' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'ERN') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'ETB' as 'name', 'Br' as 'sign', 'ETB' as 'isocurrencycode', 'Ethiopian Birr' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'ETB') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'FKP' as 'name', 'FK£' as 'sign', 'FKP' as 'isocurrencycode', 'Falkland Islands Pound' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'FKP') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'FJD' as 'name', 'FJ$' as 'sign', 'FJD' as 'isocurrencycode', 'Fiji Dollar' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'FJD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'XPF' as 'name', 'XPF₣' as 'sign', 'XPF' as 'isocurrencycode', 'CFP Franc' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'XPF') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'GMD' as 'name', 'D' as 'sign', 'GMD' as 'isocurrencycode', 'Dalasi' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'GMD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'GEL' as 'name', 'GEL' as 'sign', 'GEL' as 'isocurrencycode', 'Lari' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'GEL') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'GHS' as 'name', 'GH₵' as 'sign', 'GHS' as 'isocurrencycode', 'Ghana Cedi' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'GHS') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'GIP' as 'name', 'GIP£' as 'sign', 'GIP' as 'isocurrencycode', 'Gibraltar Pound' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'GIP') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'GTQ' as 'name', 'Q' as 'sign', 'GTQ' as 'isocurrencycode', 'Quetzal' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'GTQ') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'GNF' as 'name', 'FG' as 'sign', 'GNF' as 'isocurrencycode', 'Guinea Franc' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'GNF') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'GYD' as 'name', 'GY$' as 'sign', 'GYD' as 'isocurrencycode', 'Guyana Dollar' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'GYD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'HTG' as 'name', 'G' as 'sign', 'HTG' as 'isocurrencycode', 'Gourde' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'HTG') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'HNL' as 'name', 'L' as 'sign', 'HNL' as 'isocurrencycode', 'Lempira' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'HNL') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'HUF' as 'name', 'Ft' as 'sign', 'HUF' as 'isocurrencycode', 'Forint' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'HUF') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'ISK' as 'name', 'ISK kr' as 'sign', 'ISK' as 'isocurrencycode', 'Iceland Krona' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'ISK') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'IDR' as 'name', 'Rp' as 'sign', 'IDR' as 'isocurrencycode', 'Rupiah' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'IDR') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'XDR' as 'name', 'XDR' as 'sign', 'XDR' as 'isocurrencycode', 'SDR (Special Drawing Right)' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'XDR') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'IRR' as 'name', '﷼' as 'sign', 'IRR' as 'isocurrencycode', 'Iranian Rial' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'IRR') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'IQD' as 'name', 'ع.د' as 'sign', 'IQD' as 'isocurrencycode', 'Iraqi Dinar' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'IQD') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'ILS' as 'name', '₪' as 'sign', 'ILS' as 'isocurrencycode', 'New Israeli Sheqel' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'ILS') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'JMD' as 'name', 'JA$' as 'sign', 'JMD' as 'isocurrencycode', 'Jamaican Dollar' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'JMD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'JPY' as 'name', 'JPY¥' as 'sign', 'JPY' as 'isocurrencycode', 'Yen' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'JPY') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'JOD' as 'name', 'JODد.ا' as 'sign', 'JOD' as 'isocurrencycode', 'Jordanian Dinar' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'JOD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'KZT' as 'name', '₸' as 'sign', 'KZT' as 'isocurrencycode', 'Tenge' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'KZT') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'KES' as 'name', 'Ksh' as 'sign', 'KES' as 'isocurrencycode', 'Kenyan Shilling' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'KES') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'KPW' as 'name', 'KPW₩' as 'sign', 'KPW' as 'isocurrencycode', 'North Korean Won' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'KPW') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'KRW' as 'name', 'KRW₩' as 'sign', 'KRW' as 'isocurrencycode', 'Won' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'KRW') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'KWD' as 'name', 'KD' as 'sign', 'KWD' as 'isocurrencycode', 'Kuwaiti Dinar' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'KWD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'KGS' as 'name', 'KGS' as 'sign', 'KGS' as 'isocurrencycode', 'Som' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'KGS') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'LAK' as 'name', '₭' as 'sign', 'LAK' as 'isocurrencycode', 'Kip' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'LAK') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'LBP' as 'name', 'LL' as 'sign', 'LBP' as 'isocurrencycode', 'Lebanese Pound' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'LBP') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'LSL' as 'name', 'L' as 'sign', 'LSL' as 'isocurrencycode', 'Loti' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'LSL') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'ZAR' as 'name', 'R' as 'sign', 'ZAR' as 'isocurrencycode', 'Rand' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'ZAR') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'LRD' as 'name', 'LD$' as 'sign', 'LRD' as 'isocurrencycode', 'Liberian Dollar' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'LRD') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'LYD' as 'name', 'LD' as 'sign', 'LYD' as 'isocurrencycode', 'Libyan Dinar' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'LYD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'CHF' as 'name', 'CHf' as 'sign', 'CHF' as 'isocurrencycode', 'Swiss Franc' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'CHF') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'MOP' as 'name', 'MOP$' as 'sign', 'MOP' as 'isocurrencycode', 'Pataca' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'MOP') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'MKD' as 'name', 'den' as 'sign', 'MKD' as 'isocurrencycode', 'Denar' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'MKD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'MGA' as 'name', 'Ar' as 'sign', 'MGA' as 'isocurrencycode', 'Malagasy Ariary' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'MGA') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'MWK' as 'name', 'ZK' as 'sign', 'MWK' as 'isocurrencycode', 'Kwacha' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'MWK') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'MYR' as 'name', 'RM' as 'sign', 'MYR' as 'isocurrencycode', 'Malaysian Ringgit' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'MYR') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'MVR' as 'name', 'Rf' as 'sign', 'MVR' as 'isocurrencycode', 'Rufiyaa' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'MVR') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'MRO' as 'name', 'MRU' as 'sign', 'MRO' as 'isocurrencycode', 'Ouguiya' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'MRO') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'MUR' as 'name', 'Rs' as 'sign', 'MUR' as 'isocurrencycode', 'Mauritius Rupee' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'MUR') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'XUA' as 'name', 'XUA' as 'sign', 'XUA' as 'isocurrencycode', 'ADB Unit of Account' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'XUA') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'MXN' as 'name', 'Mex$' as 'sign', 'MXN' as 'isocurrencycode', 'Mexican Peso' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'MXN') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'MXV' as 'name', 'UDI' as 'sign', 'MXV' as 'isocurrencycode', 'Mexican Unidad de Inversion (UDI)' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'MXV') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'MDL' as 'name', 'L' as 'sign', 'MDL' as 'isocurrencycode', 'Moldovan Leu' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'MDL') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'MNT' as 'name', '₮' as 'sign', 'MNT' as 'isocurrencycode', 'Tugrik' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'MNT') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'MAD' as 'name', 'DH' as 'sign', 'MAD' as 'isocurrencycode', 'Moroccan Dirham' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'MAD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'MZN' as 'name', 'MT' as 'sign', 'MZN' as 'isocurrencycode', 'Mozambique Metical' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'MZN') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'MMK' as 'name', 'K' as 'sign', 'MMK' as 'isocurrencycode', 'Kyat' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'MMK') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'NAD' as 'name', 'N$' as 'sign', 'NAD' as 'isocurrencycode', 'Namibia Dollar' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'NAD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'NPR' as 'name', 'Rs' as 'sign', 'NPR' as 'isocurrencycode', 'Nepalese Rupee' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'NPR') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'NIO' as 'name', 'C$' as 'sign', 'NIO' as 'isocurrencycode', 'Cordoba Oro' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'NIO') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'NGN' as 'name', '₦' as 'sign', 'NGN' as 'isocurrencycode', 'Naira' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'NGN') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'OMR' as 'name', 'ر.ع' as 'sign', 'OMR' as 'isocurrencycode', 'Rial Omani' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'OMR') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'PKR' as 'name', 'Rs' as 'sign', 'PKR' as 'isocurrencycode', 'Pakistan Rupee' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'PKR') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'PAB' as 'name', 'B/.' as 'sign', 'PAB' as 'isocurrencycode', 'Balboa' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'PAB') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'PGK' as 'name', 'K' as 'sign', 'PGK' as 'isocurrencycode', 'Kina' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'PGK') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'PYG' as 'name', '₲' as 'sign', 'PYG' as 'isocurrencycode', 'Guarani' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'PYG') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'PEN' as 'name', 'S/' as 'sign', 'PEN' as 'isocurrencycode', 'Nuevo Sol' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'PEN') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'PHP' as 'name', '₱' as 'sign', 'PHP' as 'isocurrencycode', 'Philippine Peso' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'PHP') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'PLN' as 'name', 'zł' as 'sign', 'PLN' as 'isocurrencycode', 'Zloty' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'PLN') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'QAR' as 'name', 'QR' as 'sign', 'QAR' as 'isocurrencycode', 'Qatari Rial' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'QAR') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'RON' as 'name', 'L' as 'sign', 'RON' as 'isocurrencycode', 'New Romanian Leu' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'RON') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'RWF' as 'name', 'FRw' as 'sign', 'RWF' as 'isocurrencycode', 'Rwanda Franc' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'RWF') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'SHP' as 'name', 'SHP£' as 'sign', 'SHP' as 'isocurrencycode', 'Saint Helena Pound' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'SHP') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'WST' as 'name', 'WS$' as 'sign', 'WST' as 'isocurrencycode', 'Tala' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'WST') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'STD' as 'name', 'Db' as 'sign', 'STD' as 'isocurrencycode', 'Dobra' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'STD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'SAR' as 'name', 'SR' as 'sign', 'SAR' as 'isocurrencycode', 'Saudi Riyal' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'SAR') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'RSD' as 'name', 'din' as 'sign', 'RSD' as 'isocurrencycode', 'Serbian Dinar' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'RSD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'SCR' as 'name', 'SCR' as 'sign', 'SCR' as 'isocurrencycode', 'Seychelles Rupee' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'SCR') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'SLL' as 'name', 'Le' as 'sign', 'SLL' as 'isocurrencycode', 'Leone' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'SLL') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'SGD' as 'name', 'S$' as 'sign', 'SGD' as 'isocurrencycode', 'Singapore Dollar' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'SGD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'XSU' as 'name', 'S/.' as 'sign', 'XSU' as 'isocurrencycode', 'Sucre' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'XSU') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'SBD' as 'name', 'SI$' as 'sign', 'SBD' as 'isocurrencycode', 'Solomon Islands Dollar' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'SBD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'SOS' as 'name', 'Sh.So.' as 'sign', 'SOS' as 'isocurrencycode', 'Somali Shilling' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'SOS') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'SSP' as 'name', 'SS£' as 'sign', 'SSP' as 'isocurrencycode', 'South Sudanese Pound' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'SSP') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'LKR' as 'name', 'Rs' as 'sign', 'LKR' as 'isocurrencycode', 'Sri Lanka Rupee' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'LKR') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'SDG' as 'name', 'SDG' as 'sign', 'SDG' as 'isocurrencycode', 'Sudanese Pound' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'SDG') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'SRD' as 'name', 'Sr$' as 'sign', 'SRD' as 'isocurrencycode', 'Surinam Dollar' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'SRD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'SZL' as 'name', 'L' as 'sign', 'SZL' as 'isocurrencycode', 'Lilangeni' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'SZL') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'SEK' as 'name', 'kr' as 'sign', 'SEK' as 'isocurrencycode', 'Swedish Krona' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'SEK') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'CHE' as 'name', '€' as 'sign', 'CHE' as 'isocurrencycode', 'WIR Euro' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'CHE') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'CHF' as 'name', 'CHf' as 'sign', 'CHF' as 'isocurrencycode', 'Swiss Franc' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'CHF') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'CHW' as 'name', 'CHW' as 'sign', 'CHW' as 'isocurrencycode', 'WIR Franc' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'CHW') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'SYP' as 'name', 'LS' as 'sign', 'SYP' as 'isocurrencycode', 'Syrian Pound' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'SYP') LIMIT 1;";
    dbDelta($sql);


    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'TJS' as 'name', 'SM' as 'sign', 'TJS' as 'isocurrencycode', 'Somoni' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'TJS') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'TZS' as 'name', 'TSh' as 'sign', 'TZS' as 'isocurrencycode', 'Tanzanian Shilling' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'TZS') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'THB' as 'name', '฿' as 'sign', 'THB' as 'isocurrencycode', 'Baht' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'THB') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'TOP' as 'name', 'T$' as 'sign', 'TOP' as 'isocurrencycode', 'Pa’anga' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'TOP') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'TTD' as 'name', 'TT$' as 'sign', 'TTD' as 'isocurrencycode', 'Trinidad and Tobago Dollar' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'TTD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'TND' as 'name', 'DT' as 'sign', 'TND' as 'isocurrencycode', 'Tunisian Dinar' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'TND') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'TRY' as 'name', '₺' as 'sign', 'TRY' as 'isocurrencycode', 'Turkish Lira' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'TRY') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'TMT' as 'name', 'm' as 'sign', 'TMT' as 'isocurrencycode', 'Turkmenistan New Manat' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'TMT') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'UGX' as 'name', 'USh' as 'sign', 'UGX' as 'isocurrencycode', 'Uganda Shilling' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'UGX') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'UAH' as 'name', '₴' as 'sign', 'UAH' as 'isocurrencycode', 'Hryvnia' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'UAH') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'AED' as 'name', 'د.إ' as 'sign', 'AED' as 'isocurrencycode', 'UAE Dirham' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'AED') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'UYI' as 'name', '$U' as 'sign', 'UYI' as 'isocurrencycode', 'Uruguay Peso en Unidades Indexadas (URUIURUI)' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'UYI') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'USN' as 'name', 'USN$' as 'sign', 'USN' as 'isocurrencycode', 'US Dollar (Next day)' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'USN') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'UYU' as 'name', '$U' as 'sign', 'UYU' as 'isocurrencycode', 'Peso Uruguayo' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'UYU') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'UZS' as 'name', 'лв' as 'sign', 'UZS' as 'isocurrencycode', 'Uzbekistan Sum' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'UZS') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'VUV' as 'name', 'VT' as 'sign', 'VUV' as 'isocurrencycode', 'Vatu' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'VUV') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'VEF' as 'name', 'Bs' as 'sign', 'VEF' as 'isocurrencycode', 'Bolivar' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'VEF') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'VND' as 'name', '₫' as 'sign', 'VND' as 'isocurrencycode', 'Dong' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'VND') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'YER' as 'name', '﷼' as 'sign', 'YER' as 'isocurrencycode', 'Yemeni Rial' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'YER') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'ZMW' as 'name', 'ZK' as 'sign', 'ZMW' as 'isocurrencycode', 'Zambian Kwacha' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'ZMW') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'ZWL' as 'name', 'Z$' as 'sign', 'ZWL' as 'isocurrencycode', 'Zimbabwe Dollar' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_currency WHERE `name`= 'ZWL') LIMIT 1;";
    dbDelta($sql);
}

function expenseszyx987_createTable_tax() {
    global $wp_expenseszyx987_table_name;global $charset_collate;
    $sql = "CREATE TABLE IF NOT EXISTS " . $wp_expenseszyx987_table_name . "_tax (
          `id` BIGINT unsigned NOT NULL AUTO_INCREMENT,
          `name` varchar(45) not null,
          `description` varchar(250),
          `rate` decimal(15,6) NOT NULL,
          `status` tinyint(1) NOT NULL DEFAULT 1,
          `createtimeutc` DATETIME NOT NULL,
          `updatetimeutc` DATETIME,
          PRIMARY KEY (`id`)
    ) $charset_collate;";
    dbDelta( $sql );
}

function expenseszyx987_createTable_customertype() {
    global $wp_expenseszyx987_table_name;global $charset_collate;global $wpdb;
    $sql = "CREATE TABLE IF NOT EXISTS " . $wp_expenseszyx987_table_name . "_customertype (
          `id` BIGINT unsigned NOT NULL AUTO_INCREMENT,
          `name` varchar(45) not null,
          `description` varchar(250),
          `status` tinyint(1) NOT NULL DEFAULT 1,
          `createtimeutc` DATETIME NOT NULL,
          `updatetimeutc` DATETIME,
          PRIMARY KEY (`id`)
    ) $charset_collate;";
    dbDelta( $sql );

    $customertype_name = 'Business';
    $customertype_description = 'Business';
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $wp_expenseszyx987_table_name . "_customertype WHERE name = '" . $customertype_name . "'");
    if(intval($dbmyid) > 0) {
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $wp_expenseszyx987_table_name . "_customertype (`id`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 1 as 'id', %s as 'name', %s as 'description', 1 as 'status', UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_customertype WHERE `name`= '" . $customertype_name . "') LIMIT 1", array($customertype_name, $customertype_description)));
    }

    $customertype_name = 'Individual';
    $customertype_description = 'Individual';
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $wp_expenseszyx987_table_name . "_customertype WHERE name = '" . $customertype_name . "'");
    if(intval($dbmyid) > 0) {
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $wp_expenseszyx987_table_name . "_customertype (`id`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 2 as 'id', %s as 'name', %s as 'description', 1 as 'status', UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_customertype WHERE `name`= '" . $customertype_name . "') LIMIT 1", array($customertype_name, $customertype_description)));
    }
}

function expenseszyx987_createTable_customer() {
    global $wp_expenseszyx987_table_name;global $charset_collate;global $wpdb;
    $sql = "CREATE TABLE IF NOT EXISTS " . $wp_expenseszyx987_table_name . "_customer (
          `id` BIGINT unsigned NOT NULL AUTO_INCREMENT,
          `customertypeid` BIGINT unsigned,
          `name` varchar(250) NOT NULL,
          `description` varchar(250),
          `createtimeutc` DATETIME NOT NULL,
          `updatetimeutc` DATETIME,
          `status` tinyint(1) NOT NULL DEFAULT 1,
          PRIMARY KEY (`id`)
    ) $charset_collate;";
    dbDelta($sql);
}

function expenseszyx987_createTable_expense() {
    global $wp_expenseszyx987_table_name;global $charset_collate;
    $sql = "CREATE TABLE IF NOT EXISTS " . $wp_expenseszyx987_table_name . "_expense (
          `id` BIGINT unsigned NOT NULL AUTO_INCREMENT,
          `userid` BIGINT unsigned NOT NULL,
          `expensetypeid` BIGINT unsigned NOT NULL,
          `expensereferencenumber` varchar(250),
          `expensenotes` varchar(250),
          `expensedate` DATE not null,
          `expensecurrencyid` BIGINT unsigned NOT NULL,
          `expenseamount` decimal(15,6) NOT NULL,
          `expenseamountincludetax` tinyint(1),
          `taxrateid` BIGINT unsigned ,
          `customerid` BIGINT unsigned ,
          `isrecurring` tinyint(1) NOT NULL DEFAULT 0,
          `recurringpaymentstartdate` DATE, 
          `recurringpaymentenddate` DATE,
          `recurringpaymentfrequencyid` BIGINT unsigned,
          `recurringpaymentdayid` BIGINT unsigned,
          `status` tinyint(1) NOT NULL DEFAULT 1,
          `createtimeutc` DATETIME NOT NULL,
          `updatetimeutc` DATETIME,
          PRIMARY KEY (`id`)
    ) $charset_collate;";
    dbDelta( $sql );
}

function expenseszyx987_createTable_typecategory() {
    global $wp_expenseszyx987_table_name;global $charset_collate;global $wpdb;
    $sql = "CREATE TABLE IF NOT EXISTS " . $wp_expenseszyx987_table_name . "_typecategory (
          `id` BIGINT unsigned NOT NULL AUTO_INCREMENT,
          `name` varchar(250) NOT NULL,
          `description` varchar(250),
          `status` tinyint(1) NOT NULL DEFAULT 1,
          `createtimeutc` DATETIME NOT NULL,
          `updatetimeutc` DATETIME,
          PRIMARY KEY (`id`)
    ) $charset_collate;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_typecategory (`id`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 1 as id, 'Management' as name, 'Management' as description,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_typecategory WHERE `name`= 'Management') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_typecategory (`id`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 2 as id, 'Technology' as name, 'Technology' as description,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_typecategory WHERE `name`= 'Technology') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_typecategory (`id`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 3 as id, 'Services' as name, 'Services' as description,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_typecategory WHERE `name`= 'Services') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_typecategory (`id`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 4 as id, 'Other' as name, 'Other' as description,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_typecategory WHERE `name`= 'Other') LIMIT 1;";
    dbDelta($sql);
}

function expenseszyx987_createTable_type() {
    global $wp_expenseszyx987_table_name;global $charset_collate;global $wpdb;
    $sql = "CREATE TABLE IF NOT EXISTS " . $wp_expenseszyx987_table_name . "_type (
          `id` BIGINT unsigned NOT NULL AUTO_INCREMENT,
          `typecategoryid` BIGINT unsigned NOT NULL,
          `name` varchar(250) NOT NULL,
          `description` varchar(250),
          `status` tinyint(1) NOT NULL DEFAULT 1,
          `createtimeutc` DATETIME NOT NULL,
          `updatetimeutc` DATETIME,
          PRIMARY KEY (`id`)
    ) $charset_collate;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_type (`id`,`typecategoryid`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 1 as id, 1 as typecategoryid, 'Company Management' as name, 'Company Management' as description,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_type WHERE `name`= 'Company Management') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_type (`id`,`typecategoryid`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 2 as id, 1 as typecategoryid, 'Depreciation Expense' as name, 'Depreciation Expense' as description,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_type WHERE `name`= 'Depreciation Expense') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_type (`id`,`typecategoryid`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 3 as id, 1 as typecategoryid, 'Salaries and Wages' as name, 'Salaries and Wages' as description,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_type WHERE `name`= 'Salaries and Wages') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_type (`id`,`typecategoryid`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 4 as id, 2 as typecategoryid, 'Marketing and Sales' as name, 'Marketing and Sales' as description,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_type WHERE `name`= 'Marketing and Sales') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_type (`id`,`typecategoryid`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 5 as id, 2 as typecategoryid, 'IT and Network Expenses' as name, 'IT and Network Expenses' as description,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_type WHERE `name`= 'IT and Network Expenses') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_type (`id`,`typecategoryid`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 6 as id, 3 as typecategoryid, 'Accommodation' as name, 'Accommodation' as description,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_type WHERE `name`= 'Accommodation') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_type (`id`,`typecategoryid`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 7 as id, 3 as typecategoryid, 'Automobile Expense' as name, 'Automobile Expense' as description,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_type WHERE `name`= 'Automobile Expense') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_type (`id`,`typecategoryid`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 8 as id, 3 as typecategoryid, 'Check Expense' as name, 'Check Expense' as description,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_type WHERE `name`= 'Check Expense') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_type (`id`,`typecategoryid`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 9 as id, 3 as typecategoryid, 'Consultant Expense' as name, 'Consultant Expense' as description,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_type WHERE `name`= 'Consultant Expense') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_type (`id`,`typecategoryid`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 10 as id, 3 as typecategoryid, 'Credit Card Expense' as name, 'Credit Card Expense' as description,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_type WHERE `name`= 'Credit Card Expense') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_type (`id`,`typecategoryid`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 11 as id, 3 as typecategoryid, 'Debit Card Expense' as name, 'Debit Card Expense' as description,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_type WHERE `name`= 'Debit Card Expense') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_type (`id`,`typecategoryid`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 12 as id, 3 as typecategoryid, 'E Transfer Expense' as name, 'E Transfer Expense' as description,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_type WHERE `name`= 'E Transfer Expense') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_type (`id`,`typecategoryid`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 13 as id, 3 as typecategoryid, 'Health Kit and Other Health Services' as name, 'Health Kit and Other Health Services' as description,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_type WHERE `name`= 'Health Kit and Other Health Services') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_type (`id`,`typecategoryid`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 14 as id, 3 as typecategoryid, 'Janitorial Expense' as name, 'Janitorial Expense' as description,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_type WHERE `name`= 'Janitorial Expense') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_type (`id`,`typecategoryid`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 15 as id, 3 as typecategoryid, 'Meals and Entertainment' as name, 'Meals and Entertainment' as description,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_type WHERE `name`= 'Meals and Entertainment') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_type (`id`,`typecategoryid`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 16 as id, 3 as typecategoryid, 'Office and Furniture Supplies' as name, 'Office and Furniture Supplies' as description,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_type WHERE `name`= 'Office and Furniture Supplies') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_type (`id`,`typecategoryid`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 17 as id, 3 as typecategoryid, 'Postage' as name, 'Postage' as description,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_type WHERE `name`= 'Postage') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_type (`id`,`typecategoryid`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 18 as id, 3 as typecategoryid, 'Printing and Stationery' as name, 'Printing and Stationery' as description,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_type WHERE `name`= 'Printing and Stationery') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_type (`id`,`typecategoryid`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 19 as id, 3 as typecategoryid, 'Professional appearance - clothing' as name, 'Professional appearance - clothing' as description,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_type WHERE `name`= 'Professional appearance - clothing') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_type (`id`,`typecategoryid`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 20 as id, 3 as typecategoryid, 'Rent Expense' as name, 'Rent Expense' as description,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_type WHERE `name`= 'Rent Expense') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_type (`id`,`typecategoryid`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 21 as id, 3 as typecategoryid, 'Repairs and Maintenance' as name, 'Repairs and Maintenance' as description,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_type WHERE `name`= 'Repairs and Maintenance') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_type (`id`,`typecategoryid`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 22 as id, 3 as typecategoryid, 'Telephone and Fax Expense' as name, 'Telephone and Fax Expense' as description,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_type WHERE `name`= 'Telephone and Fax Expense') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $wp_expenseszyx987_table_name . "_type (`id`,`typecategoryid`,`name`,`description`,`status`,`createtimeutc`) SELECT * FROM (SELECT 23 as id, 3 as typecategoryid, 'Travel Expense' as name, 'Travel Expense' as description,1 as status,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $wp_expenseszyx987_table_name . "_type WHERE `name`= 'Travel Expense') LIMIT 1;";
    dbDelta($sql);
}

function expenseszyx987_createTable_users() {
    global $wp_expenseszyx987_table_name;global $charset_collate;global $wpdb;
    $sql = "CREATE TABLE IF NOT EXISTS " . $wp_expenseszyx987_table_name . "_users (
          `id` BIGINT unsigned NOT NULL AUTO_INCREMENT,
          `userid` BIGINT unsigned NOT NULL,
          `firstname` varchar(45) NOT NULL,
          `lastname` varchar(45) NOT NULL,
          `phone` varchar(45),
          `address` varchar(45),
          `address2` varchar(45),
          `city` varchar(45),
          `province` varchar(45),
          `country` varchar(250),
          `zip` varchar(45),
          `reportto` BIGINT unsigned,
          `picture` varchar(45),
          `email` varchar(250),
          `description` varchar(250),
          `departmentid` BIGINT unsigned,
          `roleid` BIGINT unsigned,
          `canreadinadminpage` tinyint(1) NOT NULL DEFAULT 0,
          `cancreateinadminpage` tinyint(1) NOT NULL DEFAULT 0,
          `caneditinadminpage` tinyint(1) NOT NULL DEFAULT 0,
          `canactivateinadminpage` tinyint(1) NOT NULL DEFAULT 0,
          `candeactivateinadminpage` tinyint(1) NOT NULL DEFAULT 0,
          `hourlyrate` DECIMAL(19,2),
          `yearlyrate` DECIMAL(19,2),
          `createtimeutc` DATETIME NOT NULL,
          `updatetimeutc` DATETIME,
          `enddate` DATETIME,
          `token` varchar(250),
          `tokenvalidto` DATETIME,
          `remembertoken` varchar(100),
          `remembertokenvalidto` DATETIME,
          `status` tinyint(1) NOT NULL DEFAULT 1,
          PRIMARY KEY (`id`)
    ) $charset_collate;";
    dbDelta($sql);
}

function expenseszyx987_createView() {
}

function expenseszyx987_createWebpage()
{
    global $wpdb;
    $title = "Expenses";
    $slug = 'expenses';

    // Search for an existing page with the specified page slug.
    $valid_page_found = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_type='page' AND post_status NOT IN ( 'pending', 'trash', 'future', 'auto-draft' )  AND post_name = %s LIMIT 1;", $slug ) );
    if ( $valid_page_found ) {
        return $valid_page_found;
    }

    // Search for a matching valid trashed page with the specified page slug.
    $trashed_page_found = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_type='page' AND post_status = 'trash' AND post_name = %s LIMIT 1;", $slug ) );

    if ( $trashed_page_found ) {
        $page_id   = $trashed_page_found;
        $page_data = array(
            'ID'          => $page_id,
            'post_status' => 'publish',
        );
        wp_update_post( $page_data );
        return $page_id;
    } else {
        $postData = array(
            'post_title' => $title,
            'post_name' => $slug,
            'post_status' => 'publish',
            'post_content' => '',
            'post_author' => $current_user->data->ID,
            'post_type'   => 'page',
            'post_category' => array()
        );
        $page_id = wp_insert_post($postData);
        return $page_id;
    }
}

function expenseszyx987_create_db() {
    global $wpdb;global $wp_expenseszyx987_table_name;global $charset_collate;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $wp_expenseszyx987_table_name = 'wp_expenseszyx987';
    expenseszyx987_createTable_constant();
    expenseszyx987_createTable_department();
    expenseszyx987_createTable_log();
    expenseszyx987_createTable_role();
    expenseszyx987_createTable_recurringpaymentfrequency();
    expenseszyx987_createTable_currency();
    expenseszyx987_createTable_tax();
    expenseszyx987_createTable_customertype();
    expenseszyx987_createTable_customer();
    expenseszyx987_createTable_expense();
    expenseszyx987_createTable_typecategory();
    expenseszyx987_createTable_type();
    expenseszyx987_createTable_users();

    expenseszyx987_createView();
    expenseszyx987_createStoredProcedure();
    expenseszyx987_createFirstAdminUser();
    expenseszyx987_additional_creation();

    //create a new web page for this plugin
    expenseszyx987_createWebpage();
}

register_activation_hook(__FILE__, 'expenseszyx987_create_db');

function expenseszyx987_admin() {
    include_once('expenseszyx987_admin.php');
}

function expenseszyx987_admin_actions() {
    add_options_page("Expenses Book", "Expenses Book", 1, "Expenses Book", "expenseszyx987_admin");
}

add_action('admin_menu', 'expenseszyx987_admin_actions');

function expenseszyx987_load_landing_page()
{
    $urlparts = wp_parse_url(home_url());
    $protocol = esc_html($urlparts['scheme']);
    $domain = esc_html($urlparts['host']);
    $actual_url = $protocol . "://" . $domain . esc_html($_SERVER['REQUEST_URI']);
    $actual_url = str_replace("&amp;", "&", $actual_url);
    $post_id = url_to_postid($actual_url);
    if($post_id <= 0) {return;}
    $currentpost = get_post($post_id);
    //error_log("at 1134, actual_url: " . $actual_url);
    //error_log("at 1135, post_id: " . $post_id);
    //error_log("at 1136, current Post: " . json_encode($currentpost));
    if($currentpost->post_name !== 'expenses') {return;}

    expenseszyx987_showLandingPage();
}
add_action('init', 'expenseszyx987_load_landing_page');

function expenseszyx987_validateDate($date, $format = 'Y-m-d H:i:s') {
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
}

function expenseszyx987_stripAllBackSlashes($str) {
    if($str===null){return '';}
    return str_replace('\\', '', $str);
}

function expenseszyx987_upload_folder() { 
    $upload = wp_upload_dir();
    $upload_dir = $upload['basedir'];
    $upload_dir = $upload_dir . '/dragonexpense';
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0700);  //0755 );
    } else {
        chmod($upload_dir, 0700);  //0755 );
    }
    return $upload_dir;
}

function expenseszyx987_upload_url() { 
    $upload = wp_upload_dir();
    $upload_url = $upload['baseurl'];
    $upload_url = $upload_url . '/dragonexpense';
    return $upload_url;
}
//$amountperpage, $pagenumber, $offset, $mysortby, $myorder, $searchexpensetypeid, $searchreferencenumber, $searchexpensenotes, $searchexpensefromdate, $searchexpensetodate, $searchexpensestatus, $searchminexpenseamount, $searchmaxexpenseamount, $searchexpensecustomerid, $searchexpenseisrecurring
function expenseszyx987_getExpenses_not_by_ajax($amountperpage, $pagenumber, $myoffset, $mysortby, $myorder, $expensetypeid, $searchreferencenumber, $searchexpensenotes, $fromdate, $todate, $expensestatus, $searchminexpenseamount, $searchmaxexpenseamount, $searchexpensecustomerid, $searchexpenseisrecurring) {
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        return [];
    }
    global $wpdb;global $wp_expenseszyx987_table_name;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name1 = $wp_expenseszyx987_table_name . '_expense';
    $table_name3 = $wp_expenseszyx987_table_name . '_constant';
    $table_name5 = $wp_expenseszyx987_table_name . '_type';
    $storedprocedure_name = $wp_expenseszyx987_table_name. '_getExpenseList';
    $fromdate = $fromdate === '' ? '1000-01-01' : $fromdate;
    $todate = $todate === '' ? '9999-12-31' : $todate;
    //$needToCallStoredProcedure = true;
    //if($searchreferencenumber !== '' || $searchexpensenotes !== '' || $expensetypeid > 0 || $expensestatus >= 0 || $fromdate !== '1000-01-01' || $todate !== '9999-12-31') {
    //    $needToCallStoredProcedure = true;
    //}
    if($wpdb->use_mysqli) {
        if($wpdb->dbh->connect_error) {
            die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
        }
        $total = "0";
        $expenses = array();

        $query = "SELECT name, value from $table_name3 WHERE status = 1";
        $stmt3 = $wpdb->dbh->prepare($query);
        $stmt3->execute();
        $myresult = $stmt3->get_result();
        $result3 = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
        $stmt3->close();

        //if($needToCallStoredProcedure) {
            $query = "CALL " . $storedprocedure_name . "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, @outvalue);";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 'i';
            $parameterArray[] = &$pagenumber;

            $types .= 'i';
            $parameterArray[] = &$amountperpage;

            $types .= 'i';
            $parameterArray[] = &$myoffset;

            $types .= 's';
            $parameterArray[] = &$mysortby;

            $types .= 's';
            $parameterArray[] = &$myorder;

            $types .= 's';
            $wpprefix = $wpdb->prefix;
            $parameterArray[] = &$wpprefix;

            $types .= 'i'; //show only this user's expenses list
            $userid = intval($current_user->data->ID);
            $parameterArray[] = &$userid;

            $types .= 'i';
            $parameterArray[] = &$expensetypeid;

            $types .= 's';
            $parameterArray[] = &$searchreferencenumber;

            $types .= 's';
            $parameterArray[] = &$searchexpensenotes;

            $types .= 's';
            $parameterArray[] = &$fromdate;

            $types .= 's';
            $parameterArray[] = &$todate;

            $types .= 'd';
            $parameterArray[] = &$searchminexpenseamount;

            $types .= 'd';
            $parameterArray[] = &$searchmaxexpenseamount;

            $types .= 'i';
            $parameterArray[] = &$searchexpensecustomerid;

            $types .= 'i'; //0: no, 1: yes, -1: both
            $parameterArray[] = &$searchexpenseisrecurring;

            $types .= 'i'; //0: inactive, 1: active, -1: both
            $parameterArray[] = &$expensestatus;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $expenses = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            $stmt2 = $wpdb->dbh->prepare('SELECT @outvalue');
            $stmt2->execute();
            $myresult2 = $stmt2->get_result();
            $totalObjArr = $myresult2 === FALSE ? array() : $myresult2->fetch_all(MYSQLI_ASSOC);
            $stmt2->close();

            foreach ($totalObjArr[0] as $key => $value) {
                if($key === '@outvalue') {
                    $total = $value == null ? "0" : $value;
                }
            }
            foreach ($expenses as $expense) {
                foreach ($expense as $key => $value) {
                    $expense[$key] = $value === null ? '' : deslash($value);
                }
            }
        //}
        //error_log("at 1277, expenses: " . wp_json_encode($expenses));
        $result = [];
        $result["expense"] = $expenses;
        $result["total"] = $total;
        $result["settings"] = $result3;
        //error_log("at 1231, result: " . wp_json_encode($result));
        return $result;
    }
    return [];
}

function expenseszyx987_userCanReadInAdminPage() {
    global $wpdb; global $dragon_expense_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = "wp_expenseszyx987_users";
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        return false;
    }
    $userid = intval($current_user->data->ID);
    $results = array();
    if(intval($userid) > 0) {
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                echo "Connection failed: " . esc_html($wpdb->dbh->connect_error);
                exit;
            }
            $stmt = $wpdb->dbh->prepare("SELECT * FROM $table_name WHERE status = 1 and userid = ?");
            $stmt->bind_param("i", intval($userid));
            $stmt->execute();
            $myresult = $stmt->get_result();
            $results = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            foreach($results as $result) {
                foreach($result as $key => $value) {
                    $result[$key] = deslash($value);
                }
            }
        } else {
            echo 'Mysqli is not supported by your system. ';
            exit;
        }
    }
    if(count($results) !== 1) {return false;}
    if(intval($results[0]["canreadinadminpage"]) === 1) {
        return true;
    }
    return false;
}

function expenseszyx987_userCanCreateInAdminPage() {
    global $wpdb; global $dragon_expense_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = "wp_expenseszyx987_users";
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        return false;
    }
    $userid = intval($current_user->data->ID);
    $results = array();
    if(intval($userid) > 0) {
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                echo "Connection failed: " . esc_html($wpdb->dbh->connect_error);
                exit;
            }
            $stmt = $wpdb->dbh->prepare("SELECT * FROM $table_name WHERE status = 1 and userid = ?");
            $stmt->bind_param("i", intval($userid));
            $stmt->execute();
            $myresult = $stmt->get_result();
            $results = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            foreach($results as $result) {
                foreach($result as $key => $value) {
                    $result[$key] = deslash($value);
                }
            }
        } else {
            echo 'Mysqli is not supported by your system. ';
            exit;
        }
    }
    if(count($results) !== 1) {return false;}
    if(intval($results[0]["cancreateinadminpage"]) === 1) {
        return true;
    }
    return false;
}

function expenseszyx987_userCanEditInAdminPage() {
    global $wpdb; global $dragon_expense_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = "wp_expenseszyx987_users";
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        return false;
    }
    $userid = intval($current_user->data->ID);
    $results = array();
    if(intval($userid) > 0) {
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                echo "Connection failed: " . esc_html($wpdb->dbh->connect_error);
                exit;
            }
            $stmt = $wpdb->dbh->prepare("SELECT * FROM $table_name WHERE status = 1 and userid = ?");
            $stmt->bind_param("i", intval($userid));
            $stmt->execute();
            $myresult = $stmt->get_result();
            $results = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            foreach($results as $result) {
                foreach($result as $key => $value) {
                    $result[$key] = deslash($value);
                }
            }
        } else {
            echo 'Mysqli is not supported by your system. ';
            exit;
        }
    }
    if(count($results) !== 1) {return false;}
    if(intval($results[0]["caneditinadminpage"]) === 1) {
        return true;
    }
    return false;
}

function expenseszyx987_userCanActivateInAdminPage() {
    global $wpdb; global $dragon_expense_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = "wp_expenseszyx987_users";
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        return false;
    }
    $userid = intval($current_user->data->ID);
    $results = array();
    if(intval($userid) > 0) {
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                echo "Connection failed: " . esc_html($wpdb->dbh->connect_error);
                exit;
            }
            $stmt = $wpdb->dbh->prepare("SELECT * FROM $table_name WHERE status = 1 and userid = ?");
            $stmt->bind_param("i", intval($userid));
            $stmt->execute();
            $myresult = $stmt->get_result();
            $results = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            foreach($results as $result) {
                foreach($result as $key => $value) {
                    $result[$key] = deslash($value);
                }
            }
        } else {
            echo 'Mysqli is not supported by your system. ';
            exit;
        }
    }
    if(count($results) !== 1) {return false;}
    if(intval($results[0]["canactivateinadminpage"]) === 1) {
        return true;
    }
    return false;
}

function expenseszyx987_userCanDeactivateInAdminPage() {
    global $wpdb; global $dragon_expense_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = "wp_expenseszyx987_users";
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        return false;
    }
    $userid = intval($current_user->data->ID);
    $results = array();
    if(intval($userid) > 0) {
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                echo "Connection failed: " . esc_html($wpdb->dbh->connect_error);
                exit;
            }
            $stmt = $wpdb->dbh->prepare("SELECT * FROM $table_name WHERE status = 1 and userid = ?");
            $stmt->bind_param("i", intval($userid));
            $stmt->execute();
            $myresult = $stmt->get_result();
            $results = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            foreach($results as $result) {
                foreach($result as $key => $value) {
                    $result[$key] = deslash($value);
                }
            }
        } else {
            echo 'Mysqli is not supported by your system. ';
            exit;
        }
    }
    if(count($results) !== 1) {return false;}
    if(intval($results[0]["candeactivateinadminpage"]) === 1) {
        return true;
    }
    return false;
}

function expenseszyx987_getAllExpenses($onlyActive = false) {
    global $wpdb; global $dragon_expense_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_expenseszyx987_expense';
    if($onlyActive) {
        $results = $wpdb->get_results("SELECT * FROM $table_name WHERE status = 1");
    } else {
        $results = $wpdb->get_results("SELECT * FROM $table_name");
    }
    foreach($results as $result) {
        foreach($result as $key => $value) {
            $result->$key = deslash($value);
        }
    }
    return $results;
}

function expenseszyx987_getAllExpenseTypes($onlyActive = false) {
    global $wpdb; global $dragon_expense_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_expenseszyx987_type';
    $table_name2 = 'wp_expenseszyx987_typecategory';
    if($onlyActive) {
        $results = $wpdb->get_results("SELECT t.*,tc.name as typecategoryname FROM $table_name t JOIN $table_name2 tc ON t.typecategoryid = tc.id WHERE t.status = 1");
    } else {
        $results = $wpdb->get_results("SELECT t.*,tc.name as typecategoryname FROM $table_name t JOIN $table_name2 tc ON t.typecategoryid = tc.id ");
    }
    foreach($results as $result) {
        foreach($result as $key => $value) {
            $result->$key = deslash($value);
        }
    }
    return $results;
}

function expenseszyx987_validateTime($mytime) {
    $timevalid = true;
    $dateOk=preg_match('/^[0-2][0-9][:][0-5][0-9]$/', $mytime);
    if(!$dateOk) {
        $timevalid = false;
    }
    $temp01 = floatval(str_replace(":",".",$mytime));
    if($temp01 < 0 || $temp01 > 24.0) {
        $timevalid = false;
    }
    return $timevalid;
}

//only for admin page
add_action('wp_ajax_expenseszyx987_getExpenses', 'expenseszyx987_getExpenses');
function expenseszyx987_getExpenses() {
    check_ajax_referer('expenseszyx987_getExpenses', 'expenseszyx987_hidden_security_getexpenses');
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        echo 'Invalid user info.';
        exit();
    }
    //check user_role table to see if this user can read expenses
    if(!expenseszyx987_userCanReadInAdminPage()) {echo 'You are not authorized to read expenses. Please contact web admin.';exit();}

    if((!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $storedprocedure_name = 'wp_expenseszyx987_getExpenseList';

        $userid = empty($_POST['userid']) ? '-1' : strip_tags(sanitize_text_field($_POST['userid']));
        $userid = intval($userid);

        $expensetypeid = empty($_POST['expensetypeid']) ? '-1' : strip_tags(sanitize_text_field($_POST['expensetypeid']));
        $expensetypeid = intval($expensetypeid);

        $mystatus_temp = $_POST['mystatus'] === null ? '' : strip_tags(sanitize_text_field($_POST['mystatus']));
        $mystatus = $mystatus_temp === '' ? 0 : intval($mystatus_temp);

        $amountperpage = empty($_POST['amountperpage']) ? '10' : strip_tags(sanitize_text_field($_POST['amountperpage']));
        $amountperpage = intval($amountperpage);
        if($amountperpage === -1) {$amountperpage = 10;};

        $pagenumber = empty($_POST['pagenumber']) ? '1' : strip_tags(sanitize_text_field($_POST['pagenumber']));
        $pagenumber = intval($pagenumber);
        $myoffset = ($pagenumber - 1) * $amountperpage;

        $mysortby = empty($_POST['sortby']) ? '' : strip_tags(sanitize_text_field($_POST['sortby']));
        $mysortby = expenseszyx987_stripAllBackSlashes(trim($mysortby));
        $mysortby = $mysortby === '' ? 'id' : $mysortby;

        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : strip_tags(sanitize_text_field($_POST['order']));
        $myorder = $myorder === '' ? 'desc' : $myorder;

        $fromdate = empty($_POST['fromdate']) ? '1000-01-01' : strip_tags(sanitize_text_field($_POST['fromdate']));
        $todate = empty($_POST['todate']) ? '9999-12-31' : strip_tags(sanitize_text_field($_POST['todate']));

        if(expenseszyx987_validateDate($fromdate, 'Y-m-d') && expenseszyx987_validateDate($todate, 'Y-m-d')) {
            if($fromdate > $todate) {
                echo "Error. From date is later than to date.";exit();
            }
        }else{
            echo "Error. Please enter a valid date.";exit();
        }

        $searchminexpenseamount_temp = trim($_POST['searchminexpenseamount']) === '' ? '' : strip_tags(sanitize_text_field($_POST['searchminexpenseamount']));
        $searchminexpenseamount = trim($searchminexpenseamount_temp) === '' ? '' : floatval($searchminexpenseamount_temp);

        $searchmaxexpenseamount_temp = trim($_POST['searchmaxexpenseamount']) === '' ? '' : strip_tags(sanitize_text_field($_POST['searchmaxexpenseamount']));
        $searchmaxexpenseamount = trim($searchmaxexpenseamount_temp) === '' ? '' : floatval($searchmaxexpenseamount_temp);

        $searchexpensecustomerid_temp = trim($_POST['searchexpensecustomerid']) === '' ? '' : strip_tags(sanitize_text_field($_POST['searchexpensecustomerid']));
        $searchexpensecustomerid = trim($searchexpensecustomerid_temp) === '' ? -1 : intval($searchexpensecustomerid_temp);

        $searchexpenseisrecurring_temp = trim($_POST['searchexpenseisrecurring']) === '' ? '' : strip_tags(sanitize_text_field($_POST['searchexpenseisrecurring']));
        $searchexpenseisrecurring = trim($searchexpenseisrecurring_temp) === '' ? -1 : intval($searchexpenseisrecurring_temp);

        $searchreferencenumber_temp = (empty($_POST['searchreferencenumber']) || trim($_POST['searchreferencenumber']) === '') ? '' : strip_tags(sanitize_text_field($_POST['searchreferencenumber']));
        $searchreferencenumber_temp = preg_replace('/[^a-zA-Z0-9\/()$@?!\[\]{}#%^*+|~]/', '%', $searchreferencenumber_temp);
        $searchreferencenumber = trim($searchreferencenumber_temp) === '' ? '' : $searchreferencenumber_temp;

        $searchexpensenotes_temp = (empty($_POST['searchexpensenotes']) || trim($_POST['searchexpensenotes']) === '') ? '' : strip_tags(sanitize_text_field($_POST['searchexpensenotes']));
        $searchexpensenotes_temp = preg_replace('/[^a-zA-Z0-9\/()$@?!\[\]{}#%^*+|~]/', '%', $searchexpensenotes_temp);
        $searchexpensenotes = trim($searchexpensenotes_temp) === '' ? '' : $searchexpensenotes_temp;

        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $query = "CALL " . $storedprocedure_name . "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, @outvalue);";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 'i';
            $parameterArray[] = &$pagenumber;

            $types .= 'i';
            $parameterArray[] = &$amountperpage;

            $types .= 'i';
            $parameterArray[] = &$myoffset;

            $types .= 's';
            $parameterArray[] = &$mysortby;

            $types .= 's';
            $parameterArray[] = &$myorder;

            $types .= 's';
            $wpprefix = $wpdb->prefix;
            $parameterArray[] = &$wpprefix;

            $types .= 'i';
            //$userid = -1;  //intval($current_user->data->ID);
            $parameterArray[] = &$userid;

            $types .= 'i';
            $parameterArray[] = &$expensetypeid;

            $types .= 's';
            $parameterArray[] = &$searchreferencenumber;

            $types .= 's';
            $parameterArray[] = &$searchexpensenotes;

            $types .= 's';
            $parameterArray[] = &$fromdate;

            $types .= 's';
            $parameterArray[] = &$todate;

            $types .= 'd';
            $parameterArray[] = &$searchminexpenseamount;

            $types .= 'd';
            $parameterArray[] = &$searchmaxexpenseamount;

            $types .= 'i';
            $parameterArray[] = &$searchexpensecustomerid;

            $types .= 'i'; //0: no, 1: yes, -1: both
            $parameterArray[] = &$searchexpenseisrecurring;

            $types .= 'i'; //0: inactive, 1: active, -1: both
            $parameterArray[] = &$mystatus;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $expenses = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            $stmt2 = $wpdb->dbh->prepare('SELECT @outvalue');
            $stmt2->execute();
            $myresult2 = $stmt2->get_result();
            $totalObjArr = $myresult2 === FALSE ? array() : $myresult2->fetch_all(MYSQLI_ASSOC);
            $stmt2->close();

            $total = "0";
            foreach($totalObjArr[0] as $key => $value) {
                if($key === '@outvalue') {
                    $total = $value == null ? "0" : $value;
                }
            }
            foreach($expenses as $expense) {
                foreach($expense as $key => $value) {
                    $expense[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["expense"] = $expenses;
            $result["total"] = $total;
            //error_log("at 1699, result: " . wp_json_encode($result));
            header("Content-Type: application/json");
            echo wp_json_encode($result);
            exit();
        }
    }
    header("Content-Type: application/json");
    echo wp_json_encode("{}");
    exit();
}

function expenseszyx987_addTypecategory() {
    global $dragon_expense_dbResult;
    $mynonce = empty($_POST['expenseszyx987_hidden_security']) ? '' : strip_tags(sanitize_text_field($_POST['expenseszyx987_hidden_security']));
    if(wp_verify_nonce($mynonce, 'expenseszyx987_addTypecategory') !== 1) {$dragon_expense_dbResult .= 'Invalid data. ';return;}
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        $dragon_expense_dbResult .= 'Invalid user info.';
        return;
    }
    if(!expenseszyx987_userCanCreateInAdminPage()) {
        $dragon_expense_dbResult .= 'You are not authorized to create data in admin page. Please contact web admin. ';
        return;
    }
    if(in_array('administrator', (array) $current_user->roles) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987_typecategory';
        $name = trim(sanitize_text_field($_POST['expenseszyx987_addtypecategoryname']));
        $description = trim(sanitize_text_field($_POST['expenseszyx987_addtypecategorydescription']));
        if($name === '') {$dragon_expense_dbResult .= 'Create a new type category: type category name is required. Not saved. ';return;}

        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $stmt = $wpdb->dbh->prepare("SELECT COUNT(*) countresult FROM $table_name WHERE name = ?");
            $stmt->bind_param("s", $name);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            if(count($result) === 1) {
                $temp_row = $result[0];
                $temp_result = $temp_row["countresult"];
                $dbcount = $temp_result === null ? 0 : intval($temp_result);
                if($dbcount !== 0) {$dragon_expense_dbResult .= "Create a new type category: type category name \"" . $name . "\" already exists in the table. Not saved. ";return;}
            } else {
                $dragon_expense_dbResult .= "Create a new type category: type category name \"" . $name . "\" query has error. Not saved. ";return;
            }

            $query = "INSERT INTO " . $table_name . " (`name`,`description`,`createtimeutc`) VALUES (?,?,UTC_TIMESTAMP())";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 's';
            $parameterArray[] = &$name;

            $types .= 's';
            $parameterArray[] = &$description;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->insert_id;
            $stmt->close();

            if($myresult <= 0) {
                $dragon_expense_dbResult .= 'Error adding a type category into table ' . $table_name . ". ";return;
            }
        } else {
            $dragon_expense_dbResult .= 'Mysqli is not supported by your system. ';return;
        }
        $dragon_expense_dbResult .= 'Success.';
    } else {
        $dragon_expense_dbResult .= 'Invalid data.';
    }
}

function expenseszyx987_getAllTypecategories($onlyActive = false) {
    global $wpdb; global $dragon_expense_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_expenseszyx987_typecategory';
    if($onlyActive) {
        $results = $wpdb->get_results("SELECT * from $table_name WHERE status = 1 order by name");
    } else {
        $results = $wpdb->get_results("SELECT * from $table_name order by name");
    }
    foreach($results as $result) {
        foreach($result as $key => $value) {
            $result->$key = deslash($value);
        }
    }
    return $results;
}

add_action('wp_ajax_expenseszyx987_saveTypecategory', 'expenseszyx987_saveTypecategory');
function expenseszyx987_saveTypecategory() {
    check_ajax_referer('expenseszyx987_saveTypecategory', 'expenseszyx987_hidden_security_savetypecategory');
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        echo 'Invalid user info.';
        exit();
    }
    if(!expenseszyx987_userCanEditInAdminPage()) {
        echo 'You are not authorized to edit data in admin page. Please contact web admin.';
        exit();
    }
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        $typecategoryid_temp = empty($_POST['id']) ? 0 : strip_tags(sanitize_text_field($_POST['id']));
        $typecategoryid = intval($typecategoryid_temp);

        if($typecategoryid <= 0 || $_POST['status'] === null || $_POST['status'] === '') {echo "Invalid id.";exit();}    

        $typecategoryname_temp = $_POST['name'] === null ? '' : strip_tags(sanitize_text_field($_POST['name']));
        $typecategoryname = expenseszyx987_stripAllBackSlashes($typecategoryname_temp);

        $typecategorydescription_temp = $_POST['description'] === null ? '' : strip_tags(sanitize_text_field($_POST['description']));
        $typecategorydescription = expenseszyx987_stripAllBackSlashes($typecategorydescription_temp);

        $typecategorystatus_temp = $_POST['status'] === null ? '' : strip_tags(sanitize_text_field($_POST['status']));
        $typecategorystatus = $typecategorystatus_temp === '' ? 0 : intval($typecategorystatus_temp);

        if($typecategoryname === '' && $typecategorydescription === '' && $typecategorystatus !== 0 && $typecategorystatus !== 1) {
            echo "Please enter a value.";exit();
        }
        if($typecategoryname === '' || ($typecategorystatus !== 0 && $typecategorystatus !== 1)) {
            echo "Name and status are required.";exit();
        }
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987_typecategory';
        $finalresult = 'Success';
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $stmt = $wpdb->dbh->prepare("SELECT COUNT(*) countresult FROM $table_name WHERE name = ? and id != ?");
            $stmt->bind_param("si", $typecategoryname, $typecategoryid);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            if(count($result) === 1) {
                $temp_row = $result[0];
                $temp_result = $temp_row["countresult"];
                $dbcount = $temp_result === null ? 0 : intval($temp_result);
                if($dbcount !== 0) {echo "Edit a type category: type category name \"" . esc_html($typecategoryname) . "\" already exists in the table. Not saved.";exit();}
            } else {
                echo "Edit a type category: type category name \"" . esc_html($typecategoryname) . "\" query has error. Not saved.";exit();
            }

            $stmt=null;
            $sqlColumnsArray = array();
            if($rolename !== '') {
                $sqlColumnsArray['name|s'] = $typecategoryname;
            }
            $sqlColumnsArray['description|s'] = $typecategorydescription;
            if($typecategorystatus === 0 || $typecategorystatus === 1) {
                $sqlColumnsArray['status|i'] = $typecategorystatus;
            }
            if(count($sqlColumnsArray) > 0) {
                $query = "UPDATE $table_name SET ";
                $types = '';
                $parameterArray = array('');
                foreach($sqlColumnsArray as $key => $value) {
                    $temp = explode('|', $key, 2);

                    $types .= $temp[1];
                    $query .= ' ' . $temp[0] . ' = ?, ';
                    if($temp[0] === 'name') {
                        $parameterArray[] = &$typecategoryname;
                    } elseif($temp[0] === 'description') {
                        $parameterArray[] = &$typecategorydescription;
                    } elseif($temp[0] === 'status') {
                        $parameterArray[] = &$typecategorystatus;
                    }
                }
                $query .= " updatetimeutc = UTC_TIMESTAMP() WHERE id = ? ";
                $types .= 'i';
                $parameterArray[] = &$typecategoryid;
                $parameterArray[0] = $types;
                $stmt = $wpdb->dbh->prepare($query);
                call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                $stmt->execute();
                if($wpdb->dbh->errno > 0 || $stmt->errno > 0) {
                    $finalresult = 'Edit type category failed';
                }
                $stmt->close();
            } else {
                $finalresult = 'Nothing is updated';
            }
            echo esc_html($finalresult);
            exit();
        }
    }
    echo "Invalid data.";
    exit();
}

function expenseszyx987_addType() {
    global $dragon_expense_dbResult;
    $mynonce = empty($_POST['expenseszyx987_hidden_security']) ? '' : strip_tags(sanitize_text_field($_POST['expenseszyx987_hidden_security']));
    if(wp_verify_nonce($mynonce, 'expenseszyx987_addType') !== 1) {$dragon_expense_dbResult .= 'Invalid data. ';return;}
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        $dragon_expense_dbResult .= 'Invalid user info.';
        return;
    }
    if(!expenseszyx987_userCanCreateInAdminPage()) {
        $dragon_expense_dbResult .= 'You are not authorized to create data in admin page. Please contact web admin.';
        return;
    }
    if(in_array('administrator', (array) $current_user->roles) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987_type';
        $name = sanitize_text_field($_POST['expenseszyx987_addtypename']);
        $name = expenseszyx987_stripAllBackSlashes($name);
        $description = sanitize_text_field($_POST['expenseszyx987_addtypedescription']);
        $description = expenseszyx987_stripAllBackSlashes($description);
        $typecategoryid = intval(sanitize_text_field($_POST['expenseszyx987_addtypetypecategory']));

        if($name === '' || $typecategoryid < 1) {$dragon_expense_dbResult .= 'Create a new type: type category and type name are required. Not saved. ';return;}
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $stmt = $wpdb->dbh->prepare("SELECT COUNT(*) countresult FROM $table_name WHERE name = ? and typecategoryid = ?");
            $stmt->bind_param("si", $name, $typecategoryid);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            if(count($result) === 1) {
                $temp_row = $result[0];
                $temp_result = $temp_row["countresult"];
                $dbcount = $temp_result === null ? 0 : intval($temp_result);
                if($dbcount !== 0) {$dragon_expense_dbResult .= "Create a new type: type name \"" . $name . "\" already exists for that type category in the table. Not saved. ";return;}
            } else {
                $dragon_expense_dbResult .= "Create a new type: type name \"" . $name . "\" query has error. Not saved. ";return;
            }
            $query = "INSERT INTO " . $table_name . " (`typecategoryid`,`name`,`description`,`createtimeutc`) VALUES (?,?,?,UTC_TIMESTAMP())";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 'i';
            $parameterArray[] = &$typecategoryid;

            $types .= 's';
            $parameterArray[] = &$name;

            $types .= 's';
            $parameterArray[] = &$description;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->insert_id;
            $stmt->close();

            if($myresult <= 0) {
                $dragon_expense_dbResult .= 'Error adding a type into table ' . $table_name . ". ";return;
            }
        } else {
            $dragon_expense_dbResult .= 'Mysqli is not supported by your system. ';return;
        }
        $dragon_expense_dbResult .= 'Success.';
    } else {
        $dragon_expense_dbResult .= 'Invalid data.';
    }
}

function expenseszyx987_getAllTypes($onlyActive = false) {
    global $wpdb; global $dragon_expense_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_expenseszyx987_type';
    if($onlyActive) {
        $results = $wpdb->get_results("SELECT * from $table_name WHERE status = 1 order by name");
    } else {
        $results = $wpdb->get_results("SELECT * from $table_name order by name");
    }
    foreach($results as $result) {
        foreach($result as $key => $value) {
            $result->$key = deslash($value);
        }
    }
    return $results;
}

add_action('wp_ajax_expenseszyx987_saveType', 'expenseszyx987_saveType');
function expenseszyx987_saveType() {
    check_ajax_referer('expenseszyx987_saveType', 'expenseszyx987_hidden_security_savetype');
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        echo 'Invalid user info.';
        exit();
    }
    if(!expenseszyx987_userCanEditInAdminPage()) {
        echo 'You are not authorized to edit data in admin page. Please contact web admin.';
        exit();
    }
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        $typeid_temp = empty($_POST['id']) ? 0 : strip_tags(sanitize_text_field($_POST['id']));
        $typeid = intval($typeid_temp);

        if($typeid <= 0 || $_POST['status'] === null || $_POST['status'] === '') {echo "Invalid id.";exit();}

        $typename_temp = $_POST['name'] === null ? '' : strip_tags(sanitize_text_field($_POST['name']));
        $typename = expenseszyx987_stripAllBackSlashes($typename_temp);

        $typedescription_temp = $_POST['description'] === null ? '' : strip_tags(sanitize_text_field($_POST['description']));
        $typedescription = expenseszyx987_stripAllBackSlashes($typedescription_temp);

        $typecategoryid_temp = $_POST['typecategoryid'] === null ? '' : strip_tags(sanitize_text_field($_POST['typecategoryid']));
        $typecategoryid = $typecategoryid_temp === '' ? 0 : intval($typecategoryid_temp);

        $typestatus_temp = $_POST['status'] === null ? '' : strip_tags(sanitize_text_field($_POST['status']));
        $typestatus = $typestatus_temp === '' ? 0 : intval($typestatus_temp);

        if($typename === '' && $typedescription === '' && $typecategoryid <= 0 && ($typestatus !== 0 && $typestatus !== 1)) {
            echo "Please enter a value.";exit();
        }
        if($typename === '' || ($typestatus !== 0 && $typestatus !== 1) || $typecategoryid <= 0) {
            echo "Name, type category, and status are required.";exit();
        }

        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987_type';
        $finalresult = 'Success';
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $stmt = $wpdb->dbh->prepare("SELECT COUNT(*) countresult FROM $table_name WHERE name = ? and id != ?");
            $stmt->bind_param("si", $typename, $typeid);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            if(count($result) === 1) {
                $temp_row = $result[0];
                $temp_result = $temp_row["countresult"];
                $dbcount = $temp_result === null ? 0 : intval($temp_result);
                if($dbcount !== 0) {echo "Edit a type: type name \"" . esc_html($typename) . "\" already exists in the table. Not saved.";exit();}
            } else {
                echo "Edit a type: type name \"" . esc_html($typename) . "\" query has error. Not saved.";exit();
            }

            $stmt=null;
            $sqlColumnsArray = array();
            if($rolename !== '') {
                $sqlColumnsArray['name|s'] = $typename;
            }
            $sqlColumnsArray['description|s'] = $typedescription;
            if($typecategoryid > 0) {
                $sqlColumnsArray['typecategoryid|i'] = $typecategoryid;
            }
            if($typestatus === 0 || $typestatus === 1) {
                $sqlColumnsArray['status|i'] = $typestatus;
            }
            if(count($sqlColumnsArray) > 0) {
                $query = "UPDATE $table_name SET ";
                $types = '';
                $parameterArray = array('');
                foreach($sqlColumnsArray as $key => $value) {
                    $temp = explode('|', $key, 2);

                    $types .= $temp[1];
                    $query .= ' ' . $temp[0] . ' = ?, ';
                    if($temp[0] === 'name') {
                        $parameterArray[] = &$typename;
                    } elseif($temp[0] === 'description') {
                        $parameterArray[] = &$typedescription;
                    } elseif($temp[0] === 'typecategoryid') {
                        if($typecategoryid > 0) {
                            $parameterArray[] = &$typecategoryid;
                        }
                    } elseif($temp[0] === 'status') {
                        $parameterArray[] = &$typestatus;
                    }
                }
                $query .= " updatetimeutc = UTC_TIMESTAMP() WHERE id = ? ";
                $types .= 'i';
                $parameterArray[] = &$typeid;
                $parameterArray[0] = $types;    
                $stmt = $wpdb->dbh->prepare($query);
                call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                $stmt->execute();
                if($wpdb->dbh->errno > 0 || $stmt->errno > 0) {
                    $finalresult = 'Edit type failed';
                }
                $stmt->close();
            } else {
                $finalresult = 'Nothing is updated';
            }
            echo esc_html($finalresult);
            exit();
        }
    }
    echo "Invalid data.";
    exit();
}

function expenseszyx987_addRole() {
    global $dragon_expense_dbResult;
    $mynonce = empty($_POST['expenseszyx987_hidden_security']) ? '' : strip_tags(sanitize_text_field($_POST['expenseszyx987_hidden_security']));
    if(wp_verify_nonce($mynonce, 'expenseszyx987_addRole') !== 1) {$dragon_expense_dbResult .= 'Invalid data. ';return;}
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        $dragon_expense_dbResult .= 'Invalid user info.';
        return;
    }
    if(!expenseszyx987_userCanCreateInAdminPage()) {
        $dragon_expense_dbResult .= 'You are not authorized to create data in admin page. Please contact web admin.';
        return;
    }
    if(in_array('administrator', (array) $current_user->roles) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987_role';
        $name = sanitize_text_field($_POST['expenseszyx987_addrolename']);
        $name = expenseszyx987_stripAllBackSlashes($name);
        $description = sanitize_text_field($_POST['expenseszyx987_addroledescription']);
        $description = expenseszyx987_stripAllBackSlashes($description);
        if($name === '') {$dragon_expense_dbResult .= 'Create a new role: role name are required. Not saved. ';return;}
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $stmt = $wpdb->dbh->prepare("SELECT COUNT(*) countresult FROM $table_name WHERE name = ? ");
            $stmt->bind_param("s", $name);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            if(count($result) === 1) {
                $temp_row = $result[0];
                $temp_result = $temp_row["countresult"];
                $dbcount = $temp_result === null ? 0 : intval($temp_result);
                if($dbcount !== 0) {$dragon_expense_dbResult .= "Create a new role: role name \"" . $name . "\" already exists in the table. Not saved. ";return;}
            } else {
                $dragon_expense_dbResult .= "Create a new role: role name \"" . $name . "\" query has error. Not saved. ";return;
            }
            $query = "INSERT INTO " . $table_name . " (`name`,`description`,`createtimeutc`) VALUES (?,?,UTC_TIMESTAMP())";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 's';
            $parameterArray[] = &$name;

            $types .= 's';
            $parameterArray[] = &$description;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->insert_id;
            $stmt->close();

            if($myresult <= 0) {
                $dragon_expense_dbResult .= 'Error adding a role into table ' . $table_name . ". ";return;
            }
        } else {
            $dragon_expense_dbResult .= 'Mysqli is not supported by your system. ';return;
        }
        $dragon_expense_dbResult .= 'Success.';
    } else {
        $dragon_expense_dbResult .= 'Invalid data.';
    }
}

add_action('wp_ajax_expenseszyx987_saveRole', 'expenseszyx987_saveRole');
function expenseszyx987_saveRole() {
    check_ajax_referer('expenseszyx987_saveRole', 'expenseszyx987_hidden_security_saverole');
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        echo 'Invalid user info.';
        exit();
    }
    if(!expenseszyx987_userCanEditInAdminPage()) {
        echo 'You are not authorized to edit data in admin page. Please contact web admin.';
        exit();
    }
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        $roleid_temp = empty($_POST['id']) ? 0 : strip_tags(sanitize_text_field($_POST['id']));
        $roleid = intval($roleid_temp);

        if($roleid <= 0 || $_POST['status'] === null || $_POST['status'] === '') {echo "Invalid id.";exit();}

        $rolename_temp = $_POST['name'] === null ? '' : strip_tags(sanitize_text_field($_POST['name']));
        $rolename = expenseszyx987_stripAllBackSlashes($rolename_temp);

        $roledescription_temp = $_POST['description'] === null ? '' : strip_tags(sanitize_text_field($_POST['description']));
        $roledescription = expenseszyx987_stripAllBackSlashes($roledescription_temp);

        $rolestatus_temp = $_POST['status'] === null ? '' : strip_tags(sanitize_text_field($_POST['status']));
        $rolestatus = $rolestatus_temp === '' ? 0 : intval($rolestatus_temp);

        if($rolename === '' && $roledescription === '' && $rolestatus !== 0 && $rolestatus !== 1) {
            echo "Please enter a value.";exit();
        }
        if($rolename === '' || ($rolestatus !== 0 && $rolestatus !== 1)) {
            echo "Name and status are required.";exit();
        }
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987_role';
        $finalresult = 'Success';
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $stmt = $wpdb->dbh->prepare("SELECT COUNT(*) countresult FROM $table_name WHERE name = ? and id != ?");
            $stmt->bind_param("si", $departmentname, $departmentid);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            if(count($result) === 1) {
                $temp_row = $result[0];
                $temp_result = $temp_row["countresult"];
                $dbcount = $temp_result === null ? 0 : intval($temp_result);
                if($dbcount !== 0) {echo "Edit a role: role name \"" . esc_html($rolename) . "\" already exists in the table. Not saved.";exit();}
            } else {
                echo "Edit a role: role name \"" . esc_html($rolename) . "\" query has error. Not saved.";exit();
            }

            $stmt=null;
            $sqlColumnsArray = array();
            if($rolename !== '') {
                $sqlColumnsArray['name|s'] = $rolename;
            }
            $sqlColumnsArray['description|s'] = $roledescription;
            if($rolestatus === 0 || $rolestatus === 1) {
                $sqlColumnsArray['status|i'] = $rolestatus;
            }
            if(count($sqlColumnsArray) > 0) {
                $query = "UPDATE $table_name SET ";
                $types = '';
                $parameterArray = array('');
                foreach($sqlColumnsArray as $key => $value) {
                    $temp = explode('|', $key, 2);

                    $types .= $temp[1];
                    $query .= ' ' . $temp[0] . ' = ?, ';
                    if($temp[0] === 'name') {
                        $parameterArray[] = &$rolename;
                    } elseif($temp[0] === 'description') {
                        $parameterArray[] = &$roledescription;
                    } elseif($temp[0] === 'status') {
                        $parameterArray[] = &$rolestatus;
                    }
                }
                $query .= " updatetimeutc = UTC_TIMESTAMP() WHERE id = ? ";
                $types .= 'i';
                $parameterArray[] = &$roleid;
                $parameterArray[0] = $types;
                $stmt = $wpdb->dbh->prepare($query);
                call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                $stmt->execute();
                if($wpdb->dbh->errno > 0 || $stmt->errno > 0) {
                    $finalresult = 'Edit role failed';
                }
                $stmt->close();
            } else {
                $finalresult = 'Nothing is updated';
            }
            echo esc_html($finalresult);
            exit();
        }
    }
    echo "Invalid data.";
    exit();
}

function expenseszyx987_getAllRoles($onlyActive = false) {
    global $wpdb; global $dragon_expense_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_expenseszyx987_role';
    if($onlyActive) {
        $results = $wpdb->get_results("SELECT * FROM $table_name WHERE status = 1");
    } else {
        $results = $wpdb->get_results("SELECT * FROM $table_name");
    }
    foreach($results as $result) {
        foreach($result as $key => $value) {
            $result->$key = deslash($value);
        }
    }
    return $results;
}

function expenseszyx987_getAllWPUsers($onlyActive = false) {
    global $wpdb; global $dragon_expense_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $prefix = $wpdb->prefix;
    $table_name = $prefix . 'users';
    $table_name2 = $prefix . 'usermeta';
    $query = "SELECT u.*, concat(IFNULL(m.meta_value, ''), ' ', IFNULL(m2.meta_value, '')) 'fullname' FROM $table_name u "
             . " LEFT JOIN $table_name2 m "
             . " ON u.ID = m.user_id "
             . " AND m.meta_key = 'first_name' "
             . " LEFT JOIN $table_name2 m2 "
             . " ON u.ID = m2.user_id "
             . " AND m2.meta_key = 'last_name' order by fullname";
    if($onlyActive) {    
        $results = $wpdb->get_results($query);
    } else {
        $results = $wpdb->get_results($query);
    }
    foreach($results as $result) {
        foreach($result as $key => $value) {
            $result->$key = deslash($value);
        }
    }
    return $results;
}

function expenseszyx987_getAllUsers($onlyActive = false) {
    global $wpdb; global $dragon_expense_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = "wp_expenseszyx987_users";
    if($onlyActive) {
        $results = $wpdb->get_results("SELECT * FROM $table_name WHERE status = 1");
    } else {
        $results = $wpdb->get_results("SELECT * FROM $table_name");
    }
    foreach($results as $result) {
        foreach($result as $key => $value) {
            $result->$key = deslash($value);
        }
    }
    return $results;
}

add_action('wp_ajax_expenseszyx987_getUsertypes', 'expenseszyx987_getUsertypes');
function expenseszyx987_getUsertypes() {
    check_ajax_referer('expenseszyx987_getUsertypes', 'expenseszyx987_hidden_security_getusertypes');
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        header("Content-Type: application/json");
        echo wp_json_encode("{}");
        exit();
    }
    //check wp_expenseszyx987_users table to see if this user can read data in admin page
    if(!expenseszyx987_userCanReadInAdminPage()) {    
        header("Content-Type: application/json");
        echo wp_json_encode("{}");
        exit();
    }
    if((!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $storedprocedure_name = 'wp_expenseszyx987_getUsertypeList';

        $userid_temp = empty($_POST['userid']) ? '-1' : strip_tags(sanitize_text_field($_POST['userid']));
        $userid = intval($userid_temp);

        $mystatus = -1;

        $typeid_temp = empty($_POST['typeid']) ? '-1' : strip_tags(sanitize_text_field($_POST['typeid']));
        $typeid = intval($typeid_temp);

        $typecategoryid_temp = empty($_POST['typecategoryid']) ? '-1' : strip_tags(sanitize_text_field($_POST['typecategoryid']));
        $typecategoryid = intval($typecategoryid_temp);

        $amountperpage = empty($_POST['amountperpage']) ? '10' : strip_tags(sanitize_text_field($_POST['amountperpage']));
        $amountperpage = intval($amountperpage);
        if($amountperpage === -1) {$amountperpage = 10;};

        $pagenumber = empty($_POST['pagenumber']) ? '1' : strip_tags(sanitize_text_field($_POST['pagenumber']));
        $pagenumber = intval($pagenumber);
        $myoffset = ($pagenumber - 1) * $amountperpage;

        $mysortby = empty($_POST['sortby']) ? '' : strip_tags(sanitize_text_field($_POST['sortby']));
        $mysortby = $mysortby === '' ? 'userid' : $mysortby;

        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : strip_tags(sanitize_text_field($_POST['order']));
        $myorder = $myorder === '' ? 'asc' : $myorder;

        $searchuserlogin_temp = (empty($_POST['loginname']) || trim($_POST['loginname']) === '') ? '' : strip_tags(sanitize_text_field($_POST['loginname']));
        $searchuserlogin_temp = preg_replace('/[^a-zA-Z0-9\/()$@?!\[\]{}#%^*+|~]/', '%', $searchuserlogin_temp);
        $searchuserlogin = trim($searchuserlogin_temp) === '' ? '' : $searchuserlogin_temp;

        $searchfullname_temp = (empty($_POST['fullname']) || trim($_POST['fullname']) === '') ? '' : strip_tags(sanitize_text_field($_POST['fullname']));
        $searchfullname_temp = preg_replace('/[^a-zA-Z0-9\/()$@?!\[\]{}#%^*+|~]/', '%', $searchfullname_temp);
        $searchfullname = trim($searchfullname_temp) === '' ? '' : $searchfullname_temp;

        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $query = "CALL " . $storedprocedure_name . "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, @outvalue);";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 'i';
            $parameterArray[] = &$pagenumber;

            $types .= 'i';
            $parameterArray[] = &$amountperpage;

            $types .= 'i';
            $parameterArray[] = &$myoffset;

            $types .= 's';
            $parameterArray[] = &$mysortby;

            $types .= 's';
            $parameterArray[] = &$myorder;

            $types .= 's';
            $wpprefix = $wpdb->prefix;
            $parameterArray[] = &$wpprefix;

            $types .= 'i';
            $parameterArray[] = &$userid;

            $types .= 'i';
            $parameterArray[] = &$typeid;

            $types .= 'i';
            $parameterArray[] = &$typecategoryid;

            $types .= 's';
            $parameterArray[] = &$searchuserlogin;

            $types .= 's';
            $parameterArray[] = &$searchfullname;

            $types .= 'i'; //0: inactive, 1: active, -1: both
            $parameterArray[] = &$mystatus;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $usertypes = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            $stmt2 = $wpdb->dbh->prepare('SELECT @outvalue');
            $stmt2->execute();
            $myresult2 = $stmt2->get_result();
            $totalObjArr = $myresult2 === FALSE ? array() : $myresult2->fetch_all(MYSQLI_ASSOC);
            $stmt2->close();

            $total = "0";
            foreach($totalObjArr[0] as $key => $value) {
                if($key === '@outvalue') {
                    $total = $value == null ? "0" : $value;
                }
            }
            foreach($usertypes as $usertype) {
                foreach($usertype as $key => $value) {
                    $usertype[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["usertype"] = $usertypes;
            $result["total"] = $total;
            //error_log("at 2473, result: " . wp_json_encode($result));
            header("Content-Type: application/json");
            echo wp_json_encode($result);
            exit();
        }
    }
    header("Content-Type: application/json");
    echo wp_json_encode("{}");
    exit();
}

function expenseszyx987_addUser() {
    global $dragon_expense_dbResult;
    $mynonce = empty($_POST['expenseszyx987_hidden_security']) ? '' : strip_tags(sanitize_text_field($_POST['expenseszyx987_hidden_security']));
    if(wp_verify_nonce($mynonce, 'expenseszyx987_addUser') !== 1) {$dragon_expense_dbResult .= 'Invalid data. ';return;}
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        $dragon_expense_dbResult .= 'Invalid user info.';
        return;
    }
    if(!expenseszyx987_userCanCreateInAdminPage()) {
        $dragon_expense_dbResult .= 'You are not authorized to create data in admin page. Please contact web admin.';
        return;
    }
    if(in_array('administrator', (array) $current_user->roles) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987_users';
        $firstname = trim(sanitize_text_field($_POST['expenseszyx987_adduserfirstname']));
        $lastname = trim(sanitize_text_field($_POST['expenseszyx987_adduserlastname']));

        $userid_temp = empty($_POST['expenseszyx987_adduserid']) ? '-1' : strip_tags(sanitize_text_field($_POST['expenseszyx987_adduserid']));
        $userid = intval($userid_temp);

        $canreadinadminpage_temp = empty($_POST['expenseszyx987_addusercanreadinadminpage']) ? '0' : strip_tags(sanitize_text_field($_POST['expenseszyx987_addusercanreadinadminpage']));
        $canreadinadminpage = intval($canreadinadminpage_temp);
        if($canreadinadminpage === -1) {$canreadinadminpage = 0;}

        $cancreateinadminpage_temp = empty($_POST['expenseszyx987_addusercancreateinadminpage']) ? '0' : strip_tags(sanitize_text_field($_POST['expenseszyx987_addusercancreateinadminpage']));
        $cancreateinadminpage = intval($cancreateinadminpage_temp);
        if($cancreateinadminpage === -1) {$cancreateinadminpage = 0;}

        $caneditinadminpage_temp = empty($_POST['expenseszyx987_addusercaneditinadminpage']) ? '0' : strip_tags(sanitize_text_field($_POST['expenseszyx987_addusercaneditinadminpage']));
        $caneditinadminpage = intval($caneditinadminpage_temp);
        if($caneditinadminpage === -1) {$caneditinadminpage = 0;}

        $canactivateinadminpage_temp = empty($_POST['expenseszyx987_addusercanactivateinadminpage']) ? '0' : strip_tags(sanitize_text_field($_POST['expenseszyx987_addusercanactivateinadminpage']));
        $canactivateinadminpage = intval($canactivateinadminpage_temp);
        if($canactivateinadminpage === -1) {$canactivateinadminpage = 0;}

        $candeactivateinadminpage_temp = empty($_POST['expenseszyx987_addusercandeactivateinadminpage']) ? '0' : strip_tags(sanitize_text_field($_POST['expenseszyx987_addusercandeactivateinadminpage']));
        $candeactivateinadminpage = intval($candeactivateinadminpage_temp);
        if($candeactivateinadminpage === -1) {$candeactivateinadminpage = 0;}

        $reportto_temp = empty($_POST['expenseszyx987_adduserreportto']) ? '-1' : strip_tags(sanitize_text_field($_POST['expenseszyx987_adduserreportto']));
        $reportto = intval($reportto_temp);

        $role_temp = empty($_POST['expenseszyx987_adduserrole']) ? '-1' : strip_tags(sanitize_text_field($_POST['expenseszyx987_adduserrole']));
        $role = intval($role_temp);
        if($role <= 0) {$role = null;}

        $department_temp = empty($_POST['expenseszyx987_adduserdepartment']) ? '-1' : strip_tags(sanitize_text_field($_POST['expenseszyx987_adduserdepartment']));
        $department = intval($department_temp);
        if($department <= 0) {$department = null;}

        $status_temp = $_POST['expenseszyx987_adduserstatus'] === null ? '' : strip_tags(sanitize_text_field($_POST['expenseszyx987_adduserstatus']));
        $status = $status_temp === '' ? 0 : intval($status_temp);
        if($status === -1) {$status = 1;}

        $email = trim(sanitize_text_field($_POST['expenseszyx987_adduseremail']));
        if($email === '') {$email = null;}
        $phone = trim(sanitize_text_field($_POST['expenseszyx987_adduserphone']));
        if($phone === '') {$phone = null;}
        $address = trim(sanitize_text_field($_POST['expenseszyx987_adduseraddress']));
        if($address === '') {$address = null;}
        $address2 = trim(sanitize_text_field($_POST['expenseszyx987_adduseraddress2']));
        if($address2 === '') {$address2 = null;}
        $city = trim(sanitize_text_field($_POST['expenseszyx987_addusercity']));
        if($city === '') {$city = null;}
        $province = trim(sanitize_text_field($_POST['expenseszyx987_adduserprovince']));
        if($province === '') {$province = null;}
        $country = trim(sanitize_text_field($_POST['expenseszyx987_addusercountry']));
        if($country === '') {$country = null;}
        $zip = trim(sanitize_text_field($_POST['expenseszyx987_adduserzip']));
        if($zip === '') {$zip = null;}
        $description = trim(sanitize_text_field($_POST['expenseszyx987_adduserdescription']));
        if($description === '') {$description = null;}

        if($firstname === '' || $lastname === '' || $userid <= 0 || $reportto <= 0) {$dragon_expense_dbResult .= 'Create a new user: User first name, last name, user id, and report to id are required. Not saved. ';return;}

        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $stmt = $wpdb->dbh->prepare("SELECT COUNT(*) countresult FROM $table_name WHERE userid = ?");
            $stmt->bind_param("i", $userid);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            if(count($result) === 1) {
                $temp_row = $result[0];
                $temp_result = $temp_row["countresult"];
                $dbcount = $temp_result === null ? 0 : intval($temp_result);
                if($dbcount !== 0) {$dragon_expense_dbResult .= "Create a new user: user id " . $userid . " already exists in the table. Not saved. ";return;}
            } else {
                $dragon_expense_dbResult .= "Create a new user: user id " . $userid . " query has error. Not saved. ";return;
            }

            $query = "INSERT INTO $table_name (`userid`,`firstname`,`lastname`,`phone`,`address`,`address2`,`city`,`province`,`country`,`zip`,`reportto`,`email`,`description`,`departmentid`,`roleid`,`canreadinadminpage`,`cancreateinadminpage`,`caneditinadminpage`,`canactivateinadminpage`,`candeactivateinadminpage`,`status`,`createtimeutc`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,1,UTC_TIMESTAMP())";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 'i';
            $parameterArray[] = &$userid;

            $types .= 's';
            $parameterArray[] = &$firstname;

            $types .= 's';
            $parameterArray[] = &$lastname;

            $types .= 's';
            $parameterArray[] = &$phone;

            $types .= 's';
            $parameterArray[] = &$address;

            $types .= 's';
            $parameterArray[] = &$address2;

            $types .= 's';
            $parameterArray[] = &$city;

            $types .= 's';
            $parameterArray[] = &$province;

            $types .= 's';
            $parameterArray[] = &$country;

            $types .= 's';
            $parameterArray[] = &$zip;

            $types .= 'i';
            $parameterArray[] = &$reportto;

            $types .= 's';
            $parameterArray[] = &$email;

            $types .= 's';
            $parameterArray[] = &$description;

            $types .= 'i';
            $parameterArray[] = &$departmentid;

            $types .= 'i';
            $parameterArray[] = &$roleid;

            $types .= 'i';
            $parameterArray[] = &$canreadinadminpage;

            $types .= 'i';
            $parameterArray[] = &$cancreateinadminpage;

            $types .= 'i';
            $parameterArray[] = &$caneditinadminpage;

            $types .= 'i';
            $parameterArray[] = &$canactivateinadminpage;

            $types .= 'i';
            $parameterArray[] = &$candeactivateinadminpage;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->insert_id;
            $stmt->close();

            if($myresult <= 0) {
                $dragon_expense_dbResult .= 'Error adding a user into table ' . $table_name . ". ";return;
            }
        } else {
            $dragon_expense_dbResult .= 'Mysqli is not supported by your system. ';return;
        }
        $dragon_expense_dbResult .= 'Success.';
    } else {
        $dragon_expense_dbResult .= 'Invalid data.';
    }
}

add_action('wp_ajax_expenseszyx987_saveUser', 'expenseszyx987_saveUser');
function expenseszyx987_saveUser() {
    check_ajax_referer('expenseszyx987_saveUser', 'expenseszyx987_hidden_security_saveuser');
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        echo 'Invalid user info.';
        exit();
    }
    if(!expenseszyx987_userCanEditInAdminPage()) {
        echo 'You are not authorized to edit data in admin page. Please contact web admin.';
        exit();
    }
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        $firstname_temp = $_POST['firstname'] === null ? '' : strip_tags(sanitize_text_field($_POST['firstname']));
        $firstname = expenseszyx987_stripAllBackSlashes($firstname_temp);

        $lastname_temp = $_POST['lastname'] === null ? '' : strip_tags(sanitize_text_field($_POST['lastname']));
        $lastname = expenseszyx987_stripAllBackSlashes($lastname_temp);

        //record id
        $id_temp = empty($_POST['id']) ? 0 : strip_tags(sanitize_text_field($_POST['id']));
        $id = intval($id_temp);

        //new user id
        $userid_temp = empty($_POST['userid']) ? 0 : strip_tags(sanitize_text_field($_POST['userid']));
        $userid = intval($userid_temp);

        $reportto_temp = empty($_POST['reportto']) ? 0 : strip_tags(sanitize_text_field($_POST['reportto']));
        $reportto = intval($reportto_temp);

        $status_temp = $_POST['status'] === null ? '' : strip_tags(sanitize_text_field($_POST['status']));
        $status = $status_temp === '' ? 0 : intval($status_temp);

        if($firstname === '' || $lastname === '' || $id <= 0 || $userid <= 0 || $reportto <= 0 || ($status !== 0 && $status !== 1)) {echo "First name, last name, user id, report to id, and status are required.";exit();}

        $canreadinadminpage_temp = empty($_POST['canreadinadminpage']) ? '-1' : strip_tags(sanitize_text_field($_POST['canreadinadminpage']));
        $canreadinadminpage = intval($canreadinadminpage_temp);
        if($canreadinadminpage === -1) {$canreadinadminpage=0;}

        $cancreateinadminpage_temp = empty($_POST['cancreateinadminpage']) ? '-1' : strip_tags(sanitize_text_field($_POST['cancreateinadminpage']));
        $cancreateinadminpage = intval($cancreateinadminpage_temp);
        if($cancreateinadminpage === -1) {$cancreateinadminpage=0;}

        $caneditinadminpage_temp = empty($_POST['caneditinadminpage']) ? '-1' : strip_tags(sanitize_text_field($_POST['caneditinadminpage']));
        $caneditinadminpage = intval($caneditinadminpage_temp);
        if($caneditinadminpage === -1) {$caneditinadminpage=0;}

        $canactivateinadminpage_temp = empty($_POST['canactivateinadminpage']) ? '-1' : strip_tags(sanitize_text_field($_POST['canactivateinadminpage']));
        $canactivateinadminpage = intval($canactivateinadminpage_temp);
        if($canactivateinadminpage === -1) {$canactivateinadminpage=0;}

        $candeactivateinadminpage_temp = empty($_POST['candeactivateinadminpage']) ? '-1' : strip_tags(sanitize_text_field($_POST['candeactivateinadminpage']));
        $candeactivateinadminpage = intval($candeactivateinadminpage_temp);
        if($candeactivateinadminpage === -1) {$candeactivateinadminpage=0;}

        $roleid_temp = empty($_POST['roleid']) ? 0 : strip_tags(sanitize_text_field($_POST['roleid']));
        $roleid = intval($roleid_temp);

        $departmentid_temp = empty($_POST['departmentid']) ? 0 : strip_tags(sanitize_text_field($_POST['departmentid']));
        $departmentid = intval($departmentid_temp);

        $email_temp = $_POST['email'] === null ? '' : strip_tags(sanitize_text_field($_POST['email']));
        $email = expenseszyx987_stripAllBackSlashes($email_temp);

        $phone_temp = $_POST['phone'] === null ? '' : strip_tags(sanitize_text_field($_POST['phone']));
        $phone = expenseszyx987_stripAllBackSlashes($phone_temp);

        $address_temp = $_POST['address'] === null ? '' : strip_tags(sanitize_text_field($_POST['address']));
        $address = expenseszyx987_stripAllBackSlashes($address_temp);

        $address2_temp = $_POST['address2'] === null ? '' : strip_tags(sanitize_text_field($_POST['address2']));
        $address2 = expenseszyx987_stripAllBackSlashes($address2_temp);

        $city_temp = $_POST['city'] === null ? '' : strip_tags(sanitize_text_field($_POST['city']));
        $city = expenseszyx987_stripAllBackSlashes($city_temp);

        $province_temp = $_POST['province'] === null ? '' : strip_tags(sanitize_text_field($_POST['province']));
        $province = expenseszyx987_stripAllBackSlashes($province_temp);

        $country_temp = $_POST['country'] === null ? '' : strip_tags(sanitize_text_field($_POST['country']));
        $country = expenseszyx987_stripAllBackSlashes($country_temp);

        $zip_temp = $_POST['zip'] === null ? '' : strip_tags(sanitize_text_field($_POST['zip']));
        $zip = expenseszyx987_stripAllBackSlashes($zip_temp);

        $description_temp = $_POST['description'] === null ? '' : strip_tags(sanitize_text_field($_POST['description']));
        $description = expenseszyx987_stripAllBackSlashes($description_temp);

        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987_users';
        $finalresult = 'Success';
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $stmt = $wpdb->dbh->prepare("SELECT COUNT(*) countresult FROM $table_name WHERE id = ? OR userid = ?");
            $stmt->bind_param("ii", $id, $userid);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            if(count($result) === 1) {
                $temp_row = $result[0];
                $temp_result = $temp_row["countresult"];
                $dbcount = $temp_result === null ? 0 : intval($temp_result);
                if($dbcount !== 1) {echo "Edit a user: id $id or user id $userid record(s) exist(s) $dbcount time(s) in the $table_name table. Not saved.";exit();}
            } else {
                echo "Edit a user: id " . intval($id) . ", user id " . intval($userid) . " query has error. Not saved.";exit();
            }

            $stmt=null;
            $sqlColumnsArray = array();
            if($firstname !== '') {
                $sqlColumnsArray['firstname|s'] = $firstname;
            }
            if($lastname !== '') {
                $sqlColumnsArray['lastname|s'] = $lastname;
            }
            if($userid > 0) {
                $sqlColumnsArray['userid|i'] = $userid;
            }
            if($reportto > 0) {
                $sqlColumnsArray['reportto|i'] = $reportto;
            }
            if($canreadinadminpage === 0 || $canreadinadminpage === 1) {
                $sqlColumnsArray['canreadinadminpage|i'] = $canreadinadminpage;
            }
            if($cancreateinadminpage === 0 || $cancreateinadminpage === 1) {
                $sqlColumnsArray['cancreateinadminpage|i'] = $cancreateinadminpage;
            }
            if($caneditinadminpage === 0 || $caneditinadminpage === 1) {
                $sqlColumnsArray['caneditinadminpage|i'] = $caneditinadminpage;
            }
            if($canactivateinadminpage === 0 || $canactivateinadminpage === 1) {
                $sqlColumnsArray['canactivateinadminpage|i'] = $canactivateinadminpage;
            }
            if($candeactivateinadminpage === 0 || $candeactivateinadminpage === 1) {
                $sqlColumnsArray['candeactivateinadminpage|i'] = $candeactivateinadminpage;
            }
            $sqlColumnsArray['roleid|i'] = $roleid;
            $sqlColumnsArray['departmentid|i'] = $departmentid;
            $sqlColumnsArray['email|s'] = $email;
            $sqlColumnsArray['phone|s'] = $phone;
            $sqlColumnsArray['address|s'] = $address;
            $sqlColumnsArray['address2|s'] = $address2;
            $sqlColumnsArray['city|s'] = $city;
            $sqlColumnsArray['province|s'] = $province;
            $sqlColumnsArray['country|s'] = $country;
            $sqlColumnsArray['zip|s'] = $zip;
            $sqlColumnsArray['description|s'] = $description;
            if($status === 0 || $status === 1) {
                $sqlColumnsArray['status|i'] = $status;
            }

            if(count($sqlColumnsArray) > 0) {
                $query = "UPDATE $table_name SET ";
                $types = '';
                $parameterArray = array('');    
                foreach($sqlColumnsArray as $key => $value) {
                    $temp = explode('|', $key, 2);
                    if($temp[0] === 'roleid' && $sqlColumnsArray['roleid|i'] <= 0) {
                        $query .= ' ' . $temp[0] . ' = null, ';
                    } elseif($temp[0] === 'departmentid' && $sqlColumnsArray['departmentid|i'] <= 0) {
                        $query .= ' ' . $temp[0] . ' = null, ';
                    } else {
                        $types .= $temp[1];
                        $query .= ' ' . $temp[0] . ' = ?, ';
                    }

                    if($temp[0] === 'roleid') {
                        if($sqlColumnsArray['roleid|i'] > 0) {
                            $parameterArray[] = &$sqlColumnsArray['roleid|i'];
                        }
                    } elseif($temp[0] === 'departmentid') {
                        if($sqlColumnsArray['departmentid|i'] > 0) {
                            $parameterArray[] = &$sqlColumnsArray['departmentid|i'];
                        }
                    } else {
                        $parameterArray[] = &$sqlColumnsArray[$key];
                    }
                }
                $query .= " updatetimeutc = UTC_TIMESTAMP() WHERE userid = ? ";
                $types .= 'i';
                $parameterArray[] = &$userid;
                $parameterArray[0] = $types;
                $stmt = $wpdb->dbh->prepare($query);
                call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                $stmt->execute();
                if($wpdb->dbh->errno > 0 || $stmt->errno > 0) {
                    $finalresult = 'Edit user failed';
                }
                $stmt->close();
            } else {
                $finalresult = 'Nothing is updated';
            }
            echo esc_html($finalresult);
            exit();
        }
    }
    echo "Invalid data.";
    exit();
}

add_action('wp_ajax_expenseszyx987_getUsers', 'expenseszyx987_getUsers');
function expenseszyx987_getUsers() {
    check_ajax_referer('expenseszyx987_getUsers', 'expenseszyx987_hidden_security_getusers');
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        header("Content-Type: application/json");
        echo wp_json_encode("{}");
        exit();
    }
    if(!expenseszyx987_userCanReadInAdminPage()) {
        header("Content-Type: application/json");
        echo wp_json_encode("{}");
        exit();
    }
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $storedprocedure_name = 'wp_expenseszyx987_getUserList';

        $userid = (!isset($_POST['userid'])) ? '-1' : strip_tags(sanitize_text_field($_POST['userid']));
        $userid = intval($userid);

        $userstatus = (!isset($_POST['userstatus'])) ? '-1' : strip_tags(sanitize_text_field($_POST['userstatus']));
        $userstatus = intval($userstatus);

        $amountperpage = empty($_POST['amountperpage']) ? '10' : strip_tags(sanitize_text_field($_POST['amountperpage']));
        $amountperpage = intval($amountperpage);
        if($amountperpage === -1) {$amountperpage = 10;}

        $pagenumber = empty($_POST['pagenumber']) ? '1' : strip_tags(sanitize_text_field($_POST['pagenumber']));
        $pagenumber = intval($pagenumber);

        $myoffset = ($pagenumber - 1) * $amountperpage;

        $mysortby = empty($_POST['sortby']) ? '' : strip_tags(sanitize_text_field($_POST['sortby']));
        $mysortby = $mysortby === '' ? 'id' : $mysortby;

        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : strip_tags(sanitize_text_field($_POST['order']));
        $myorder = $myorder === '' ? 'asc' : $myorder;

        $userfullname = empty($_POST['userfullname']) ? '' : strip_tags(sanitize_text_field($_POST['userfullname']));
        $email = empty($_POST['email']) ? '' : strip_tags(sanitize_text_field($_POST['email']));

        $reportto = (!isset($_POST['reportto'])) ? '-1' : strip_tags(sanitize_text_field($_POST['reportto']));
        $reportto = intval($reportto);

        $canreadinadminpage = (!isset($_POST['canreadinadminpage'])) ? '-1' : strip_tags(sanitize_text_field($_POST['canreadinadminpage']));
        $canreadinadminpage = intval($canreadinadminpage);
        if($canreadinadminpage !== 0 && $canreadinadminpage !== 1 && $canreadinadminpage !== -1) {$canreadinadminpage = -1;}

        $cancreateinadminpage = (!isset($_POST['cancreateinadminpage'])) ? '-1' : strip_tags(sanitize_text_field($_POST['cancreateinadminpage']));
        $cancreateinadminpage = intval($cancreateinadminpage);
        if($cancreateinadminpage !== 0 && $cancreateinadminpage !== 1 && $cancreateinadminpage !== -1) {$cancreateinadminpage = 0;}

        $caneditinadminpage = (!isset($_POST['caneditinadminpage'])) ? '-1' : strip_tags(sanitize_text_field($_POST['caneditinadminpage']));
        $caneditinadminpage = intval($caneditinadminpage);
        if($caneditinadminpage !== 0 && $caneditinadminpage !== 1 && $caneditinadminpage !== -1) {$caneditinadminpage = 0;}

        $canactivateinadminpage = (!isset($_POST['canactivateinadminpage'])) ? '-1' : strip_tags(sanitize_text_field($_POST['canactivateinadminpage']));
        $canactivateinadminpage = intval($canactivateinadminpage);
        if($canactivateinadminpage !== 0 && $canactivateinadminpage !== 1 && $canactivateinadminpage !== -1) {$canactivateinadminpage = 0;}

        $candeactivateinadminpage = (!isset($_POST['candeactivateinadminpage'])) ? '-1' : strip_tags(sanitize_text_field($_POST['candeactivateinadminpage']));
        $candeactivateinadminpage = intval($candeactivateinadminpage);
        if($candeactivateinadminpage !== 0 && $candeactivateinadminpage !== 1 && $candeactivateinadminpage !== -1) {$candeactivateinadminpage = 0;}

        $roleid = (!isset($_POST['roleid'])) ? '-1' : strip_tags(sanitize_text_field($_POST['roleid']));
        $roleid = intval($roleid);

        $departmentid = (!isset($_POST['departmentid'])) ? '-1' : strip_tags(sanitize_text_field($_POST['departmentid']));
        $departmentid = intval($departmentid);

        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $query = "CALL " . $storedprocedure_name . "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, @outvalue );";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 'i';
            $parameterArray[] = &$pagenumber;

            $types .= 'i';
            $parameterArray[] = &$amountperpage;

            $types .= 'i';
            $parameterArray[] = &$myoffset;

            $types .= 's';
            $parameterArray[] = &$mysortby;

            $types .= 's';
            $parameterArray[] = &$myorder;

            $types .= 'i';
            $parameterArray[] = &$userid;

            $types .= 's';
            $parameterArray[] = &$userfullname;

            $types .= 's';
            $parameterArray[] = &$email;

            $types .= 'i';
            $parameterArray[] = &$reportto;

            $types .= 'i';
            $parameterArray[] = &$canreadinadminpage;

            $types .= 'i';
            $parameterArray[] = &$cancreateinadminpage;

            $types .= 'i';
            $parameterArray[] = &$caneditinadminpage;

            $types .= 'i';
            $parameterArray[] = &$canactivateinadminpage;

            $types .= 'i';
            $parameterArray[] = &$candeactivateinadminpage;

            $types .= 'i';
            $parameterArray[] = &$roleid;

            $types .= 'i';
            $parameterArray[] = &$departmentid;

            $types .= 'i'; //0: inactive, 1: active, -1: both
            $parameterArray[] = &$userstatus;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $users = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            $stmt2 = $wpdb->dbh->prepare('SELECT @outvalue');
            $stmt2->execute();
            $myresult2 = $stmt2->get_result();
            $totalObjArr = $myresult2 === FALSE ? array() : $myresult2->fetch_all(MYSQLI_ASSOC);
            $stmt2->close();

            $total = "0";
            foreach ($totalObjArr[0] as $key => $value) {
                if($key === '@outvalue') {
                    $total = $value == null ? "0" : $value;
                }
            }
            foreach ($users as $user) {
                foreach ($user as $key => $value) {
                    $user[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["user"] = $users;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo wp_json_encode($result);
            exit();
        }
    }
    header("Content-Type: application/json");
    echo wp_json_encode("{}");
    exit();
}

function expenseszyx987_addDepartment() {
    global $dragon_expense_dbResult;
    $mynonce = empty($_POST['expenseszyx987_hidden_security']) ? '' : strip_tags(sanitize_text_field($_POST['expenseszyx987_hidden_security']));
    if(wp_verify_nonce($mynonce, 'expenseszyx987_addDepartment') !== 1) {$dragon_expense_dbResult .= 'Invalid data. ';return;}
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        $dragon_expense_dbResult .= 'Invalid user info.';
        return;
    }
    if(!expenseszyx987_userCanCreateInAdminPage()) {
        $dragon_expense_dbResult .= 'You are not authorized to create data in admin page. Please contact web admin.';
        return;
    }
    if(in_array('administrator', (array) $current_user->roles) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987_department';
        $name = trim(sanitize_text_field($_POST['expenseszyx987_adddepartmentname']));
        $description = trim(sanitize_text_field($_POST['expenseszyx987_adddepartmentdescription']));

        if($name === '') {$dragon_expense_dbResult .= 'Create a new department: Department name is required. Not saved. ';return;}

        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $stmt = $wpdb->dbh->prepare("SELECT COUNT(*) countresult FROM $table_name WHERE name = ?");
            $stmt->bind_param("s", $name);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            if(count($result) === 1) {
                $temp_row = $result[0];
                $temp_result = $temp_row["countresult"];
                $dbcount = $temp_result === null ? 0 : intval($temp_result);
                if($dbcount !== 0) {$dragon_expense_dbResult .= "Create a new department: department name \"" . $name . "\" already exists in the table. Not saved. ";return;}
            } else {
                $dragon_expense_dbResult .= "Create a new department: department name \"" . $name . "\" query has error. Not saved. ";return;
            }

            $query = "INSERT INTO " . $table_name . " (`name`,`description`,`createtimeutc`) VALUES (?,?,UTC_TIMESTAMP())";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 's';
            $parameterArray[] = &$name;

            $types .= 's';
            $parameterArray[] = &$description;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->insert_id;
            $stmt->close();

            if($myresult <= 0) {
                $dragon_expense_dbResult .= 'Error adding a department into table ' . $table_name . ". ";return;
            }
        } else {
            $dragon_expense_dbResult .= 'Mysqli is not supported by your system. ';return;
        }
        $dragon_expense_dbResult .= 'Success.';
    } else {
        $dragon_expense_dbResult .= 'Invalid data.';
    }
}

function expenseszyx987_getAllSettings($onlyActive = false) {
    global $wpdb; global $dragon_expense_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_expenseszyx987_constant';
    if($onlyActive) {
        $results = $wpdb->get_results("SELECT * from $table_name WHERE status = 1 order by name");
    } else {
        $results = $wpdb->get_results("SELECT * from $table_name order by name");
    }
    foreach($results as $result) {
        foreach($result as $key => $value) {
            $result->$key = deslash($value);
        }
    }
    return $results;
}

function expenseszyx987_getAllDepartments($onlyActive = false) {
    global $wpdb; global $dragon_expense_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_expenseszyx987_department';
    if($onlyActive) {
        $results = $wpdb->get_results("SELECT * from $table_name WHERE status = 1 order by name");
    } else {
        $results = $wpdb->get_results("SELECT * from $table_name order by name");
    }
    foreach($results as $result) {
        foreach($result as $key => $value) {
            $result->$key = deslash($value);
        }
    }
    return $results;
}

function expenseszyx987_addCustomertype() {
    global $dragon_expense_dbResult;
    $mynonce = empty($_POST['expenseszyx987_hidden_security']) ? '' : strip_tags(sanitize_text_field($_POST['expenseszyx987_hidden_security']));
    if(wp_verify_nonce($mynonce, 'expenseszyx987_addCustomertype') !== 1) {$dragon_expense_dbResult .= 'Invalid data. ';return;}
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        $dragon_expense_dbResult .= 'Invalid user info.';
        return;
    }
    if(!expenseszyx987_userCanCreateInAdminPage()) {
        $dragon_expense_dbResult .= 'You are not authorized to create data in admin page. Please contact web admin.';
        return;
    }
    if(in_array('administrator', (array) $current_user->roles) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987_customertype';
        $name = trim(sanitize_text_field($_POST['expenseszyx987_addcustomertypename']));
        $description = trim(sanitize_text_field($_POST['expenseszyx987_addcustomertypedescription']));

        if($name === '') {$dragon_expense_dbResult .= 'Create a new customer type: Customer type name is required. Not saved. ';return;}

        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $stmt = $wpdb->dbh->prepare("SELECT COUNT(*) countresult FROM $table_name WHERE name = ?");
            $stmt->bind_param("s", $name);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            if(count($result) === 1) {
                $temp_row = $result[0];
                $temp_result = $temp_row["countresult"];
                $dbcount = $temp_result === null ? 0 : intval($temp_result);
                if($dbcount !== 0) {$dragon_expense_dbResult .= "Create a new customer type: customer type name \"" . $name . "\" already exists in the table. Not saved. ";return;}
            } else {
                $dragon_expense_dbResult .= "Create a new customer type: customer type name \"" . $name . "\" query has error. Not saved. ";return;
            }

            $query = "INSERT INTO " . $table_name . " (`name`,`description`,`createtimeutc`) VALUES (?,?,UTC_TIMESTAMP())";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 's';
            $parameterArray[] = &$name;

            $types .= 's';
            $parameterArray[] = &$description;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->insert_id;
            $stmt->close();

            if($myresult <= 0) {
                $dragon_expense_dbResult .= 'Error adding a customer type into table ' . $table_name . ". ";return;
            }
        } else {
            $dragon_expense_dbResult .= 'Mysqli is not supported by your system. ';return;
        }
        $dragon_expense_dbResult .= 'Success.';
    } else {
        $dragon_expense_dbResult .= 'Invalid data.';
    }
}

function expenseszyx987_getAllCustomertypes($onlyActive = false) {
    global $wpdb; global $dragon_expense_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_expenseszyx987_customertype';
    if($onlyActive) {
        $results = $wpdb->get_results("SELECT * from $table_name WHERE status = 1 order by name");
    } else {
        $results = $wpdb->get_results("SELECT * from $table_name order by name");
    }
    foreach($results as $result) {
        foreach($result as $key => $value) {
            $result->$key = deslash($value);
        }
    }
    return $results;
}

function expenseszyx987_addCustomer() {
    global $dragon_expense_dbResult;
    $mynonce = empty($_POST['expenseszyx987_hidden_security']) ? '' : strip_tags(sanitize_text_field($_POST['expenseszyx987_hidden_security']));
    if(wp_verify_nonce($mynonce, 'expenseszyx987_addCustomer') !== 1) {$dragon_expense_dbResult .= 'Invalid data. ';return;}
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        $dragon_expense_dbResult .= 'Invalid user info.';
        return;
    }
    if(!expenseszyx987_userCanCreateInAdminPage()) {
        $dragon_expense_dbResult .= 'You are not authorized to create data in admin page. Please contact web admin.';
        return;
    }
    if(in_array('administrator', (array) $current_user->roles) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987_customer';
        $name = trim(sanitize_text_field($_POST['expenseszyx987_addcustomername']));
        $description = trim(sanitize_text_field($_POST['expenseszyx987_addcustomerdescription']));
        $customertypeid = trim(sanitize_text_field($_POST['expenseszyx987_addcustomercustomertype']));
        $customertypeid = intval($customertypeid);
        if($customertypeid === -1) {
            $customertypeid = null;
        }
        if($name === '') {$dragon_expense_dbResult .= 'Create a new customer: Customer name is required. Not saved. ';return;}

        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $stmt = $wpdb->dbh->prepare("SELECT COUNT(*) countresult FROM $table_name WHERE name = ?");
            $stmt->bind_param("s", $name);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            if(count($result) === 1) {
                $temp_row = $result[0];
                $temp_result = $temp_row["countresult"];
                $dbcount = $temp_result === null ? 0 : intval($temp_result);
                if($dbcount !== 0) {$dragon_expense_dbResult .= "Create a new customer: customer name \"" . $name . "\" already exists in the table. Not saved. ";return;}
            } else {
                $dragon_expense_dbResult .= "Create a new customer: customer name \"" . $name . "\" query has error. Not saved. ";return;
            }

            $query = "INSERT INTO " . $table_name . " (`name`,`description`,`customertypeid`,`createtimeutc`) VALUES (?,?,?,UTC_TIMESTAMP())";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 's';
            $parameterArray[] = &$name;

            $types .= 's';
            $parameterArray[] = &$description;

            $types .= 'i';
            $parameterArray[] = &$customertypeid;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->insert_id;
            $stmt->close();

            if($myresult <= 0) {
                $dragon_expense_dbResult .= 'Error adding a customer into table ' . $table_name . ". ";return;
            }
        } else {
            $dragon_expense_dbResult .= 'Mysqli is not supported by your system. ';return;
        }
        $dragon_expense_dbResult .= 'Success.';
    } else {
        $dragon_expense_dbResult .= 'Invalid data.';
    }
}

function expenseszyx987_getAllCustomers($onlyActive = false) {
    global $wpdb; global $dragon_expense_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_expenseszyx987_customer';
    if($onlyActive) {
        $results = $wpdb->get_results("SELECT * from $table_name WHERE status = 1 order by name");
    } else {
        $results = $wpdb->get_results("SELECT * from $table_name order by name");
    }
    foreach($results as $result) {
        foreach($result as $key => $value) {
            $result->$key = deslash($value);
        }
    }
    return $results;
}

function expenseszyx987_addRecurringpaymentfrequency() {
    global $dragon_expense_dbResult;
    $mynonce = empty($_POST['expenseszyx987_hidden_security']) ? '' : strip_tags(sanitize_text_field($_POST['expenseszyx987_hidden_security']));
    if(wp_verify_nonce($mynonce, 'expenseszyx987_addRecurringpaymentfrequency') !== 1) {$dragon_expense_dbResult .= 'Invalid data. ';return;}
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        $dragon_expense_dbResult .= 'Invalid user info.';
        return;
    }
    if(!expenseszyx987_userCanCreateInAdminPage()) {
        $dragon_expense_dbResult .= 'You are not authorized to create data in admin page. Please contact web admin.';
        return;
    }
    if(in_array('administrator', (array) $current_user->roles) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987_recurringpaymentfrequency';
        $name = trim(sanitize_text_field($_POST['expenseszyx987_addrecurringpaymentfrequencyname']));
        $description = trim(sanitize_text_field($_POST['expenseszyx987_addrecurringpaymentfrequencydescription']));

        if($name === '') {$dragon_expense_dbResult .= 'Create a new recurring payment frequency: recurring payment frequency name is required. Not saved. ';return;}

        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $stmt = $wpdb->dbh->prepare("SELECT COUNT(*) countresult FROM $table_name WHERE name = ?");
            $stmt->bind_param("s", $name);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            if(count($result) === 1) {
                $temp_row = $result[0];
                $temp_result = $temp_row["countresult"];
                $dbcount = $temp_result === null ? 0 : intval($temp_result);
                if($dbcount !== 0) {$dragon_expense_dbResult .= "Create a new recurring payment frequency: recurring payment frequency name \"" . $name . "\" already exists in the table. Not saved. ";return;}
            } else {
                $dragon_expense_dbResult .= "Create a new recurring payment frequency: recurring payment frequency name \"" . $name . "\" query has error. Not saved. ";return;
            }

            $query = "INSERT INTO " . $table_name . " (`name`,`description`,`createtimeutc`) VALUES (?,?,UTC_TIMESTAMP())";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 's';
            $parameterArray[] = &$name;

            $types .= 's';
            $parameterArray[] = &$description;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->insert_id;
            $stmt->close();

            if($myresult <= 0) {
                $dragon_expense_dbResult .= 'Error adding a recurring payment frequency into table ' . $table_name . ". ";return;
            }
        } else {
            $dragon_expense_dbResult .= 'Mysqli is not supported by your system. ';return;
        }
        $dragon_expense_dbResult .= 'Success.';
    } else {
        $dragon_expense_dbResult .= 'Invalid data.';
    }
}

function expenseszyx987_getAllRecurringpaymentfrequencies($onlyActive = false) {
    global $wpdb; global $dragon_expense_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_expenseszyx987_recurringpaymentfrequency';
    if($onlyActive) {
        $results = $wpdb->get_results("SELECT * from $table_name WHERE status = 1 order by name");
    } else {
        $results = $wpdb->get_results("SELECT * from $table_name order by name");
    }
    foreach($results as $result) {
        foreach($result as $key => $value) {
            $result->$key = deslash($value);
        }
    }
    return $results;
}

function expenseszyx987_addTax() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['expenseszyx987_hidden_security']) ? '' : strip_tags(sanitize_text_field($_POST['expenseszyx987_hidden_security']));
    if(wp_verify_nonce($mynonce, 'expenseszyx987_addTax') !== 1) {$dragon_ecommerce_dbResult .= 'Invalid data. ';return;}
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        $dragon_ecommerce_dbResult .= 'Invalid user info.';
        return;
    }
    if(in_array('administrator', (array) $current_user->roles) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987_tax';
        $name = trim(sanitize_text_field($_POST['expenseszyx987_addtaxname']));
        $name = stripslashes(trim($name));
        $rate_string = trim(sanitize_text_field($_POST['expenseszyx987_addtaxrate']));
        $rate_string = stripslashes(trim($rate_string));
        $rate = floatval($rate_string);
        $description = trim(sanitize_text_field($_POST['expenseszyx987_addtaxdescription']));
        $description = stripslashes(trim($description));
        if($name === '' || $rate_string === '') {$dragon_ecommerce_dbResult .= 'Create a new rate: Tax name and rate are required. Not saved. ';return;}
        if($rate < 0) {$dragon_ecommerce_dbResult .= "Create a new rate: rate is less than 0. Not saved. ";return;}
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }

            $stmt = $wpdb->dbh->prepare("SELECT COUNT(*) countresult FROM $table_name WHERE name = ?");
            $stmt->bind_param("s", $name);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            if(count($result) === 1) {
                $temp_row = $result[0];
                $temp_result = $temp_row["countresult"];
                $dbcount = $temp_result === null ? 0 : intval($temp_result);
                if($dbcount > 0) {$dragon_ecommerce_dbResult .= "Create a new rate: rate name: \"" . $name . "\" already exist(s) in the rate table. Not saved. ";return;}
            } else {
                $dragon_ecommerce_dbResult .= "Create a new rate: rate name \"" . $name . "\" query has error. Not saved. ";return;
            }
            $query = "INSERT INTO " . $table_name . " (`name`,`rate`,`description`,`createtimeutc`) VALUES (?,?,?,UTC_TIMESTAMP())";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 's';
            $parameterArray[] = &$name;

            $types .= 'd';
            $parameterArray[] = &$rate;

            $types .= 's';
            $parameterArray[] = &$description;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->insert_id;
            $stmt->close();
            if($myresult <= 0) {
                $dragon_ecommerce_dbResult .= 'Error adding a rate into table ' . $table_name . ". ";return;
            }
        } else {
            $dragon_ecommerce_dbResult .= 'Mysqli is not supported by your system. ';return;
        }
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }
}

function expenseszyx987_getAllTaxes($onlyActive = false) {
    global $wpdb; global $dragon_ecommerce_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_expenseszyx987_tax';
    if($onlyActive) {
        $results = $wpdb->get_results("SELECT * from $table_name WHERE status = 1 order by name");
    } else {
        $results = $wpdb->get_results("SELECT * from $table_name order by name");
    }
    foreach($results as $result) {
        foreach($result as $key => $value) {
            $result->$key = deslash($value);
        }
    }
    return $results;
}

add_action('wp_ajax_expenseszyx987_saveTax', 'expenseszyx987_saveTax');
function expenseszyx987_saveTax() {
    check_ajax_referer('expenseszyx987_saveTax', 'expenseszyx987_hidden_security_savetax');
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        echo 'Invalid user info.';
        exit();
    }
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        $taxid_temp = empty($_POST['id']) ? 0 : strip_tags(sanitize_text_field($_POST['id']));
        $taxid = intval($taxid_temp);

        if($taxid <= 0 || $_POST['status'] === null || $_POST['status'] === '') {echo "Invalid id.";exit();}

        $taxname_temp = $_POST['name'] === null ? '' : strip_tags(sanitize_text_field($_POST['name']));
        $taxname = stripslashes(trim($taxname_temp));

        $taxrate_temp = $_POST['rate'] === null ? '' : strip_tags(sanitize_text_field($_POST['rate']));
        $taxrate_temp = stripslashes(trim($taxrate_temp));
        $taxrate = floatval($taxrate_temp);

        $taxdescription_temp = $_POST['description'] === null ? '' : strip_tags(sanitize_text_field($_POST['description']));
        $taxdescription = stripslashes(trim($taxdescription_temp));

        $taxstatus_temp = $_POST['status'] === null ? '' : strip_tags(sanitize_text_field($_POST['status']));
        $taxstatus = $taxstatus_temp === '' ? 0 : intval($taxstatus_temp);

        if(($taxrate_temp === null || $taxrate_temp === '')
            && $taxname === '' && $taxdescription === '' && $taxstatus === -1) {
            echo "Please enter a value.";exit();
        }
        if(($taxrate_temp === null || $taxrate_temp === '')
            || $taxname === '' || $taxstatus === -1) {
            echo "Name, rate, and status are required.";exit();
        }
        if($taxrate < 0) {
            echo "Rate should be no less than 0.";exit();
        }
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987_tax';
        $finalresult = 'Success';
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }

            $stmt = $wpdb->dbh->prepare("SELECT COUNT(*) countresult FROM $table_name WHERE name = ? AND id != ?");
            $stmt->bind_param("si", $taxname, $taxid);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            if(count($result) === 1) {
                $temp_row = $result[0];
                $temp_result = $temp_row["countresult"];
                $dbcount = $temp_result === null ? 0 : intval($temp_result);
                if($dbcount > 0) {$finalresult = "Edit a tax: tax name: \"" . esc_html($taxname) . "\" already exist(s) in the tax table. Not saved. ";echo esc_html($finalresult);exit();}
            } else {
                $finalresult = "Edit a tax: tax name \"" . esc_html($taxname) . "\" query has error. Not saved. ";echo $finalresult;exit();
            }
            $stmt=null;
            $sqlColumnsArray = array();
            if($taxname !== '') {
                $sqlColumnsArray['name|s'] = $taxname;
            }
            $sqlColumnsArray['description|s'] = $taxdescription;
            if($taxrate !== null && $taxrate >= 0) {
                $sqlColumnsArray['rate|d'] = $taxrate;
            }
            if($taxstatus === 0 || $taxstatus === 1) {
                $sqlColumnsArray['status|i'] = $taxstatus;
            }
            if(count($sqlColumnsArray) > 0) {
                $query = "UPDATE $table_name SET ";
                $types = '';
                $parameterArray = array('');
                foreach($sqlColumnsArray as $key => $value) {
                    $temp = explode('|', $key, 2);
                    $types .= $temp[1];
                    $query .= ' ' . $temp[0] . ' = ?, ';
                    if($temp[0] === 'name') {
                        $parameterArray[] = &$taxname;
                    } elseif($temp[0] === 'description') {
                        $parameterArray[] = &$taxdescription;
                    } elseif($temp[0] === 'rate') {
                        $parameterArray[] = &$taxrate;
                    } elseif($temp[0] === 'status') {
                        $parameterArray[] = &$taxstatus;
                    }
                }
                $query .= " updatetimeutc = UTC_TIMESTAMP() WHERE id = ? ";
                $types .= 'i';
                $parameterArray[] = &$taxid;
                $parameterArray[0] = $types;
                $stmt = $wpdb->dbh->prepare($query);
                call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                $stmt->execute();
                if($wpdb->dbh->errno > 0 || $stmt->errno > 0) {
                    $finalresult = 'Edit tax failed';
                }
                $stmt->close();
            } else {
                $finalresult = 'Nothing is updated';
            }
            echo esc_html($finalresult);
            exit();
        }
    }
    echo "Invalid data.";
    exit();
}

function expenseszyx987_addCurrency() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['expenseszyx987_hidden_security']) ? '' : strip_tags(sanitize_text_field($_POST['expenseszyx987_hidden_security']));
    if(wp_verify_nonce($mynonce, 'expenseszyx987_addCurrency') !== 1) {$dragon_ecommerce_dbResult .= 'Invalid data. ';return;}
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        $dragon_ecommerce_dbResult .= 'Invalid user info.';
        return;
    }
    if(in_array('administrator', (array) $current_user->roles) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987_currency';
        $name = trim(sanitize_text_field($_POST['expenseszyx987_addcurrencyname']));
        $name = stripslashes(trim($name));
        $sign = trim(sanitize_text_field($_POST['expenseszyx987_addcurrencysign']));
        $sign = stripslashes(trim($sign));
        $isocurrencycode = trim(sanitize_text_field($_POST['expenseszyx987_addcurrencyisocurrencycode']));
        $isocurrencycode = stripslashes(trim($isocurrencycode));
        $description = trim(sanitize_text_field($_POST['expenseszyx987_addcurrencydescription']));
        $description = stripslashes(trim($description));
        if($name === '' || $sign === '' || $isocurrencycode === '') {$dragon_ecommerce_dbResult .= 'Create a new currency: Currency name, sign and ISO currency code are required. Not saved. ';return;}
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            //There could be the same sign for different currency
            $stmt = $wpdb->dbh->prepare("SELECT COUNT(*) countresult FROM $table_name WHERE name = ? or isocurrencycode = ?");
            $stmt->bind_param("ss", $name, $isocurrencycode);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            if(count($result) === 1) {
                $temp_row = $result[0];
                $temp_result = $temp_row["countresult"];
                $dbcount = $temp_result === null ? 0 : intval($temp_result);
                if($dbcount > 0) {$dragon_ecommerce_dbResult .= "Create a new currency: currency name: \"" . $name . "\" and/or isocurrencycode: \"" . $isocurrencycode . "\" already exist(s) in the currency table. Not saved. ";return;}
            } else {
                $dragon_ecommerce_dbResult .= "Create a new currency: currency name \"" . $name . "\" query has error. Not saved. ";return;
            }
            $query = "INSERT INTO " . $table_name . " (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) VALUES (?,?,?,?,UTC_TIMESTAMP())";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 's';
            $parameterArray[] = &$name;

            $types .= 's';
            $parameterArray[] = &$sign;

            $types .= 's';
            $parameterArray[] = &$isocurrencycode;

            $types .= 's';
            $parameterArray[] = &$description;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->insert_id;
            $stmt->close();
            if($myresult <= 0) {
                $dragon_ecommerce_dbResult .= 'Error adding a currency into table ' . $table_name . ". ";return;
            }
        } else {
            $dragon_ecommerce_dbResult .= 'Mysqli is not supported by your system. ';return;
        }
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }
}

function expenseszyx987_getAllCurrencies($onlyActive = false) {
    global $wpdb; global $dragon_ecommerce_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_expenseszyx987_currency';
    if($onlyActive) {
        $results = $wpdb->get_results("SELECT * from $table_name WHERE status = 1 order by name");
    } else {
        $results = $wpdb->get_results("SELECT * from $table_name order by name");
    }
    foreach($results as $result) {
        foreach($result as $key => $value) {
            $result->$key = deslash($value);
        }
    }
    return $results;
}

add_action('wp_ajax_expenseszyx987_saveCurrency', 'expenseszyx987_saveCurrency');
function expenseszyx987_saveCurrency() {
    check_ajax_referer('expenseszyx987_saveCurrency', 'expenseszyx987_hidden_security_savecurrency');
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        echo 'Invalid user info.';
        exit();
    }
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        $currencyid_temp = empty($_POST['id']) ? 0 : strip_tags(sanitize_text_field($_POST['id']));
        $currencyid = intval($currencyid_temp);

        if($currencyid <= 0 || $_POST['status'] === null || $_POST['status'] === '') {echo "Invalid id.";exit();}

        $currencyname_temp = $_POST['name'] === null ? '' : strip_tags(sanitize_text_field($_POST['name']));
        $currencyname = stripslashes(trim($currencyname_temp));

        $currencysign_temp = $_POST['sign'] === null ? '' : strip_tags(sanitize_text_field($_POST['sign']));
        $currencysign = stripslashes(trim($currencysign_temp));

        $isocurrencycode_temp = $_POST['isocurrencycode'] === null ? '' : strip_tags(sanitize_text_field($_POST['isocurrencycode']));
        $isocurrencycode = stripslashes(trim($isocurrencycode_temp));

        $currencydescription_temp = $_POST['description'] === null ? '' : strip_tags(sanitize_text_field($_POST['description']));
        $currencydescription = stripslashes(trim($currencydescription_temp));

        $currencystatus_temp = $_POST['status'] === null ? '' : strip_tags(sanitize_text_field($_POST['status']));
        $currencystatus = $currencystatus_temp === '' ? 0 : intval($currencystatus_temp);

        if(($isocurrencycode === null || $isocurrencycode === '') && ($currencysign === null || $currencysign === '')
            && $currencyname === '' && $currencydescription === '' && $currencystatus === -1) {
            echo "Please enter a value.";exit();
        }
        if(($isocurrencycode === null || $isocurrencycode === '') || ($currencysign === null || $currencysign === '')
            || $currencyname === '' || $currencystatus === -1) {
            echo "Name, sign, isocurrencycode, and status are required.";exit();
        }
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987_currency';
        $finalresult = 'Success';
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            //There could be the same sign for different currency
            $stmt = $wpdb->dbh->prepare("SELECT COUNT(*) countresult FROM $table_name WHERE (name = ? or isocurrencycode = ?) AND id != ?");
            $stmt->bind_param("ssi", $currencyname, $isocurrencycode, $currencyid);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            if(count($result) === 1) {
                $temp_row = $result[0];
                $temp_result = $temp_row["countresult"];
                $dbcount = $temp_result === null ? 0 : intval($temp_result);
                if($dbcount > 0) {$finalresult = "Edit a currency: currency name: \"" . esc_html($currencyname) . "\"  and/or isocurrencycode: \"" . esc_html($isocurrencycode) . "\" already exist(s) in the currency table. Not saved. ";echo $finalresult;exit();}
            } else {
                $finalresult = "Edit a currency: currency name \"" . esc_html($currencyname) . "\" query has error. Not saved. ";echo esc_html($finalresult);exit();
            }
            $stmt=null;
            $sqlColumnsArray = array();
            if($currencyname !== '') {
                $sqlColumnsArray['name|s'] = $currencyname;
            }
            $sqlColumnsArray['description|s'] = $currencydescription;
            if($isocurrencycode !== null && $isocurrencycode !== '') {
                $sqlColumnsArray['isocurrencycode|s'] = $isocurrencycode;
            }
            if($currencysign !== null && $currencysign !== '') {
                $sqlColumnsArray['sign|s'] = $currencysign;
            }
            if($currencystatus === 0 || $currencystatus === 1) {
                $sqlColumnsArray['status|i'] = $currencystatus;
            }
            if(count($sqlColumnsArray) > 0) {
                $query = "UPDATE $table_name SET ";
                $types = '';
                $parameterArray = array('');
                foreach($sqlColumnsArray as $key => $value) {
                    $temp = explode('|', $key, 2);
                    $types .= $temp[1];
                    $query .= ' ' . $temp[0] . ' = ?, ';
                    if($temp[0] === 'name') {
                        $parameterArray[] = &$currencyname;
                    } elseif($temp[0] === 'description') {
                        $parameterArray[] = &$currencydescription;
                    } elseif($temp[0] === 'isocurrencycode') {
                        $parameterArray[] = &$isocurrencycode;
                    } elseif($temp[0] === 'sign') {
                        $parameterArray[] = &$currencysign;
                    } elseif($temp[0] === 'status') {
                        $parameterArray[] = &$currencystatus;
                    }
                }
                $query .= " updatetimeutc = UTC_TIMESTAMP() WHERE id = ? ";
                $types .= 'i';
                $parameterArray[] = &$currencyid;
                $parameterArray[0] = $types;
                $stmt = $wpdb->dbh->prepare($query);
                call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                $stmt->execute();
                if($wpdb->dbh->errno > 0 || $stmt->errno > 0) {
                    $finalresult = 'Edit currency failed';
                }
                $stmt->close();
            } else {
                $finalresult = 'Nothing is updated';
            }
            echo esc_html($finalresult);
            exit();
        }
    }
    echo "Invalid data.";
    exit();
}

add_action('wp_ajax_expenseszyx987_saveCustomertype', 'expenseszyx987_saveCustomertype');
function expenseszyx987_saveCustomertype() {
    check_ajax_referer('expenseszyx987_saveCustomertype', 'expenseszyx987_hidden_security_savecustomertype');
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        echo 'Invalid user info.';
        exit();
    }
    if(!expenseszyx987_userCanEditInAdminPage()) {
        echo 'You are not authorized to edit data in admin page. Please contact web admin.';
        exit();
    }
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        $customertypeid_temp = empty($_POST['id']) ? 0 : strip_tags(sanitize_text_field($_POST['id']));
        $customertypeid = intval($customertypeid_temp);

        if($customertypeid <= 0 || $_POST['status'] === null || $_POST['status'] === '') {echo "Invalid id.";exit();}

        $customertypename_temp = $_POST['name'] === null ? '' : strip_tags(sanitize_text_field($_POST['name']));
        $customertypename = expenseszyx987_stripAllBackSlashes($customertypename_temp);

        $customertypedescription_temp = $_POST['description'] === null ? '' : strip_tags(sanitize_text_field($_POST['description']));
        $customertypedescription = expenseszyx987_stripAllBackSlashes($customertypedescription_temp);

        $customertypestatus_temp = $_POST['status'] === null ? '' : strip_tags(sanitize_text_field($_POST['status']));
        $customertypestatus = $customertypestatus_temp === '' ? 0 : intval($customertypestatus_temp);

        if($customertypename === '' && $customertypedescription === '' && $customertypestatus !== 0 && $customertypestatus !== 1) {
            echo "Please enter a value.";exit();
        }
        if($customertypename === '' || ($customertypestatus !== 0 && $customertypestatus !== 1)) {
            echo "Name and status are required.";exit();
        }
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987_customertype';
        $finalresult = 'Success';
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $stmt = $wpdb->dbh->prepare("SELECT COUNT(*) countresult FROM $table_name WHERE name = ? and id != ?");
            $stmt->bind_param("si", $customertypename, $customertypeid);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            if(count($result) === 1) {
                $temp_row = $result[0];
                $temp_result = $temp_row["countresult"];
                $dbcount = $temp_result === null ? 0 : intval($temp_result);
                if($dbcount !== 0) {echo "Edit a Customertype: customertype name \"" . esc_html($customertypename) . "\" already exists in the table. Not saved.";exit();}
            } else {
                echo "Edit a Customertype: customertype name \"" . esc_html($customertypename) . "\" query has error. Not saved.";exit();
            }

            $stmt=null;
            $sqlColumnsArray = array();
            if($customertypename !== '') {
                $sqlColumnsArray['name|s'] = $customertypename;
            }
            $sqlColumnsArray['description|s'] = $customertypedescription;
            if($customertypestatus === 0 || $customertypestatus === 1) {
                $sqlColumnsArray['status|i'] = $customertypestatus;
            }
            if(count($sqlColumnsArray) > 0) {
                $query = "UPDATE $table_name SET ";
                $types = '';
                $parameterArray = array('');
                foreach($sqlColumnsArray as $key => $value) {
                    $temp = explode('|', $key, 2);

                    $types .= $temp[1];
                    $query .= ' ' . $temp[0] . ' = ?, ';
                    if($temp[0] === 'name') {
                        $parameterArray[] = &$customertypename;
                    } elseif($temp[0] === 'description') {
                        $parameterArray[] = &$customertypedescription;
                    } elseif($temp[0] === 'status') {
                        $parameterArray[] = &$customertypestatus;
                    }
                }
                $query .= " updatetimeutc = UTC_TIMESTAMP() WHERE id = ? ";
                $types .= 'i';
                $parameterArray[] = &$customertypeid;
                $parameterArray[0] = $types;
                $stmt = $wpdb->dbh->prepare($query);
                call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                $stmt->execute();
                if($wpdb->dbh->errno > 0 || $stmt->errno > 0) {
                    $finalresult = 'Edit customertype failed';
                }
                $stmt->close();
            } else {
                $finalresult = 'Nothing is updated';
            }
            echo esc_html($finalresult);
            exit();
        }
    }
    echo "Invalid data.";
    exit();
}

add_action('wp_ajax_expenseszyx987_saveCustomer', 'expenseszyx987_saveCustomer');
function expenseszyx987_saveCustomer() {
    check_ajax_referer('expenseszyx987_saveCustomer', 'expenseszyx987_hidden_security_savecustomer');
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        echo 'Invalid user info.';
        exit();
    }
    if(!expenseszyx987_userCanEditInAdminPage()) {
        echo 'You are not authorized to edit data in admin page. Please contact web admin.';
        exit();
    }
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        $customerid_temp = empty($_POST['id']) ? 0 : strip_tags(sanitize_text_field($_POST['id']));
        $customerid = intval($customerid_temp);

        if($customerid <= 0 || $_POST['status'] === null || $_POST['status'] === '') {echo "Invalid id.";exit();}

        $customername_temp = $_POST['name'] === null ? '' : strip_tags(sanitize_text_field($_POST['name']));
        $customername = expenseszyx987_stripAllBackSlashes($customername_temp);

        $customerdescription_temp = $_POST['description'] === null ? '' : strip_tags(sanitize_text_field($_POST['description']));
        $customerdescription = expenseszyx987_stripAllBackSlashes($customerdescription_temp);

        $customerstatus_temp = $_POST['status'] === null ? '' : strip_tags(sanitize_text_field($_POST['status']));
        $customerstatus = $customerstatus_temp === '' ? 0 : intval($customerstatus_temp);        

        $customertypeid_temp = empty($_POST['customertypeid']) ? '-1' : strip_tags(sanitize_text_field($_POST['customertypeid']));
        $customertypeid = intval($customertypeid_temp);

        if($customername === '' && $customerdescription === '' && $customerstatus !== 0 && $customerstatus !== 1 && $customertypeid == -1) {
            echo "Please enter a value.";exit();
        }
        if($customername === '' || ($customerstatus !== 0 && $customerstatus !== 1)) {
            echo "Name and status are required.";exit();
        }
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987_customer';
        $finalresult = 'Success';
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $stmt = $wpdb->dbh->prepare("SELECT COUNT(*) countresult FROM $table_name WHERE name = ? and id != ?");
            $stmt->bind_param("si", $customername, $customerid);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            if(count($result) === 1) {
                $temp_row = $result[0];
                $temp_result = $temp_row["countresult"];
                $dbcount = $temp_result === null ? 0 : intval($temp_result);
                if($dbcount !== 0) {echo "Edit a customer: customer name \"" . esc_html($customername) . "\" already exists in the table. Not saved.";exit();}
            } else {
                echo "Edit a customer: customer name \"" . esc_html($customername) . "\" query has error. Not saved.";exit();
            }

            $stmt=null;
            $sqlColumnsArray = array();
            if($customername !== '') {
                $sqlColumnsArray['name|s'] = $customername;
            }
            $sqlColumnsArray['description|s'] = $customerdescription;
            if($customerstatus === 0 || $customerstatus === 1) {
                $sqlColumnsArray['status|i'] = $customerstatus;
            }
            $sqlColumnsArray['customertypeid|s'] = $customertypeid;
            if($customertypeid === -1) {
                $customertypeid = null;
            }
            if(count($sqlColumnsArray) > 0) {
                $query = "UPDATE $table_name SET ";
                $types = '';
                $parameterArray = array('');
                foreach($sqlColumnsArray as $key => $value) {
                    $temp = explode('|', $key, 2);

                    $types .= $temp[1];
                    $query .= ' ' . $temp[0] . ' = ?, ';
                    if($temp[0] === 'name') {
                        $parameterArray[] = &$customername;
                    } elseif($temp[0] === 'description') {
                        $parameterArray[] = &$customerdescription;
                    } elseif($temp[0] === 'status') {
                        $parameterArray[] = &$customerstatus;
                    } elseif($temp[0] === 'customertypeid') {
                        $parameterArray[] = &$customertypeid;
                    }
                }
                $query .= " updatetimeutc = UTC_TIMESTAMP() WHERE id = ? ";
                $types .= 'i';
                $parameterArray[] = &$customerid;
                $parameterArray[0] = $types;
                $stmt = $wpdb->dbh->prepare($query);
                call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                $stmt->execute();
                if($wpdb->dbh->errno > 0 || $stmt->errno > 0) {
                    $finalresult = 'Edit customer failed';
                }
                $stmt->close();
            } else {
                $finalresult = 'Nothing is updated';
            }
            echo esc_html($finalresult);
            exit();
        }
    }
    echo "Invalid data.";
    exit();
}

add_action('wp_ajax_expenseszyx987_saveRecurringpaymentfrequency', 'expenseszyx987_saveRecurringpaymentfrequency');
function expenseszyx987_saveRecurringpaymentfrequency() {
    check_ajax_referer('expenseszyx987_saveRecurringpaymentfrequency', 'expenseszyx987_hidden_security_saverecurringpaymentfrequency');
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        echo 'Invalid user info.';
        exit();
    }
    if(!expenseszyx987_userCanEditInAdminPage()) {
        echo 'You are not authorized to edit data in admin page. Please contact web admin.';
        exit();
    }
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        $recurringpaymentfrequencyid_temp = empty($_POST['id']) ? 0 : strip_tags(sanitize_text_field($_POST['id']));
        $recurringpaymentfrequencyid = intval($recurringpaymentfrequencyid_temp);

        if($recurringpaymentfrequencyid <= 0 || $_POST['status'] === null || $_POST['status'] === '') {echo "Invalid id.";exit();}

        $recurringpaymentfrequencyname_temp = $_POST['name'] === null ? '' : strip_tags(sanitize_text_field($_POST['name']));
        $recurringpaymentfrequencyname = expenseszyx987_stripAllBackSlashes($recurringpaymentfrequencyname_temp);

        $recurringpaymentfrequencydescription_temp = $_POST['description'] === null ? '' : strip_tags(sanitize_text_field($_POST['description']));
        $recurringpaymentfrequencydescription = expenseszyx987_stripAllBackSlashes($recurringpaymentfrequencydescription_temp);

        $recurringpaymentfrequencystatus_temp = $_POST['status'] === null ? '' : strip_tags(sanitize_text_field($_POST['status']));
        $recurringpaymentfrequencystatus = $recurringpaymentfrequencystatus_temp === '' ? 0 : intval($recurringpaymentfrequencystatus_temp);

        if($recurringpaymentfrequencyname === '' && $recurringpaymentfrequencydescription === '' && $recurringpaymentfrequencystatus !== 0 && $recurringpaymentfrequencystatus !== 1) {
            echo "Please enter a value.";exit();
        }
        if($recurringpaymentfrequencyname === '' || ($recurringpaymentfrequencystatus !== 0 && $recurringpaymentfrequencystatus !== 1)) {
            echo "Name and status are required.";exit();
        }
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987_recurringpaymentfrequency';
        $finalresult = 'Success';
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $stmt = $wpdb->dbh->prepare("SELECT COUNT(*) countresult FROM $table_name WHERE name = ? and id != ?");
            $stmt->bind_param("si", $recurringpaymentfrequencyname, $recurringpaymentfrequencyid);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            if(count($result) === 1) {
                $temp_row = $result[0];
                $temp_result = $temp_row["countresult"];
                $dbcount = $temp_result === null ? 0 : intval($temp_result);
                if($dbcount !== 0) {echo "Edit a recurring payment frequency: recurring payment frequency name \"" . esc_html($recurringpaymentfrequencyname) . "\" already exists in the table. Not saved.";exit();}
            } else {
                echo "Edit a recurring payment frequency: recurring payment frequency name \"" . esc_html($recurringpaymentfrequencyname) . "\" query has error. Not saved.";exit();
            }

            $stmt=null;
            $sqlColumnsArray = array();
            if($recurringpaymentfrequencyname !== '') {
                $sqlColumnsArray['name|s'] = $recurringpaymentfrequencyname;
            }
            $sqlColumnsArray['description|s'] = $recurringpaymentfrequencydescription;
            if($recurringpaymentfrequencystatus === 0 || $recurringpaymentfrequencystatus === 1) {
                $sqlColumnsArray['status|i'] = $recurringpaymentfrequencystatus;
            }
            if(count($sqlColumnsArray) > 0) {
                $query = "UPDATE $table_name SET ";
                $types = '';
                $parameterArray = array('');
                foreach($sqlColumnsArray as $key => $value) {
                    $temp = explode('|', $key, 2);

                    $types .= $temp[1];
                    $query .= ' ' . $temp[0] . ' = ?, ';
                    if($temp[0] === 'name') {
                        $parameterArray[] = &$recurringpaymentfrequencyname;
                    } elseif($temp[0] === 'description') {
                        $parameterArray[] = &$recurringpaymentfrequencydescription;
                    } elseif($temp[0] === 'status') {
                        $parameterArray[] = &$recurringpaymentfrequencystatus;
                    }
                }
                $query .= " updatetimeutc = UTC_TIMESTAMP() WHERE id = ? ";
                $types .= 'i';
                $parameterArray[] = &$recurringpaymentfrequencyid;
                $parameterArray[0] = $types;
                $stmt = $wpdb->dbh->prepare($query);
                call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                $stmt->execute();
                if($wpdb->dbh->errno > 0 || $stmt->errno > 0) {
                    $finalresult = 'Edit recurring payment frequency failed';
                }
                $stmt->close();
            } else {
                $finalresult = 'Nothing is updated';
            }
            echo esc_html($finalresult);
            exit();
        }
    }
    echo "Invalid data.";
    exit();
}

add_action('wp_ajax_expenseszyx987_saveDepartment', 'expenseszyx987_saveDepartment');
function expenseszyx987_saveDepartment() {
    check_ajax_referer('expenseszyx987_saveDepartment', 'expenseszyx987_hidden_security_savedepartment');
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        echo 'Invalid user info.';
        exit();
    }
    if(!expenseszyx987_userCanEditInAdminPage()) {
        echo 'You are not authorized to edit data in admin page. Please contact web admin.';
        exit();
    }
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        $departmentid_temp = empty($_POST['id']) ? 0 : strip_tags(sanitize_text_field($_POST['id']));
        $departmentid = intval($departmentid_temp);

        if($departmentid <= 0 || $_POST['status'] === null || $_POST['status'] === '') {echo "Invalid id.";exit();}

        $departmentname_temp = $_POST['name'] === null ? '' : strip_tags(sanitize_text_field($_POST['name']));
        $departmentname = expenseszyx987_stripAllBackSlashes($departmentname_temp);

        $departmentdescription_temp = $_POST['description'] === null ? '' : strip_tags(sanitize_text_field($_POST['description']));
        $departmentdescription = expenseszyx987_stripAllBackSlashes($departmentdescription_temp);

        $departmentstatus_temp = $_POST['status'] === null ? '' : strip_tags(sanitize_text_field($_POST['status']));
        $departmentstatus = $departmentstatus_temp === '' ? 0 : intval($departmentstatus_temp);

        if($departmentname === '' && $departmentdescription === '' && $departmentstatus !== 0 && $departmentstatus !== 1) {
            echo "Please enter a value.";exit();
        }
        if($departmentname === '' || ($departmentstatus !== 0 && $departmentstatus !== 1)) {
            echo "Name and status are required.";exit();
        }
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987_department';
        $finalresult = 'Success';
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $stmt = $wpdb->dbh->prepare("SELECT COUNT(*) countresult FROM $table_name WHERE name = ? and id != ?");
            $stmt->bind_param("si", $departmentname, $departmentid);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            if(count($result) === 1) {
                $temp_row = $result[0];
                $temp_result = $temp_row["countresult"];
                $dbcount = $temp_result === null ? 0 : intval($temp_result);
                if($dbcount !== 0) {echo "Edit a department: department name \"" . esc_html($departmentname) . "\" already exists in the table. Not saved.";exit();}
            } else {
                echo "Edit a department: department name \"" . esc_html($departmentname) . "\" query has error. Not saved.";exit();
            }

            $stmt=null;
            $sqlColumnsArray = array();
            if($departmentname !== '') {
                $sqlColumnsArray['name|s'] = $departmentname;
            }
            $sqlColumnsArray['description|s'] = $departmentdescription;
            if($departmentstatus === 0 || $departmentstatus === 1) {
                $sqlColumnsArray['status|i'] = $departmentstatus;
            }
            if(count($sqlColumnsArray) > 0) {
                $query = "UPDATE $table_name SET ";
                $types = '';
                $parameterArray = array('');
                foreach($sqlColumnsArray as $key => $value) {
                    $temp = explode('|', $key, 2);

                    $types .= $temp[1];
                    $query .= ' ' . $temp[0] . ' = ?, ';
                    if($temp[0] === 'name') {
                        $parameterArray[] = &$departmentname;
                    } elseif($temp[0] === 'description') {
                        $parameterArray[] = &$departmentdescription;
                    } elseif($temp[0] === 'status') {
                        $parameterArray[] = &$departmentstatus;
                    }
                }
                $query .= " updatetimeutc = UTC_TIMESTAMP() WHERE id = ? ";
                $types .= 'i';
                $parameterArray[] = &$departmentid;
                $parameterArray[0] = $types;    
                $stmt = $wpdb->dbh->prepare($query);
                call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                $stmt->execute();
                if($wpdb->dbh->errno > 0 || $stmt->errno > 0) {
                    $finalresult = 'Edit department failed';
                }
                $stmt->close();
            } else {
                $finalresult = 'Nothing is updated';
            }
            echo esc_html($finalresult);
            exit();
        }
    }
    echo "Invalid data.";
    exit();
}

add_action('wp_ajax_expenseszyx987_editConstantvalue', 'expenseszyx987_editConstantvalue');
function expenseszyx987_editConstantvalue() {
    check_ajax_referer('expenseszyx987_editConstantvalue', 'expenseszyx987_hidden_security_editconstantvalue');
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        echo 'Invalid user info.';
        exit();
    }
    if(!expenseszyx987_userCanEditInAdminPage()) {
        echo 'You are not authorized to edit data in admin page. Please contact web admin.';
        exit();
    }
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        $constantid_temp = empty($_POST['id']) ? 0 : strip_tags(sanitize_text_field($_POST['id']));
        $constantid = intval($constantid_temp);

        if($constantid <= 0 || $_POST['value'] === null) {echo "Invalid id.";exit();}

        $constantname_temp = $_POST['name'] === null ? '' : strip_tags(sanitize_text_field($_POST['name']));
        $constantname = $constantname_temp;

        $constantvalue_temp = $_POST['value'] === null ? '' : strip_tags(sanitize_text_field($_POST['value']));
        $constantvalue = $constantvalue_temp;

        $constantvalue2 = "";
        //if($constantname === 'COMPANY_TIMEZONE' && ($constantvalue === '-1' || $constantvalue === '')) {
        //    echo "Please choose a timezone.";exit();
        //}
        //if($constantname === 'COMPANY_TIMEZONE') {
        //    $temp = explode("|", $constantvalue);
        //    $constantvalue = $temp[0];
        //    $constantvalue2 = $temp[1];
        //}
        if($constantvalue2 === "" || $constantvalue2 === null) {
            $constantvalue2 = "+00:00";
        }
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987_constant';
        $finalresult = '';
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $query = "UPDATE $table_name SET value = ?, updatetimeutc = UTC_TIMESTAMP() WHERE id = ? ";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 's';
            $parameterArray[] = &$constantvalue;

            $types .= 'i';
            $parameterArray[] = &$constantid;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            if($wpdb->dbh->errno > 0 || $stmt->errno > 0) {
                $finalresult .= 'Edit constant id: ' . $constantid . ' failed. ';
            }
            $stmt->close();

            /*if($constantname === 'COMPANY_TIMEZONE' && $constantvalue2 !== '') {
                $query = "UPDATE $table_name SET value = ?, updatetimeutc = UTC_TIMESTAMP() WHERE name='COMPANY_TIMEZONE_HOURS' ";
                $stmt = $wpdb->dbh->prepare($query);
                $types = '';
                $parameterArray = array('');

                $types .= 's';
                $parameterArray[] = &$constantvalue2;

                $parameterArray[0] = $types;
                call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                $stmt->execute();
                if($wpdb->dbh->errno > 0 || $stmt->errno > 0) {
                    $finalresult .= 'Edit constant COMPANY_TIMEZONE_HOURS failed. ';
                }
                $stmt->close();
            }*/
            if($finalresult === '') {$finalresult = 'Success';}
            echo esc_html($finalresult);
            exit();
        } else {
            echo 'This website can not use mysqli. Please contact website admin.';
            exit();
        }
    }
    echo "Invalid data.";
    exit();
}

add_action('wp_ajax_expenseszyx987_getExpensedetails', 'expenseszyx987_getExpensedetails');
function expenseszyx987_getExpensedetails() {
    check_ajax_referer('expenseszyx987_getExpensedetails', 'expenseszyx987_hidden_security_getexpensedetails');
    if(!expenseszyx987_userCanReadInAdminPage()) {
        header("Content-Type: application/json");
        echo wp_json_encode("{}");    
        exit();
    }
    if((!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $storedprocedure_name = 'wp_expenseszyx987_getExpenseDetailsList';

        $amountperpage = empty($_POST['amountperpage']) ? '10' : strip_tags(sanitize_text_field($_POST['amountperpage']));
        $amountperpage = intval($amountperpage);
        if($amountperpage === -1) {$amountperpage = 10;};

        $pagenumber = empty($_POST['pagenumber']) ? '1' : strip_tags(sanitize_text_field($_POST['pagenumber']));
        $pagenumber = intval($pagenumber);
        $myoffset = ($pagenumber - 1) * $amountperpage;

        $mysortby = empty($_POST['sortby']) ? '' : strip_tags(sanitize_text_field($_POST['sortby']));
        $mysortby = $mysortby === '' ? 'id' : $mysortby;

        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : strip_tags(sanitize_text_field($_POST['order']));
        $myorder = $myorder === '' ? 'desc' : $myorder;

        $fromdate = empty($_POST['fromdate']) ? '1000-01-01 00:00:00' : strip_tags(sanitize_text_field($_POST['fromdate']));
        $todate = empty($_POST['todate']) ? '9999-12-31 23:59:59' : strip_tags(sanitize_text_field($_POST['todate']));

        if(expenseszyx987_validateDate($fromdate) && expenseszyx987_validateDate($todate)) {
            if($fromdate > $todate) {
                echo "Error. From date is later than to date.";exit();
            }
        }else{
            echo "Error. Please enter a valid date.";exit();
        }

        $searchtypename_temp = (empty($_POST['typename']) || trim($_POST['typename']) === '') ? '' : strip_tags(sanitize_text_field($_POST['typename']));
        $searchtypename_temp = preg_replace('/[^a-zA-Z0-9\/()$@?!\[\]{}#%^*+|~]/', '%', $searchtypename_temp);
        $searchtypename = trim($searchtypename_temp) === '' ? '' : $searchtypename_temp;

        $searchtypecategoryname_temp = (empty($_POST['typecategoryname']) || trim($_POST['typecategoryname']) === '') ? '' : strip_tags(sanitize_text_field($_POST['typecategoryname']));
        $searchtypecategoryname_temp = preg_replace('/[^a-zA-Z0-9\/()$@?!\[\]{}#%^*+|~]/', '%', $searchtypecategoryname_temp);
        $searchtypecategoryname = trim($searchtypecategoryname_temp) === '' ? '' : $searchtypecategoryname_temp;

        $expenseid = empty($_POST['expenseid']) ? '-1' : strip_tags(sanitize_text_field($_POST['expenseid']));
        $expenseid = intval($expenseid);

        $userid = empty($_POST['userid']) ? '-1' : strip_tags(sanitize_text_field($_POST['userid']));
        $userid = intval($userid);

        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $query = "CALL " . $storedprocedure_name . "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, @outvalue);";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 'i';
            $parameterArray[] = &$pagenumber;

            $types .= 'i';
            $parameterArray[] = &$amountperpage;

            $types .= 'i';
            $parameterArray[] = &$myoffset;

            $types .= 's';
            $parameterArray[] = &$mysortby;

            $types .= 's';
            $parameterArray[] = &$myorder;

            $types .= 'i';
            $parameterArray[] = &$expenseid;

            $types .= 'i';
            $parameterArray[] = &$userid;

            $types .= 's';
            $parameterArray[] = &$searchtypename;

            $types .= 's';
            $parameterArray[] = &$searchtypecategoryname;

            $types .= 's';
            $parameterArray[] = &$fromdate;

            $types .= 's';
            $parameterArray[] = &$todate;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $expenses = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            $stmt2 = $wpdb->dbh->prepare('SELECT @outvalue');
            $stmt2->execute();
            $myresult2 = $stmt2->get_result();
            $totalObjArr = $myresult2 === FALSE ? array() : $myresult2->fetch_all(MYSQLI_ASSOC);
            $stmt2->close();

            $total = "0";
            foreach($totalObjArr[0] as $key => $value) {
                if($key === '@outvalue') {
                    $total = $value == null ? "0" : $value;
                }
            }
            foreach($expenses as $expense) {
                foreach($expense as $key => $value) {
                    $expense[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["expensedetails"] = $expenses;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo wp_json_encode($result);
            exit();
        }
    }
    header("Content-Type: application/json");
    echo wp_json_encode("{}");
    exit();
}

add_action('wp_ajax_expenseszyx987_getTypecategories', 'expenseszyx987_getTypecategoriesByAjax');
function expenseszyx987_getTypecategoriesByAjax() {
    check_ajax_referer('expenseszyx987_getTypecategories', 'expenseszyx987_hidden_security_gettypecategories');
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        header("Content-Type: application/json");
        echo wp_json_encode("{}");
        exit();
    }
    if(!expenseszyx987_userCanReadInAdminPage()) {
        header("Content-Type: application/json");
        echo wp_json_encode("{}");
        exit();
    }
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $storedprocedure_name = 'wp_expenseszyx987_getTypecategoryList';

        $typecategorystatus = (!isset($_POST['typecategorystatus'])) ? '-1' : strip_tags(sanitize_text_field($_POST['typecategorystatus']));
        $typecategorystatus = intval($typecategorystatus);

        $amountperpage = empty($_POST['amountperpage']) ? '10' : strip_tags(sanitize_text_field($_POST['amountperpage']));
        $amountperpage = intval($amountperpage);
        if($amountperpage === -1) {$amountperpage = 10;}

        $pagenumber = empty($_POST['pagenumber']) ? '1' : strip_tags(sanitize_text_field($_POST['pagenumber']));
        $pagenumber = intval($pagenumber);

        $myoffset = ($pagenumber - 1) * $amountperpage;

        $mysortby = empty($_POST['sortby']) ? '' : strip_tags(sanitize_text_field($_POST['sortby']));
        $mysortby = $mysortby === '' ? 'id' : $mysortby;

        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : strip_tags(sanitize_text_field($_POST['order']));
        $myorder = $myorder === '' ? 'asc' : $myorder;

        $searchwords = empty($_POST['searchwords']) ? '' : strip_tags(sanitize_text_field($_POST['searchwords']));

        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $query = "CALL " . $storedprocedure_name . "(?, ?, ?, ?, ?, ?, ?, @outvalue );";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 'i';
            $parameterArray[] = &$pagenumber;

            $types .= 'i';
            $parameterArray[] = &$amountperpage;

            $types .= 'i';
            $parameterArray[] = &$myoffset;

            $types .= 's';
            $parameterArray[] = &$mysortby;

            $types .= 's';
            $parameterArray[] = &$myorder;

            $types .= 's';
            $parameterArray[] = &$searchwords;

            $types .= 'i'; //0: inactive, 1: active, -1: both
            $parameterArray[] = &$typecategorystatus;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $typecategories = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            $stmt2 = $wpdb->dbh->prepare('SELECT @outvalue');
            $stmt2->execute();
            $myresult2 = $stmt2->get_result();
            $totalObjArr = $myresult2 === FALSE ? array() : $myresult2->fetch_all(MYSQLI_ASSOC);
            $stmt2->close();

            $total = "0";
            foreach ($totalObjArr[0] as $key => $value) {
                if($key === '@outvalue') {
                    $total = $value == null ? "0" : $value;
                }
            }
            foreach ($typecategories as $typecategory) {
                foreach ($typecategory as $key => $value) {
                    $typecategory[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["typecategory"] = $typecategories;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo wp_json_encode($result);
            exit();
        }
    }
    header("Content-Type: application/json");
    echo wp_json_encode("{}");
    exit();
}

add_action('wp_ajax_expenseszyx987_getTypes', 'expenseszyx987_getTypesByAjax');
function expenseszyx987_getTypesByAjax() {
    check_ajax_referer('expenseszyx987_getTypes', 'expenseszyx987_hidden_security_gettypes');
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        header("Content-Type: application/json");
        echo wp_json_encode("{}");
        exit();
    }
    if(!expenseszyx987_userCanReadInAdminPage()) {
        header("Content-Type: application/json");
        echo wp_json_encode("{}");
        exit();
    }
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $storedprocedure_name = 'wp_expenseszyx987_getTypeList';

        $typestatus = (!isset($_POST['typestatus'])) ? '-1' : strip_tags(sanitize_text_field($_POST['typestatus']));
        $typestatus = intval($typestatus);

        $amountperpage = empty($_POST['amountperpage']) ? '10' : strip_tags(sanitize_text_field($_POST['amountperpage']));
        $amountperpage = intval($amountperpage);
        if($amountperpage === -1) {$amountperpage = 10;}

        $pagenumber = empty($_POST['pagenumber']) ? '1' : strip_tags(sanitize_text_field($_POST['pagenumber']));
        $pagenumber = intval($pagenumber);

        $myoffset = ($pagenumber - 1) * $amountperpage;

        $mysortby = empty($_POST['sortby']) ? '' : strip_tags(sanitize_text_field($_POST['sortby']));
        $mysortby = $mysortby === '' ? 'id' : $mysortby;

        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : strip_tags(sanitize_text_field($_POST['order']));
        $myorder = $myorder === '' ? 'asc' : $myorder;

        $searchwords = empty($_POST['searchwords']) ? '' : strip_tags(sanitize_text_field($_POST['searchwords']));

        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $query = "CALL " . $storedprocedure_name . "(?, ?, ?, ?, ?, ?, ?, @outvalue );";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 'i';
            $parameterArray[] = &$pagenumber;

            $types .= 'i';
            $parameterArray[] = &$amountperpage;

            $types .= 'i';
            $parameterArray[] = &$myoffset;

            $types .= 's';
            $parameterArray[] = &$mysortby;

            $types .= 's';
            $parameterArray[] = &$myorder;

            $types .= 's';
            $parameterArray[] = &$searchwords;

            $types .= 'i'; //0: inactive, 1: active, -1: both
            $parameterArray[] = &$typestatus;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $types = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            $stmt2 = $wpdb->dbh->prepare('SELECT @outvalue');
            $stmt2->execute();
            $myresult2 = $stmt2->get_result();
            $totalObjArr = $myresult2 === FALSE ? array() : $myresult2->fetch_all(MYSQLI_ASSOC);
            $stmt2->close();

            $total = "0";
            foreach ($totalObjArr[0] as $key => $value) {
                if($key === '@outvalue') {
                    $total = $value == null ? "0" : $value;
                }
            }
            foreach ($types as $type) {
                foreach ($type as $key => $value) {
                    $type[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["type"] = $types;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo wp_json_encode($result);
            exit();
        }
    }
    header("Content-Type: application/json");
    echo wp_json_encode("{}");
    exit();
}

add_action('wp_ajax_expenseszyx987_getRoles', 'expenseszyx987_getRolesByAjax');
function expenseszyx987_getRolesByAjax() {
    check_ajax_referer('expenseszyx987_getRoles', 'expenseszyx987_hidden_security_getroles');
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        header("Content-Type: application/json");
        echo wp_json_encode("{}");
        exit();
    }
    if(!expenseszyx987_userCanReadInAdminPage()) {
        header("Content-Type: application/json");
        echo wp_json_encode("{}");
        exit();
    }
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $storedprocedure_name = 'wp_expenseszyx987_getRoleList';

        $rolestatus = (!isset($_POST['rolestatus'])) ? '-1' : strip_tags(sanitize_text_field($_POST['rolestatus']));
        $rolestatus = intval($rolestatus);

        $amountperpage = empty($_POST['amountperpage']) ? '10' : strip_tags(sanitize_text_field($_POST['amountperpage']));
        $amountperpage = intval($amountperpage);
        if($amountperpage === -1) {$amountperpage = 10;}

        $pagenumber = empty($_POST['pagenumber']) ? '1' : strip_tags(sanitize_text_field($_POST['pagenumber']));
        $pagenumber = intval($pagenumber);

        $myoffset = ($pagenumber - 1) * $amountperpage;

        $mysortby = empty($_POST['sortby']) ? '' : strip_tags(sanitize_text_field($_POST['sortby']));
        $mysortby = $mysortby === '' ? 'id' : $mysortby;

        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : strip_tags(sanitize_text_field($_POST['order']));
        $myorder = $myorder === '' ? 'asc' : $myorder;

        $searchwords = empty($_POST['searchwords']) ? '' : strip_tags(sanitize_text_field($_POST['searchwords']));

        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $query = "CALL " . $storedprocedure_name . "(?, ?, ?, ?, ?, ?, ?, @outvalue );";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 'i';
            $parameterArray[] = &$pagenumber;

            $types .= 'i';
            $parameterArray[] = &$amountperpage;

            $types .= 'i';
            $parameterArray[] = &$myoffset;

            $types .= 's';
            $parameterArray[] = &$mysortby;

            $types .= 's';
            $parameterArray[] = &$myorder;

            $types .= 's';
            $parameterArray[] = &$searchwords;

            $types .= 'i'; //0: inactive, 1: active, -1: both
            $parameterArray[] = &$rolestatus;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $roles = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            $stmt2 = $wpdb->dbh->prepare('SELECT @outvalue');
            $stmt2->execute();
            $myresult2 = $stmt2->get_result();
            $totalObjArr = $myresult2 === FALSE ? array() : $myresult2->fetch_all(MYSQLI_ASSOC);
            $stmt2->close();

            $total = "0";
            foreach ($totalObjArr[0] as $key => $value) {
                if($key === '@outvalue') {
                    $total = $value == null ? "0" : $value;
                }
            }
            foreach ($roles as $role) {
                foreach ($role as $key => $value) {
                    $role[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["role"] = $roles;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo wp_json_encode($result);
            exit();
        }
    }
    header("Content-Type: application/json");
    echo wp_json_encode("{}");
    exit();
}

add_action('wp_ajax_expenseszyx987_getTaxes', 'expenseszyx987_getTaxesByAjax');
function expenseszyx987_getTaxesByAjax() {
    check_ajax_referer('expenseszyx987_getTaxes', 'expenseszyx987_hidden_security_gettaxes');
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        header("Content-Type: application/json");
        echo wp_json_encode("{}");
        exit();
    }
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $storedprocedure_name = 'wp_expenseszyx987_getTaxList';

        $taxstatus = (!isset($_POST['taxstatus'])) ? '1' : strip_tags(sanitize_text_field($_POST['taxstatus']));
        $taxstatus = intval($taxstatus);

        $amountperpage = empty($_POST['amountperpage']) ? '10' : strip_tags(sanitize_text_field($_POST['amountperpage']));
        $amountperpage = intval($amountperpage);
        if($amountperpage === -1) {$amountperpage = 10;}

        $pagenumber = empty($_POST['pagenumber']) ? '1' : strip_tags(sanitize_text_field($_POST['pagenumber']));
        $pagenumber = intval($pagenumber);

        $myoffset = ($pagenumber - 1) * $amountperpage;

        $mysortby = empty($_POST['sortby']) ? '' : strip_tags(sanitize_text_field($_POST['sortby']));
        $mysortby = stripslashes(trim($mysortby));
        $mysortby = $mysortby === '' ? 'id' : $mysortby;

        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : strip_tags(sanitize_text_field($_POST['order']));
        $myorder = stripslashes(trim($myorder));
        $myorder = $myorder === '' ? 'asc' : $myorder;

        $searchwords = empty($_POST['searchwords']) ? '' : strip_tags(sanitize_text_field($_POST['searchwords']));
        $searchwords = stripslashes(trim($searchwords));

        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $query = "CALL " . $storedprocedure_name . "(?, ?, ?, ?, ?, ?, ?, @outvalue );";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 'i';
            $parameterArray[] = &$pagenumber;

            $types .= 'i';
            $parameterArray[] = &$amountperpage;

            $types .= 'i';
            $parameterArray[] = &$myoffset;

            $types .= 's';
            $parameterArray[] = &$mysortby;

            $types .= 's';
            $parameterArray[] = &$myorder;

            $types .= 's';
            $parameterArray[] = &$searchwords;

            $types .= 'i'; //0: inactive, 1: active, -1: both
            $parameterArray[] = &$taxstatus;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $taxes = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            $stmt2 = $wpdb->dbh->prepare('SELECT @outvalue');
            $stmt2->execute();
            $myresult2 = $stmt2->get_result();
            $totalObjArr = $myresult2 === FALSE ? array() : $myresult2->fetch_all(MYSQLI_ASSOC);
            $stmt2->close();
            $total = "0";
            foreach ($totalObjArr[0] as $key => $value) {
                if($key === '@outvalue') {
                    $total = $value == null ? "0" : $value;
                }
            }
            foreach ($taxes as $tax) {
                foreach ($tax as $key => $value) {
                    $tax[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["tax"] = $taxes;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo wp_json_encode($result);
            exit();
        }
    }
    header("Content-Type: application/json");
    echo wp_json_encode("{}");
    exit();
}

add_action('wp_ajax_expenseszyx987_getCurrencies', 'expenseszyx987_getCurrenciesByAjax');
function expenseszyx987_getCurrenciesByAjax() {
    check_ajax_referer('expenseszyx987_getCurrencies', 'expenseszyx987_hidden_security_getcurrencies');
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        header("Content-Type: application/json");
        echo wp_json_encode("{}");
        exit();
    }
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $storedprocedure_name = 'wp_expenseszyx987_getCurrencyList';

        $currencystatus = (!isset($_POST['currencystatus'])) ? '1' : strip_tags(sanitize_text_field($_POST['currencystatus']));
        $currencystatus = intval($currencystatus);

        $amountperpage = empty($_POST['amountperpage']) ? '10' : strip_tags(sanitize_text_field($_POST['amountperpage']));
        $amountperpage = intval($amountperpage);
        if($amountperpage === -1) {$amountperpage = 10;}

        $pagenumber = empty($_POST['pagenumber']) ? '1' : strip_tags(sanitize_text_field($_POST['pagenumber']));
        $pagenumber = intval($pagenumber);

        $myoffset = ($pagenumber - 1) * $amountperpage;

        $mysortby = empty($_POST['sortby']) ? '' : strip_tags(sanitize_text_field($_POST['sortby']));
        $mysortby = stripslashes(trim($mysortby));
        $mysortby = $mysortby === '' ? 'id' : $mysortby;

        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : strip_tags(sanitize_text_field($_POST['order']));
        $myorder = stripslashes(trim($myorder));
        $myorder = $myorder === '' ? 'asc' : $myorder;

        $searchwords = empty($_POST['searchwords']) ? '' : strip_tags(sanitize_text_field($_POST['searchwords']));
        $searchwords = stripslashes(trim($searchwords));

        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $query = "CALL " . $storedprocedure_name . "(?, ?, ?, ?, ?, ?, ?, @outvalue );";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 'i';
            $parameterArray[] = &$pagenumber;

            $types .= 'i';
            $parameterArray[] = &$amountperpage;

            $types .= 'i';
            $parameterArray[] = &$myoffset;

            $types .= 's';
            $parameterArray[] = &$mysortby;

            $types .= 's';
            $parameterArray[] = &$myorder;

            $types .= 's';
            $parameterArray[] = &$searchwords;

            $types .= 'i'; //0: inactive, 1: active, -1: both
            $parameterArray[] = &$currencystatus;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $currencies = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            $stmt2 = $wpdb->dbh->prepare('SELECT @outvalue');
            $stmt2->execute();
            $myresult2 = $stmt2->get_result();
            $totalObjArr = $myresult2 === FALSE ? array() : $myresult2->fetch_all(MYSQLI_ASSOC);
            $stmt2->close();
            $total = "0";
            foreach ($totalObjArr[0] as $key => $value) {
                if($key === '@outvalue') {
                    $total = $value == null ? "0" : $value;
                }
            }
            foreach ($currencies as $currency) {
                foreach ($currency as $key => $value) {
                    $currency[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["currency"] = $currencies;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo wp_json_encode($result);
            exit();
        }
    }
    header("Content-Type: application/json");
    echo wp_json_encode("{}");
    exit();
}

add_action('wp_ajax_expenseszyx987_getCustomertypes', 'expenseszyx987_getCustomertypesByAjax');
function expenseszyx987_getCustomertypesByAjax() {
    check_ajax_referer('expenseszyx987_getCustomertypes', 'expenseszyx987_hidden_security_getcustomertypes');
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        header("Content-Type: application/json");
        echo wp_json_encode("{}");
        exit();
    }
    if(!expenseszyx987_userCanReadInAdminPage()) {
        header("Content-Type: application/json");
        echo wp_json_encode("{}");
        exit();
    }
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $storedprocedure_name = 'wp_expenseszyx987_getCustomertypeList';

        $customertypestatus = (!isset($_POST['customertypestatus'])) ? '-1' : strip_tags(sanitize_text_field($_POST['customertypestatus']));
        $customertypestatus = intval($customertypestatus);

        $amountperpage = empty($_POST['amountperpage']) ? '10' : strip_tags(sanitize_text_field($_POST['amountperpage']));
        $amountperpage = intval($amountperpage);
        if($amountperpage === -1) {$amountperpage = 10;}

        $pagenumber = empty($_POST['pagenumber']) ? '1' : strip_tags(sanitize_text_field($_POST['pagenumber']));
        $pagenumber = intval($pagenumber);

        $myoffset = ($pagenumber - 1) * $amountperpage;

        $mysortby = empty($_POST['sortby']) ? '' : strip_tags(sanitize_text_field($_POST['sortby']));
        $mysortby = $mysortby === '' ? 'id' : $mysortby;

        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : strip_tags(sanitize_text_field($_POST['order']));
        $myorder = $myorder === '' ? 'asc' : $myorder;

        $searchwords = empty($_POST['searchwords']) ? '' : strip_tags(sanitize_text_field($_POST['searchwords']));

        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $query = "CALL " . $storedprocedure_name . "(?, ?, ?, ?, ?, ?, ?, @outvalue );";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 'i';
            $parameterArray[] = &$pagenumber;

            $types .= 'i';
            $parameterArray[] = &$amountperpage;

            $types .= 'i';
            $parameterArray[] = &$myoffset;

            $types .= 's';
            $parameterArray[] = &$mysortby;

            $types .= 's';
            $parameterArray[] = &$myorder;

            $types .= 's';
            $parameterArray[] = &$searchwords;

            $types .= 'i'; //0: inactive, 1: active, -1: both
            $parameterArray[] = &$customertypestatus;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $customertypes = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            $stmt2 = $wpdb->dbh->prepare('SELECT @outvalue');
            $stmt2->execute();
            $myresult2 = $stmt2->get_result();
            $totalObjArr = $myresult2 === FALSE ? array() : $myresult2->fetch_all(MYSQLI_ASSOC);
            $stmt2->close();

            $total = "0";
            foreach ($totalObjArr[0] as $key => $value) {
                if($key === '@outvalue') {
                    $total = $value == null ? "0" : $value;
                }
            }
            foreach ($customertypes as $customertype) {
                foreach ($customertype as $key => $value) {
                    $customertype[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["customertype"] = $customertypes;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo wp_json_encode($result);
            exit();
        }
    }
    header("Content-Type: application/json");
    echo wp_json_encode("{}");
    exit();
}

add_action('wp_ajax_expenseszyx987_getRecurringpaymentfrequencies', 'expenseszyx987_getRecurringpaymentfrequenciesByAjax');
function expenseszyx987_getRecurringpaymentfrequenciesByAjax() {
    check_ajax_referer('expenseszyx987_getRecurringpaymentfrequencies', 'expenseszyx987_hidden_security_getrecurringpaymentfrequencies');
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        header("Content-Type: application/json");
        echo wp_json_encode("{}");
        exit();
    }
    if(!expenseszyx987_userCanReadInAdminPage()) {
        header("Content-Type: application/json");
        echo wp_json_encode("{}");
        exit();
    }
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $storedprocedure_name = 'wp_expenseszyx987_getRecurringpaymentfrequencyList';

        $recurringpaymentfrequencystatus = (!isset($_POST['recurringpaymentfrequencystatus'])) ? '-1' : strip_tags(sanitize_text_field($_POST['recurringpaymentfrequencystatus']));
        $recurringpaymentfrequencystatus = intval($recurringpaymentfrequencystatus);

        $amountperpage = empty($_POST['amountperpage']) ? '10' : strip_tags(sanitize_text_field($_POST['amountperpage']));
        $amountperpage = intval($amountperpage);
        if($amountperpage === -1) {$amountperpage = 10;}

        $pagenumber = empty($_POST['pagenumber']) ? '1' : strip_tags(sanitize_text_field($_POST['pagenumber']));
        $pagenumber = intval($pagenumber);

        $myoffset = ($pagenumber - 1) * $amountperpage;

        $mysortby = empty($_POST['sortby']) ? '' : strip_tags(sanitize_text_field($_POST['sortby']));
        $mysortby = $mysortby === '' ? 'id' : $mysortby;

        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : strip_tags(sanitize_text_field($_POST['order']));
        $myorder = $myorder === '' ? 'asc' : $myorder;

        $searchwords = empty($_POST['searchwords']) ? '' : strip_tags(sanitize_text_field($_POST['searchwords']));

        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $query = "CALL " . $storedprocedure_name . "(?, ?, ?, ?, ?, ?, ?, @outvalue );";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 'i';
            $parameterArray[] = &$pagenumber;

            $types .= 'i';
            $parameterArray[] = &$amountperpage;

            $types .= 'i';
            $parameterArray[] = &$myoffset;

            $types .= 's';
            $parameterArray[] = &$mysortby;

            $types .= 's';
            $parameterArray[] = &$myorder;

            $types .= 's';
            $parameterArray[] = &$searchwords;

            $types .= 'i'; //0: inactive, 1: active, -1: both
            $parameterArray[] = &$recurringpaymentfrequencystatus;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $recurringpaymentfrequencies = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            $stmt2 = $wpdb->dbh->prepare('SELECT @outvalue');
            $stmt2->execute();
            $myresult2 = $stmt2->get_result();
            $totalObjArr = $myresult2 === FALSE ? array() : $myresult2->fetch_all(MYSQLI_ASSOC);
            $stmt2->close();

            $total = "0";
            foreach ($totalObjArr[0] as $key => $value) {
                if($key === '@outvalue') {
                    $total = $value == null ? "0" : $value;
                }
            }
            foreach ($recurringpaymentfrequencies as $recurringpaymentfrequency) {
                foreach ($recurringpaymentfrequency as $key => $value) {
                    $recurringpaymentfrequency[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["recurringpaymentfrequency"] = $recurringpaymentfrequencies;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo wp_json_encode($result);
            exit();
        }
    }
    header("Content-Type: application/json");
    echo wp_json_encode("{}");
    exit();
}

add_action('wp_ajax_expenseszyx987_getCustomers', 'expenseszyx987_getCustomersByAjax');
function expenseszyx987_getCustomersByAjax() {
    check_ajax_referer('expenseszyx987_getCustomers', 'expenseszyx987_hidden_security_getcustomers');
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        header("Content-Type: application/json");
        echo wp_json_encode("{}");
        exit();
    }
    if(!expenseszyx987_userCanReadInAdminPage()) {
        header("Content-Type: application/json");
        echo wp_json_encode("{}");
        exit();
    }
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $storedprocedure_name = 'wp_expenseszyx987_getCustomerList';

        $customerstatus = (!isset($_POST['customerstatus'])) ? '-1' : strip_tags(sanitize_text_field($_POST['customerstatus']));
        $customerstatus = intval($customerstatus);

        $amountperpage = empty($_POST['amountperpage']) ? '10' : strip_tags(sanitize_text_field($_POST['amountperpage']));
        $amountperpage = intval($amountperpage);
        if($amountperpage === -1) {$amountperpage = 10;}

        $pagenumber = empty($_POST['pagenumber']) ? '1' : strip_tags(sanitize_text_field($_POST['pagenumber']));
        $pagenumber = intval($pagenumber);

        $myoffset = ($pagenumber - 1) * $amountperpage;

        $mysortby = empty($_POST['sortby']) ? '' : strip_tags(sanitize_text_field($_POST['sortby']));
        $mysortby = $mysortby === '' ? 'id' : $mysortby;

        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : strip_tags(sanitize_text_field($_POST['order']));
        $myorder = $myorder === '' ? 'asc' : $myorder;

        $searchwords = empty($_POST['searchwords']) ? '' : strip_tags(sanitize_text_field($_POST['searchwords']));

        $customertypeid = empty($_POST['customertypeid']) ? '-1' : strip_tags(sanitize_text_field($_POST['customertypeid']));
        $customertypeid = intval($customertypeid);

        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $query = "CALL " . $storedprocedure_name . "(?, ?, ?, ?, ?, ?, ?, ?, @outvalue );";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 'i';
            $parameterArray[] = &$pagenumber;

            $types .= 'i';
            $parameterArray[] = &$amountperpage;

            $types .= 'i';
            $parameterArray[] = &$myoffset;

            $types .= 's';
            $parameterArray[] = &$mysortby;

            $types .= 's';
            $parameterArray[] = &$myorder;

            $types .= 's';
            $parameterArray[] = &$searchwords;

            $types .= 'i';
            $parameterArray[] = &$customertypeid;

            $types .= 'i'; //0: inactive, 1: active, -1: both
            $parameterArray[] = &$customerstatus;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $customers = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            $stmt2 = $wpdb->dbh->prepare('SELECT @outvalue');
            $stmt2->execute();
            $myresult2 = $stmt2->get_result();
            $totalObjArr = $myresult2 === FALSE ? array() : $myresult2->fetch_all(MYSQLI_ASSOC);
            $stmt2->close();

            $total = "0";
            foreach ($totalObjArr[0] as $key => $value) {
                if($key === '@outvalue') {
                    $total = $value == null ? "0" : $value;
                }
            }
            foreach ($customers as $customer) {
                foreach ($customer as $key => $value) {
                    $customer[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["customer"] = $customers;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo wp_json_encode($result);
            exit();
        }
    }
    header("Content-Type: application/json");
    echo wp_json_encode("{}");
    exit();
}

add_action('wp_ajax_expenseszyx987_getDepartments', 'expenseszyx987_getDepartmentsByAjax');
function expenseszyx987_getDepartmentsByAjax() {
    check_ajax_referer('expenseszyx987_getDepartments', 'expenseszyx987_hidden_security_getdepartments');
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        header("Content-Type: application/json");
        echo wp_json_encode("{}");
        exit();
    }
    if(!expenseszyx987_userCanReadInAdminPage()) {
        header("Content-Type: application/json");
        echo wp_json_encode("{}");
        exit();
    }
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $storedprocedure_name = 'wp_expenseszyx987_getDepartmentList';

        $departmentstatus = (!isset($_POST['departmentstatus'])) ? '-1' : strip_tags(sanitize_text_field($_POST['departmentstatus']));
        $departmentstatus = intval($departmentstatus);

        $amountperpage = empty($_POST['amountperpage']) ? '10' : strip_tags(sanitize_text_field($_POST['amountperpage']));
        $amountperpage = intval($amountperpage);
        if($amountperpage === -1) {$amountperpage = 10;}

        $pagenumber = empty($_POST['pagenumber']) ? '1' : strip_tags(sanitize_text_field($_POST['pagenumber']));
        $pagenumber = intval($pagenumber);

        $myoffset = ($pagenumber - 1) * $amountperpage;

        $mysortby = empty($_POST['sortby']) ? '' : strip_tags(sanitize_text_field($_POST['sortby']));
        $mysortby = $mysortby === '' ? 'id' : $mysortby;

        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : strip_tags(sanitize_text_field($_POST['order']));
        $myorder = $myorder === '' ? 'asc' : $myorder;

        $searchwords = empty($_POST['searchwords']) ? '' : strip_tags(sanitize_text_field($_POST['searchwords']));

        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $query = "CALL " . $storedprocedure_name . "(?, ?, ?, ?, ?, ?, ?, @outvalue );";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 'i';
            $parameterArray[] = &$pagenumber;

            $types .= 'i';
            $parameterArray[] = &$amountperpage;

            $types .= 'i';
            $parameterArray[] = &$myoffset;

            $types .= 's';
            $parameterArray[] = &$mysortby;

            $types .= 's';
            $parameterArray[] = &$myorder;

            $types .= 's';
            $parameterArray[] = &$searchwords;

            $types .= 'i'; //0: inactive, 1: active, -1: both
            $parameterArray[] = &$departmentstatus;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $departments = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            $stmt2 = $wpdb->dbh->prepare('SELECT @outvalue');
            $stmt2->execute();
            $myresult2 = $stmt2->get_result();
            $totalObjArr = $myresult2 === FALSE ? array() : $myresult2->fetch_all(MYSQLI_ASSOC);
            $stmt2->close();

            $total = "0";
            foreach ($totalObjArr[0] as $key => $value) {
                if($key === '@outvalue') {
                    $total = $value == null ? "0" : $value;
                }
            }
            foreach ($departments as $department) {
                foreach ($department as $key => $value) {
                    $department[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["department"] = $departments;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo wp_json_encode($result);
            exit();
        }
    }
    header("Content-Type: application/json");
    echo wp_json_encode("{}");
    exit();
}

add_action('wp_ajax_expenseszyx987_getConstants', 'expenseszyx987_getConstantsByAjax');
function expenseszyx987_getConstantsByAjax() {
    check_ajax_referer('expenseszyx987_getConstants', 'expenseszyx987_hidden_security_getconstants');
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        header("Content-Type: application/json");
        echo wp_json_encode("{}");
        exit();
    }
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        $startDate = empty($_POST['start']) ? '' : strip_tags(sanitize_text_field($_POST['start']));
        $startDate = sanitize_text_field(str_ireplace("T"," ",$startDate));
        $startDate = sanitize_text_field(str_ireplace("Z","",$startDate));

        $endDate = empty($_POST['end']) ? '' : strip_tags(sanitize_text_field($_POST['end']));
        $endDate = sanitize_text_field(str_ireplace("T"," ",$endDate));
        $endDate = sanitize_text_field(str_ireplace("Z","",$endDate));

        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987_constant';
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $query = "SELECT * FROM $table_name;";
            $stmt = $wpdb->dbh->prepare($query);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $constants = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            $counter = 0;
            foreach ($constants as $constant) {
                $found = false;
                foreach ($constant as $key => $value) {
                    $constant[$key] = $value === null ? '' : deslash($value);
                    if($key === 'name' && $value === 'DBBACKUP_DETAILS') {
                        $found = true;
                    }// elseif($key === 'name' && $value === 'COMPANY_TIMEZONE' && $constants[$counter]['value'] !== null && $constants[$counter]['value'] !== '') {
                        //date_default_timezone_set($constants[$counter]['value']);
                        //$timezone = $constants[$counter]['value'];
                    //}
                }
                if($found) {
                    if($constant['value'] !== null && $constant['value'] !== '') {
                        $constants[$counter]['value'] = 'HAS VALUE';
                    }
                }
                $counter++;
            }
            $result = [];
            $result["total"] = count($constants);
            $result["constant"] = $constants;
            header("Content-Type: application/json");
            echo wp_json_encode($result);
            exit();
        }
    }
    header("Content-Type: application/json");
    echo wp_json_encode("{}");
    exit();
}

add_action('wp_ajax_expenseszyx987_getLogs', 'expenseszyx987_getLogsByAjax');
function expenseszyx987_getLogsByAjax() {
    check_ajax_referer('expenseszyx987_getLogs', 'expenseszyx987_hidden_security_getlogs');
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        header("Content-Type: application/json");
        echo wp_json_encode("{}");
        exit();
    }
    if(!expenseszyx987_userCanReadInAdminPage()) {
        header("Content-Type: application/json");
        echo wp_json_encode("{}");
        exit();
    }
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

        $table_name = 'wp_expenseszyx987_log';
        $storedprocedure_name = 'wp_expenseszyx987_getLogList';

        $logstatus = (!isset($_POST['logstatus'])) ? '1' : strip_tags(sanitize_text_field($_POST['logstatus']));
        $logstatus = intval($logstatus);

        $amountperpage = empty($_POST['amountperpage']) ? '10' : strip_tags(sanitize_text_field($_POST['amountperpage']));
        $amountperpage = intval($amountperpage);
        if($amountperpage === -1) {$amountperpage = 10;}

        $pagenumber = empty($_POST['pagenumber']) ? '1' : strip_tags(sanitize_text_field($_POST['pagenumber']));
        $pagenumber = intval($pagenumber);

        $myoffset = ($pagenumber - 1) * $amountperpage;

        $mysortby = empty($_POST['sortby']) ? '' : strip_tags(sanitize_text_field($_POST['sortby']));
        $mysortby = $mysortby === '' ? 'id' : $mysortby;

        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : strip_tags(sanitize_text_field($_POST['order']));
        $myorder = $myorder === '' ? 'desc' : $myorder;

        $searchwords = empty($_POST['searchwords']) ? '' : strip_tags(sanitize_text_field($_POST['searchwords']));

        $searchtype_temp = (!isset($_POST['searchtype'])) ? '' : strip_tags(sanitize_text_field($_POST['searchtype']));
        $searchtype = $searchtype_temp;
        if($searchtype === '-1') {$searchtype = "";}

        $processname_temp = (!isset($_POST['processname'])) ? '' : strip_tags(sanitize_text_field($_POST['processname']));
        $processname = $processname_temp;
        if($processname === '-1') {$processname = "";}

        $userid_temp = (!isset($_POST['userid'])) ? '0' : strip_tags(sanitize_text_field($_POST['userid']));
        $userid = intval($userid_temp);
        if($userid === -1) {$userid = 0;}

        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $query = "CALL " . $storedprocedure_name . "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, @outvalue );";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 'i';
            $parameterArray[] = &$pagenumber;

            $types .= 'i';
            $parameterArray[] = &$amountperpage;

            $types .= 'i';
            $parameterArray[] = &$myoffset;

            $types .= 's';
            $parameterArray[] = &$mysortby;

            $types .= 's';
            $parameterArray[] = &$myorder;

            $types .= 's';
            $parameterArray[] = &$searchwords;

            $types .= 's';
            $parameterArray[] = &$searchtype;

            $types .= 's';
            $parameterArray[] = &$processname;

            $types .= 'i';
            $parameterArray[] = &$userid;

            $types .= 'i'; //0: inactive, 1: active, -1: both
            $parameterArray[] = &$logstatus;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $logs = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            $stmt2 = $wpdb->dbh->prepare('SELECT @outvalue');
            $stmt2->execute();
            $myresult2 = $stmt2->get_result();
            $totalObjArr = $myresult2 === FALSE ? array() : $myresult2->fetch_all(MYSQLI_ASSOC);
            $stmt2->close();
            $total = "0";
            foreach ($totalObjArr[0] as $key => $value) {
                if($key === '@outvalue') {
                    $total = $value == null ? "0" : $value;
                }
            }
            foreach ($logs as $log) {
                foreach ($log as $key => $value) {
                    $log[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["log"] = $logs;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo wp_json_encode($result);
            exit();
        }
    }
    header("Content-Type: application/json");
    echo wp_json_encode("{}");
    exit();
}

function expenseszyx987_setCookie_not_by_ajax() {
    check_ajax_referer('expenseszyx987_createcookie', 'expenseszyx987_hidden_security_createcookie');
    if((!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        $value = empty($_POST['expenseszyx987_orderitems']) ? '' : sanitize_text_field($_POST['expenseszyx987_orderitems']);
        $value = strip_tags($value);
        $value = expenseszyx987_stripAllBackSlashes($value); 

        $expenseszyx987_orderitems = empty($_POST['expenseszyx987_orderitems']) ? '' : sanitize_text_field($_POST['expenseszyx987_orderitems']);
        $_SESSION['expenseszyx987_orderitems'] = $expenseszyx987_orderitems;
        $setcookieresult = setcookie('expenseszyx987_orderitems', expenseszyx987_stripAllBackSlashes($expenseszyx987_orderitems), 0, '/', '', true, true);
        if($setcookieresult) {
            return "success";
        } else {
            return "Set cookie failed.";
        }
    }
    return "Invalid details. Cookie is not set.";
}

function expenseszyx987_sanitizeEmailAddress($v) {
    return sanitize_email($v);
}

function expenseszyx987_sanitizeEmailAddressAndPassword($v) {
    $temp = explode("|", $v);
    return sanitize_email($temp[0]) . '|' . sanitize_text_field($temp[1]);
}

function expenseszyx987_reloadPageAfterPost() {
    echo "<meta http-equiv='refresh' content='0'>";
    exit();
}

function expenseszyx987_getConstantRowPerTable() {
    global $wpdb; global $dragon_expense_dbResult;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_expenseszyx987_constant';
    $result = $wpdb->get_var("SELECT value FROM $table_name WHERE name = 'AMOUNT_PER_PAGE'");
    return $result === null ? 0 : intval($result);
}

function expenseszyx987_dropConstantTable() {
    global $dragon_expense_dbResult;
    $mynonce = empty($_POST['expenseszyx987_hidden_security']) ? '' : strip_tags(sanitize_text_field($_POST['expenseszyx987_hidden_security']));
    if(wp_verify_nonce($mynonce, 'expenseszyx987_dropConstantTable') !== 1) {$dragon_expense_dbResult .= 'Invalid data. ';return;}
    $current_user = wp_get_current_user();    
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        $dragon_expense_dbResult .= 'Invalid user info.';
        return;
    }
    if(!expenseszyx987_userCanEditInAdminPage()) {
        $dragon_expense_dbResult .= 'You are not authorized to edit data in admin page. Please contact web admin.';
        return;
    }
    if(in_array('administrator', (array) $current_user->roles) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_constant;";
        $wpdb->query($sql);
        expenseszyx987_createTable_constant();
        $dragon_expense_dbResult .= 'Success.';
    } else {
        $dragon_expense_dbResult .= 'Invalid data.';
    }
}

function expenseszyx987_dropDepartmentTable() {
    global $dragon_expense_dbResult;
    $mynonce = empty($_POST['expenseszyx987_hidden_security']) ? '' : strip_tags(sanitize_text_field($_POST['expenseszyx987_hidden_security']));
    if(wp_verify_nonce($mynonce, 'expenseszyx987_dropDepartmentTable') !== 1) {$dragon_expense_dbResult .= 'Invalid data. ';return;}
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        $dragon_expense_dbResult .= 'Invalid user info.';
        return;
    }
    if(!expenseszyx987_userCanEditInAdminPage()) {
        $dragon_expense_dbResult .= 'You are not authorized to edit data in admin page. Please contact web admin.';
        return;
    }
    if(in_array('administrator', (array) $current_user->roles) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_department;";
        $wpdb->query($sql);
        expenseszyx987_createTable_department();
        $dragon_expense_dbResult .= 'Success.';
    } else {
        $dragon_expense_dbResult .= 'Invalid data.';
    }
}

function expenseszyx987_dropLogTable() {
    global $dragon_expense_dbResult;
    $mynonce = empty($_POST['expenseszyx987_hidden_security']) ? '' : strip_tags(sanitize_text_field($_POST['expenseszyx987_hidden_security']));
    if(wp_verify_nonce($mynonce, 'expenseszyx987_dropLogTable') !== 1) {$dragon_expense_dbResult .= 'Invalid data. ';return;}
    $current_user = wp_get_current_user();    
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        $dragon_expense_dbResult .= 'Invalid user info.';
        return;
    }
    if(!expenseszyx987_userCanEditInAdminPage()) {
        $dragon_expense_dbResult .= 'You are not authorized to edit data in admin page. Please contact web admin.';
        return;
    }
    if(in_array('administrator', (array) $current_user->roles) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_log;";
        $wpdb->query($sql);
        expenseszyx987_createTable_log();
        $dragon_expense_dbResult .= 'Success.';
    } else {
        $dragon_expense_dbResult .= 'Invalid data.';
    }
}

function expenseszyx987_dropLogCreateNewLogTable() {
    global $dragon_expense_dbResult;
    $mynonce = empty($_POST['expenseszyx987_hidden_security']) ? '' : strip_tags(sanitize_text_field($_POST['expenseszyx987_hidden_security']));
    if(wp_verify_nonce($mynonce, 'expenseszyx987_dropLogCreateNewLogTable') !== 1) {$dragon_expense_dbResult .= 'Invalid data. ';return;}
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        $dragon_expense_dbResult .= 'Invalid user info.';
        return;
    }
    if(!expenseszyx987_userCanEditInAdminPage()) {
        $dragon_expense_dbResult .= 'You are not authorized to edit data in admin page. Please contact web admin.';
        return;
    }    
    if(in_array('administrator', (array) $current_user->roles) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_log;";
        $wpdb->query($sql);
        expenseszyx987_createTable_log();
        $dragon_expense_dbResult .= 'Success.';
    } else {
        $dragon_expense_dbResult .= 'Invalid data.';
    }
}

function expenseszyx987_dropRoleTable() {
    global $dragon_expense_dbResult;
    $mynonce = empty($_POST['expenseszyx987_hidden_security']) ? '' : strip_tags(sanitize_text_field($_POST['expenseszyx987_hidden_security']));
    if(wp_verify_nonce($mynonce, 'expenseszyx987_dropRoleTable') !== 1) {$dragon_expense_dbResult .= 'Invalid data. ';return;}
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        $dragon_expense_dbResult .= 'Invalid user info.';
        return;
    }
    if(!expenseszyx987_userCanEditInAdminPage()) {
        $dragon_expense_dbResult .= 'You are not authorized to edit data in admin page. Please contact web admin.';
        return;
    }
    if(in_array('administrator', (array) $current_user->roles) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_role;";
        $wpdb->query($sql);
        expenseszyx987_createTable_role();
        $dragon_expense_dbResult .= 'Success.';
    } else {
        $dragon_expense_dbResult .= 'Invalid data.';
    }
}

function expenseszyx987_dropRecurringpaymentfrequencyTable() {
    global $dragon_expense_dbResult;
    $mynonce = empty($_POST['expenseszyx987_hidden_security']) ? '' : strip_tags(sanitize_text_field($_POST['expenseszyx987_hidden_security']));
    if(wp_verify_nonce($mynonce, 'expenseszyx987_dropRecurringpaymentfrequencyTable') !== 1) {$dragon_expense_dbResult .= 'Invalid data. ';return;}
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        $dragon_expense_dbResult .= 'Invalid user info.';
        return;
    }
    if(!expenseszyx987_userCanEditInAdminPage()) {
        $dragon_expense_dbResult .= 'You are not authorized to edit data in admin page. Please contact web admin.';
        return;
    }    
    if(in_array('administrator', (array) $current_user->roles) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_recurringpaymentfrequency;";
        $wpdb->query($sql);
        expenseszyx987_createTable_recurringpaymentfrequency();
        $dragon_expense_dbResult .= 'Success.';
    } else {
        $dragon_expense_dbResult .= 'Invalid data.';
    }
}

function expenseszyx987_dropCurrencyTable() {
    global $dragon_expense_dbResult;
    $mynonce = empty($_POST['expenseszyx987_hidden_security']) ? '' : strip_tags(sanitize_text_field($_POST['expenseszyx987_hidden_security']));
    if(wp_verify_nonce($mynonce, 'expenseszyx987_dropCurrencyTable') !== 1) {$dragon_expense_dbResult .= 'Invalid data. ';return;}
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        $dragon_expense_dbResult .= 'Invalid user info.';
        return;
    }
    if(!expenseszyx987_userCanEditInAdminPage()) {
        $dragon_expense_dbResult .= 'You are not authorized to edit data in admin page. Please contact web admin.';
        return;
    }    
    if(in_array('administrator', (array) $current_user->roles) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_currency;";
        $wpdb->query($sql);
        expenseszyx987_createTable_currency();
        $dragon_expense_dbResult .= 'Success.';
    } else {
        $dragon_expense_dbResult .= 'Invalid data.';
    }
}

function expenseszyx987_dropTaxrateTable() {
    global $dragon_expense_dbResult;
    $mynonce = empty($_POST['expenseszyx987_hidden_security']) ? '' : strip_tags(sanitize_text_field($_POST['expenseszyx987_hidden_security']));
    if(wp_verify_nonce($mynonce, 'expenseszyx987_dropTaxrateTable') !== 1) {$dragon_expense_dbResult .= 'Invalid data. ';return;}
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        $dragon_expense_dbResult .= 'Invalid user info.';
        return;
    }
    if(!expenseszyx987_userCanEditInAdminPage()) {
        $dragon_expense_dbResult .= 'You are not authorized to edit data in admin page. Please contact web admin.';
        return;
    }
    if(in_array('administrator', (array) $current_user->roles) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_tax;";
        $wpdb->query($sql);
        expenseszyx987_createTable_tax();
        $dragon_expense_dbResult .= 'Success.';
    } else {
        $dragon_expense_dbResult .= 'Invalid data.';
    }
}

function expenseszyx987_dropExpenseTable() {
    global $dragon_expense_dbResult;
    $mynonce = empty($_POST['expenseszyx987_hidden_security']) ? '' : strip_tags(sanitize_text_field($_POST['expenseszyx987_hidden_security']));
    if(wp_verify_nonce($mynonce, 'expenseszyx987_dropExpenseTable') !== 1) {$dragon_expense_dbResult .= 'Invalid data. ';return;}
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        $dragon_expense_dbResult .= 'Invalid user info.';
        return;
    }
    if(!expenseszyx987_userCanEditInAdminPage()) {
        $dragon_expense_dbResult .= 'You are not authorized to edit data in admin page. Please contact web admin.';
        return;
    }    
    if(in_array('administrator', (array) $current_user->roles) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_expense;";
        $wpdb->query($sql);
        expenseszyx987_createTable_expense();
        $dragon_expense_dbResult .= 'Success.';
    } else {
        $dragon_expense_dbResult .= 'Invalid data.';
    }
}

function expenseszyx987_dropTypeTable() {
    global $dragon_expense_dbResult;
    $mynonce = empty($_POST['expenseszyx987_hidden_security']) ? '' : strip_tags(sanitize_text_field($_POST['expenseszyx987_hidden_security']));
    if(wp_verify_nonce($mynonce, 'expenseszyx987_dropTypeTable') !== 1) {$dragon_expense_dbResult .= 'Invalid data. ';return;}
    $current_user = wp_get_current_user();    
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        $dragon_expense_dbResult .= 'Invalid user info.';
        return;
    }
    if(!expenseszyx987_userCanEditInAdminPage()) {
        $dragon_expense_dbResult .= 'You are not authorized to edit data in admin page. Please contact web admin.';
        return;
    }
    if(in_array('administrator', (array) $current_user->roles) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_type;";
        $wpdb->query($sql);
        expenseszyx987_createTable_type();
        $dragon_expense_dbResult .= 'Success.';
    } else {
        $dragon_expense_dbResult .= 'Invalid data.';
    }
}

function expenseszyx987_dropTypecategoryTable() {
    global $dragon_expense_dbResult;
    $mynonce = empty($_POST['expenseszyx987_hidden_security']) ? '' : strip_tags(sanitize_text_field($_POST['expenseszyx987_hidden_security']));
    if(wp_verify_nonce($mynonce, 'expenseszyx987_dropTypecategoryTable') !== 1) {$dragon_expense_dbResult .= 'Invalid data. ';return;}
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        $dragon_expense_dbResult .= 'Invalid user info.';
        return;
    }
    if(!expenseszyx987_userCanEditInAdminPage()) {
        $dragon_expense_dbResult .= 'You are not authorized to edit data in admin page. Please contact web admin.';
        return;
    }
    if(in_array('administrator', (array) $current_user->roles) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_typecategory;";
        $wpdb->query($sql);
        expenseszyx987_createTable_typecategory();
        $dragon_expense_dbResult .= 'Success.';
    } else {
        $dragon_expense_dbResult .= 'Invalid data.';
    }
}

function expenseszyx987_dropUsersTable() {
    global $dragon_expense_dbResult;
    $mynonce = empty($_POST['expenseszyx987_hidden_security']) ? '' : strip_tags(sanitize_text_field($_POST['expenseszyx987_hidden_security']));
    if(wp_verify_nonce($mynonce, 'expenseszyx987_dropUsersTable') !== 1) {$dragon_expense_dbResult .= 'Invalid data. ';return;}
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        $dragon_expense_dbResult .= 'Invalid user info.';
        return;
    }
    if(!expenseszyx987_userCanEditInAdminPage()) {
        $dragon_expense_dbResult .= 'You are not authorized to edit data in admin page. Please contact web admin.';
        return;
    }
    if(in_array('administrator', (array) $current_user->roles) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_users;";
        $wpdb->query($sql);
        expenseszyx987_createTable_users();
        $dragon_expense_dbResult .= 'Success.';
    } else {
        $dragon_expense_dbResult .= 'Invalid data.';
    }
}

//Drop and create all stored procedures
function expenseszyx987_dropAllStoredprocedures() {
    global $dragon_expense_dbResult;
    $mynonce = empty($_POST['expenseszyx987_hidden_security']) ? '' : strip_tags(sanitize_text_field($_POST['expenseszyx987_hidden_security']));
    if(wp_verify_nonce($mynonce, 'expenseszyx987_dropAllStoredprocedures') !== 1) {$dragon_expense_dbResult .= 'Invalid data. ';return;}
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        $dragon_expense_dbResult .= 'Invalid user info.';
        return;
    }
    if(!expenseszyx987_userCanEditInAdminPage()) {
        $dragon_expense_dbResult .= 'You are not authorized to edit data in admin page. Please contact web admin.';
        return;
    }
    if(in_array('administrator', (array) $current_user->roles) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        expenseszyx987_createStoredProcedure();
        $dragon_expense_dbResult .= 'Success.';
    } else {
        $dragon_expense_dbResult .= 'Invalid data.';
    }
}

function expenseszyx987_dropAllTables() {
    global $dragon_expense_dbResult;
    $mynonce = empty($_POST['expenseszyx987_hidden_security']) ? '' : strip_tags(sanitize_text_field($_POST['expenseszyx987_hidden_security']));
    if(wp_verify_nonce($mynonce, 'expenseszyx987_dropAllTables') !== 1) {$dragon_expense_dbResult .= 'Invalid data. ';return;}
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        $dragon_expense_dbResult .= 'Invalid user info.';
        return;
    }
    if(!expenseszyx987_userCanEditInAdminPage()) {
        $dragon_expense_dbResult .= 'You are not authorized to edit data in admin page. Please contact web admin.';
        return;
    }
    if(in_array('administrator', (array) $current_user->roles) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_constant;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_department;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_log;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_role;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_recurringpaymentfrequency;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_currency;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_tax;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_customertype;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_customer;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_expense;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_type;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_typecategory;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_user_type;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_users;";
        $wpdb->query($sql);

        expenseszyx987_createTable_constant();
        expenseszyx987_createTable_department();
        expenseszyx987_createTable_log();
        expenseszyx987_createTable_role();
        expenseszyx987_createTable_recurringpaymentfrequency();
        expenseszyx987_createTable_currency();
        expenseszyx987_createTable_tax();
        expenseszyx987_createTable_customertype();
        expenseszyx987_createTable_customer();
        expenseszyx987_createTable_expense();
        expenseszyx987_createTable_typecategory();
        expenseszyx987_createTable_type();
        expenseszyx987_createTable_users();
        expenseszyx987_additional_creation();

        $dragon_expense_dbResult .= 'Success.';
    } else {
        $dragon_expense_dbResult .= 'Invalid data.';
    }
}

function expenseszyx987_showLandingPage() {
    require_once dirname(__FILE__) . '/' . "expenseszyx987_landingpage.php";
}

function expenseszyx987_saveToLogTable($message, $processname  = '', $type = 'info', $userid = null) {
    global $wpdb;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    if(!expenseszyx987_userCanEditInAdminPage()) {
        return 'You are not authorized to edit data in admin page. Please contact web admin.';
    }
    if($wpdb->use_mysqli) {
        if($wpdb->dbh->connect_error) {
            return "Connection failed: " . esc_html($wpdb->dbh->connect_error);
        }
        $table_name = 'wp_expenseszyx987_log';
        if($userid === null){
            $query = "INSERT INTO " . $table_name . " (`processname`,`type`,`description`,`createtimeutc`) VALUES (?,?,?,UTC_TIMESTAMP())";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 's';
            $parameterArray[] = &$processname;

            $types .= 's';
            $parameterArray[] = &$type;

            $types .= 's';
            $parameterArray[] = &$message;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->insert_id;
            $stmt->close();
            if($myresult <= 0) {
                return 'Error adding a message into table ' . $table_name . ". ";
            }
            return 'Success';
        } else {
            $query = "INSERT INTO " . $table_name . " (`processname`,`userid`,`type`,`description`,`createtimeutc`) VALUES (?,?,?,?,UTC_TIMESTAMP())";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 's';
            $parameterArray[] = &$processname;

            $types .= 'i';
            $userid2 = intval($userid);
            $parameterArray[] = &$userid2;

            $types .= 's';
            $parameterArray[] = &$type;

            $types .= 's';
            $parameterArray[] = &$message;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->insert_id;
            $stmt->close();
            if($myresult <= 0) {
                return 'Error adding a message into table ' . $table_name . ". ";
            }
            return 'Success';
        }
    }
    return 'Mysqli is not supported.';
}

function expenseszyx987_getAllLogtypesProcessnamesUserids($onlyActive = true) {
    global $wpdb; global $dragon_expense_dbResult; $results = array();
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    if(!expenseszyx987_userCanReadInAdminPage()) {
        return array();
    }
    $table_name = 'wp_expenseszyx987_log';
    if($onlyActive) {
        $results["type"] = $wpdb->get_results("SELECT distinct type from $table_name WHERE type is not null and status = 1 order by type");
    } else {
        $results["type"] = $wpdb->get_results("SELECT distinct type from $table_name WHERE type is not null order by type");
    }
    foreach($results["type"] as $result) {
        foreach($result as $key => $value) {
            $result->$key = deslash($value);
        }
    }

    if($onlyActive) {
        $results["processname"] = $wpdb->get_results("SELECT distinct processname from $table_name WHERE processname is not null and status = 1 order by processname");
    } else {
        $results["processname"] = $wpdb->get_results("SELECT distinct processname from $table_name WHERE processname is not null order by processname");
    }
    foreach($results["processname"] as $result) {
        foreach($result as $key => $value) {
            $result->$key = deslash($value);
        }
    }

    if($onlyActive) {
        $results["userid"] = $wpdb->get_results("SELECT distinct userid from $table_name WHERE userid is not null and status = 1 order by userid");
    } else {
        $results["userid"] = $wpdb->get_results("SELECT distinct userid from $table_name WHERE userid is not null order by userid");
    }
    foreach($results["userid"] as $result) {
        foreach($result as $key => $value) {
            $result->$key = deslash($value);
        }
    }
    return $results;
}

function expenseszyx987_cron_encrypt_decrypt($action, $string) {
    $output = false;
    if(!expenseszyx987_userCanEditInAdminPage()) {
        return $output;
    }
    $encrypt_method = "AES-256-CBC";
    $secret_key = 'a9j2F1t7Y2h8U5t6M8s3V9W1o3Q7C9d5';
    $secret_iv = 'b2yt59G17pa6V92X';
    $key = hash('sha256', $secret_key);
    $iv = substr(hash('sha256', $secret_iv), 0, 16);
    if($action == 'encrypt') {
        $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
        $output = base64_encode($output);
    } elseif($action == 'decrypt') {
        $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
    }
    return $output;
}

add_action('expenseszyx987_cron_dbbackup_hook', 'expenseszyx987_cron_dbbackup');
function expenseszyx987_cron_dbbackup() {
    global $wpdb;
    if(!expenseszyx987_userCanEditInAdminPage()) {
        $message = 'You are not authorized to edit data in admin page. Please contact web admin.';
        expenseszyx987_saveToLogTable($message, 'Enable cron db auto backup', 'error');
        return;
    }
    $table_name = 'wp_expenseszyx987_constant';
    $backupdetails = $wpdb->get_var("SELECT value FROM " . $table_name . " WHERE name = 'DBBACKUP_DETAILS' and status = 1 LIMIT 1");
    if(!empty($backupdetails)) {
        $backupdetails = expenseszyx987_cron_encrypt_decrypt('decrypt', $backupdetails);
        if($backupdetails !== '') {
            //$timezone = $wpdb->get_var("SELECT value FROM $table_name WHERE name = 'COMPANY_TIMEZONE'");
            //if($timezone !== '') {
            //    date_default_timezone_set($timezone);
            //}
            //$timezone=get_option('timezone_string');
            //if(!empty($timezone)){date_default_timezone_set($timezone);}
            $backupdetails = str_replace('CURRENT_DATE', date('YmdHis'), $backupdetails);
            expenseszyx987_saveToLogTable($backupdetails, 'cron db auto backup backupdetails', 'info');
            system($backupdetails, $myoutput);
            if($myoutput === false || $myoutput === null) {
                $pattern = '/--password=\S+/i';
                $replacement = "--password=xxxxxx";
                $backupdetails_temp = preg_replace($pattern, $replacement, $backupdetails);
                $message = "Enable cron db auto backup error: command: " . $backupdetails_temp;
                expenseszyx987_saveToLogTable($message, 'Enable cron db auto backup', 'error');
            }
        }
    }
}

//daily
function expenseszyx987_myprefix_custom_cron_scheduledaily( $schedules ) {
    $schedules['every_day'] = array(
        'interval' => 86400, // Every 24 hours
        'display'  => __( 'Every day' ),
    );
    return $schedules;
}
add_filter( 'cron_schedules', 'expenseszyx987_myprefix_custom_cron_scheduledaily' );

//weekly
function expenseszyx987_myprefix_custom_cron_scheduleweekly( $schedules ) {
    $schedules['every_week'] = array(
        'interval' => 604800, // Every week
        'display'  => __( 'Every week' ),
    );
    return $schedules;
}
add_filter( 'cron_schedules', 'expenseszyx987_myprefix_custom_cron_scheduleweekly' );

//twice daily
function expenseszyx987_myprefix_custom_cron_scheduletwicedaily( $schedules ) {
    $schedules['every_twelve_hours'] = array(
        'interval' => 43200, // Every 12 hours
        'display'  => __( 'Every 12 hours' ),
    );
    return $schedules;
}
add_filter( 'cron_schedules', 'expenseszyx987_myprefix_custom_cron_scheduletwicedaily' );

//hourly
function expenseszyx987_myprefix_custom_cron_schedulehourly( $schedules ) {
    $schedules['every_one_hour'] = array(
        'interval' => 3600, // Every 1 hour
        'display'  => __( 'Every 1 hour' ),
    );
    return $schedules;
}
add_filter( 'cron_schedules', 'expenseszyx987_myprefix_custom_cron_schedulehourly' );

function expenseszyx987_enableAutoBackupDatabaseEveryday() {
    if(empty($_POST['Submit']) || $_POST['Submit'] !== 'ENABLE automatically backup database' || empty($_POST['expenseszyx987_hidden_security'])) {return;}
    global $dragon_expense_dbResult;
    $mynonce = empty($_POST['expenseszyx987_hidden_security']) ? '' : strip_tags(sanitize_text_field($_POST['expenseszyx987_hidden_security']));
    if(wp_verify_nonce($mynonce, 'expenseszyx987_enableAutoBackupDatabaseEveryday') !== 1) {return;}
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        $dragon_expense_dbResult .= 'Invalid user info. ';
        return;
    }
    if(!expenseszyx987_userCanEditInAdminPage()) {
        $dragon_expense_dbResult .= 'You are not authorized to edit data in admin page. Please contact web admin.';
        return;
    }
    if(in_array('administrator', (array) $current_user->roles) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        $hostname = empty($_POST['expenses_dbbackup_hostname']) ? '' : strip_tags(sanitize_text_field($_POST['expenses_dbbackup_hostname']));
        $username = empty($_POST['expenses_dbbackup_username']) ? '' : strip_tags(sanitize_text_field($_POST['expenses_dbbackup_username']));
        $password = empty($_POST['expenses_dbbackup_password']) ? '' : strip_tags(sanitize_text_field($_POST['expenses_dbbackup_password']));

        $dbname = empty($_POST['expenses_dbbackup_dbname']) ? '' : trim(strip_tags(sanitize_text_field($_POST['expenses_dbbackup_dbname'])));

        $mysqldump_path = empty($_POST['expenses_dbbackup_mysqldumppath']) ? '' : strip_tags(sanitize_text_field($_POST['expenses_dbbackup_mysqldumppath']));
        $mysqldump_path = str_replace("\\", "/", $mysqldump_path);
        $mysqldump_path = sanitize_text_field($mysqldump_path);
        if($mysqldump_path !== '' && substr($mysqldump_path, -1) !== '/') {$mysqldump_path .= '/';}
        $backupfilelocation = empty($_POST['expenses_dbbackup_backupfilelocation']) ? '' : strip_tags(sanitize_text_field($_POST['expenses_dbbackup_backupfilelocation']));
        $backupfilelocation = str_replace("\\", "/", $backupfilelocation);
        $backupfilelocation = str_replace("//", "/", $backupfilelocation);
        $backupfilelocation = sanitize_text_field($backupfilelocation);
        if($backupfilelocation !== '' && substr($backupfilelocation, -1) !== '/') {$backupfilelocation .= '/';}
        $backupfrequency = empty($_POST['expenses_dbbackup_frequency']) ? '' : strip_tags(sanitize_text_field($_POST['expenses_dbbackup_frequency']));
        $backuptime = empty($_POST['expenses_dbbackup_time']) ? '' : strip_tags(sanitize_text_field($_POST['expenses_dbbackup_time']));

        if($hostname === '' || $username === '' || $password === '' || $mysqldump_path === '' || $backupfilelocation === '' || $backupfrequency === '-1' || ($backupfrequency !== 'daily' && $backupfrequency !== 'weekly' && $backupfrequency !== 'twicedaily' && $backupfrequency !== 'hourly') || $backuptime === '') {$dragon_expense_dbResult .= 'Hostname, username, password, mysqldump path, backup file location, backup frequency, and backup time are all required. ';return;}
        if(expenseszyx987_validateDate($backuptime)) {
        } else {
            $dragon_expense_dbResult .= 'Backup time does not have a correct time format. ';return;
        }
        //save to db constant table: update DBBACKUP_LOCALTIME, DBBACKUP_FREQUENCY, DBBACKUP_DETAILS
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_expenseszyx987_constant';
        $finalresult = '';
        //$timezone = $wpdb->get_var("SELECT value FROM $table_name WHERE name = 'COMPANY_TIMEZONE'");
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $backupdetails = '';
            if($dbname === '') {
                $backupdetails = '"' . $mysqldump_path . 'mysqldump" --add-drop-table -h ' . $hostname . " -u " . $username . " --password=" . $password . ' --all-databases > "' . $backupfilelocation . 'backupdb.CURRENT_DATE.sql" ';
                $backupdetails = expenseszyx987_cron_encrypt_decrypt('encrypt', $backupdetails);
            } else {
                $backupdetails = '"' . $mysqldump_path . 'mysqldump" --add-drop-table -h ' . $hostname . " -u " . $username . " --password=" . $password . ' --databases ' . $dbname . ' > "' . $backupfilelocation . 'backupdb.CURRENT_DATE.sql" ';
                $backupdetails = expenseszyx987_cron_encrypt_decrypt('encrypt', $backupdetails);
            }
            $query = "UPDATE $table_name SET value = ?, updatetimeutc = UTC_TIMESTAMP() WHERE name = 'DBBACKUP_LOCALTIME' ";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 's';
            $parameterArray[] = &$backuptime;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            if($wpdb->dbh->errno > 0 || $stmt->errno > 0) {
                $finalresult .= 'Edit constant DBBACKUP_LOCALTIME failed. ';
            }
            $stmt->close();

            $query = "UPDATE $table_name SET value = ?, updatetimeutc = UTC_TIMESTAMP() WHERE name = 'DBBACKUP_FREQUENCY' ";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 's';
            $parameterArray[] = &$backupfrequency;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            if($wpdb->dbh->errno > 0 || $stmt->errno > 0) {
                $finalresult .= 'Edit constant DBBACKUP_FREQUENCY failed. ';
            }
            $stmt->close();

            $query = "UPDATE $table_name SET value = ?, updatetimeutc = UTC_TIMESTAMP() WHERE name = 'DBBACKUP_DETAILS' ";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 's';
            $parameterArray[] = &$backupdetails;

            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            if($wpdb->dbh->errno > 0 || $stmt->errno > 0) {
                $finalresult .= 'Edit constant DBBACKUP_DETAILS failed. ';
            }
            $stmt->close();

            if($finalresult === '') {
                $finalresult = 'Success. ';
                if(!wp_next_scheduled('expenseszyx987_cron_dbbackup_hook')) {
                    //if($timezone !== '') {
                    //    date_default_timezone_set($timezone);
                    //}
                    //$timezone=get_option('timezone_string');
                    //if(!empty($timezone)){date_default_timezone_set($timezone);}
                    $backupfrequency2 = '';
                    if($backupfrequency === 'daily') {
                        $backupfrequency2 = 'every_day';
                    }elseif($backupfrequency === 'weekly') {
                        $backupfrequency2 = 'every_week';
                    }elseif($backupfrequency === 'twicedaily') {
                        $backupfrequency2 = 'every_twelve_hours';
                    }elseif($backupfrequency === 'hourly') {
                        $backupfrequency2 = 'every_one_hour';
                    }
                    wp_schedule_event(strtotime($backuptime), $backupfrequency2, 'expenseszyx987_cron_dbbackup_hook');
                }
            }
            $dragon_expense_dbResult .= $finalresult;
            return;
        } else {
            $dragon_expense_dbResult .= "This website can not use mysqli. Please contact website admin. ";
            return;
        }
    } else {
        $dragon_expense_dbResult .= 'Invalid data.';
        return;
    }
}

function expenseszyx987_disableAutoBackupDatabaseEveryday() {
    if(empty($_POST['Submit']) || $_POST['Submit'] !== 'DISABLE automatically backup database' || empty($_POST['expenseszyx987_hidden_security'])) {return;}
    global $dragon_expense_dbResult;
    $mynonce = empty($_POST['expenseszyx987_hidden_security']) ? '' : strip_tags(sanitize_text_field($_POST['expenseszyx987_hidden_security']));
    if(wp_verify_nonce($mynonce, 'expenseszyx987_disableAutoBackupDatabaseEveryday') !== 1) {return;}
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        $dragon_expense_dbResult .= 'Invalid user info. ';
        return;
    }
    if(!expenseszyx987_userCanEditInAdminPage()) {
        $dragon_expense_dbResult .= 'You are not authorized to edit data in admin page. Please contact web admin.';
        return;
    }
    if(in_array('administrator', (array) $current_user->roles) && (!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        $timestamp = wp_next_scheduled('expenseszyx987_cron_dbbackup_hook');
        wp_unschedule_event($timestamp, 'expenseszyx987_cron_dbbackup_hook');
        $dragon_expense_dbResult .= 'Success.';
        return;
    } else {
        $dragon_expense_dbResult .= 'Invalid data.';
        return;
    }
}

function expenseszyx987_OneTimeBackupDatabaseNow() {
    if(empty($_POST['Submit']) || $_POST['Submit'] !== 'Backup database now' || empty($_POST['expenseszyx987_hidden_security'])) {return;}
    $mynonce = empty($_POST['expenseszyx987_hidden_security']) ? '' : strip_tags(sanitize_text_field($_POST['expenseszyx987_hidden_security']));
    if(wp_verify_nonce($mynonce, 'expenseszyx987_backupDatabaseNow') !== 1) {return;}
    expenseszyx987_cron_dbbackup();
}

function expenseszyx987_getConstants($key) {
    global $wpdb;$table_name_prefix = 'wp_expenseszyx987';
    $table_name = $table_name_prefix . '_constant';
    $stmt = $wpdb->dbh->prepare("SELECT value FROM $table_name WHERE name = ? LIMIT 1 ");
    $stmt->bind_param("s", $key);
    $stmt->execute();
    $myresult = $stmt->get_result();
    $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    if(empty($result)) {
        return "";
    } else {
        return $result[0]["value"];
    }
}

function expenseszyx987_getAssociatesForManager($managerid) {
    global $wpdb;$table_name_prefix = 'wp_expenseszyx987';
    $table_name = $table_name_prefix . '_users';
    $temps = $wpdb->get_results("SELECT userid from $table_name WHERE status = 1 and reportto = " . intval($managerid) . " ORDER BY userid");
    $users = array();
    foreach($temps as $temp) {
        $users[] = $temp["userid"];
    }
    return $users;
}

function expenseszyx987_getUID() {
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        return 0;
    }
    return intval($current_user->data->ID);
}

function expenseszyx987_getUserRoleName() {
    global $wpdb;$table_name_prefix = 'wp_expenseszyx987';
    $table_name = $table_name_prefix . '_users';
    $table_name2 = $table_name_prefix . '_role';
    $sql = "SELECT r.name as rolename FROM $table_name t LEFT JOIN $table_name2 r ON r.id = t.roleid ";
    $sql .= " WHERE t.status = 1 AND t.userid = " . expenseszyx987_getUID() . " LIMIT 1";
    $temp = $wpdb->get_results($sql);
    if(!empty($temp)) { return $temp[0]->rolename;} else {return '';}
}

function expenseszyx987_getAssociatesAndSelfForManager($managerid) {
    global $wpdb;$table_name_prefix = 'wp_expenseszyx987';
    $table_name = $table_name_prefix . '_users';
    $temps = $wpdb->get_results("SELECT userid from $table_name WHERE status = 1 and reportto = " . intval($managerid) . " ORDER BY userid");
    $users = array();
    $users[] = $managerid;
    foreach($temps as $temp) {
        $users[] = $temp["id"];
    }
    return $users;
}

function expenseszyx987_hasAssociates($id) {
    global $wpdb;$table_name_prefix = 'wp_expenseszyx987';
    $table_name = $table_name_prefix . '_users';
    $temps = $wpdb->get_results("SELECT userid from $table_name WHERE status = 1 AND reportto = " . intval($id) . " ORDER BY userid");
    if(count($temps)){return true;}
    return false;
}

function expenseszyx987_getUsername() {
    global $wpdb;$table_name = $wpdb->prefix . 'users';
    $temp = $wpdb->get_results("SELECT user_login from $table_name WHERE id = " . expenseszyx987_getUID() . " LIMIT 1 ");
    if(!empty($temp)) { return $temp;} else {return '';}
}

function expenseszyx987_getUserrole() {
    global $wpdb;$table_name_prefix = 'wp_expenseszyx987';
    $table_name = $table_name_prefix . '_users';
    $temp = $wpdb->get_results("SELECT roleid from $table_name WHERE status = 1 AND id = " . expenseszyx987_getUID() . " LIMIT 1 ");
    if(!empty($temp) && $temp[0]->roleid !== null) { return intval($temp[0]->roleid);} else {return 0;}
}

function expenseszyx987_getUserEmailAddress() {
    global $wpdb;$table_name = $wpdb->prefix . 'users';
    $temp = $wpdb->get_results("SELECT user_email from $table_name WHERE id = " . expenseszyx987_getUID() . " LIMIT 1 ");
    if(empty($temp)) {
        return "";
    } else {
        return $temp[0]->user_email;
    }
}

function expenseszyx987_doesThisExpenseUserReportToThisUser($expenseid, $managerid) {
    if(intval($expenseid) <= 0 || intval($managerid) <= 0 ) {return false;}
    global $wpdb;$table_name_prefix = 'wp_expenseszyx987';
    $table_name = $table_name_prefix . '_expense';
    $table_name2 = $table_name_prefix . '_users';
    $temp = $wpdb->get_results("SELECT u.reportto from $table_name t JOIN $table_name2 u ON t.userid = u.userid AND t.id = " . intval($expenseid) . " LIMIT 1 ");
    if(empty($temp)) {
        return false;
    } else {
        return intval($temp[0]->reportto) === intval($managerid);
    }
}

function expenseszyx987_getManagerUID() {
    global $wpdb;$table_name_prefix = 'wp_expenseszyx987';
    $table_name = $table_name_prefix . '_users';
    $temp = $wpdb->get_results("SELECT reportto from $table_name WHERE status = 1 AND id = " . expenseszyx987_getUID() . " LIMIT 1 ");
    if(empty($temp)) {
        return 0;
    } else {
        return intval($temp[0]->reportto);
    }
}

function expenseszyx987_getManagerEmailAddress() {
    global $wpdb;$table_name_prefix = 'wp_expenseszyx987';
    $table_name = $table_name_prefix . '_users';
    $sql = "SELECT a.email FROM $table_name t LEFT JOIN $table_name a ON t.reportto = a.id ";
    $sql .= " WHERE a.status = 1 AND t.status = 1 AND t.userid = " . expenseszyx987_getUID() . " LIMIT 1 ";
    $temp = $wpdb->get_results($sql);
    if(empty($temp)) {
        return "";
    } else {
        return $temp[0]->email;
    }
}

function expenseszyx987_removeAssociatesFromUserArray($userid, $users) {
    $associatesArr = expenseszyx987_getAssociatesForManager(intval($userid));
    $usersArr = explode(",", $users);
    $temp = array();
    foreach($usersArr as $k) {
        if(!in_array($k, $associatesArr)) {
            $temp[] = $k;
        }
    }
    return implode(",",$temp);
}

//This is for user page, not admin page
add_action('wp_ajax_expenseszyx987_deleteExpense', 'expenseszyx987_deleteExpense');
function expenseszyx987_deleteExpense() {
    check_ajax_referer('expenseszyx987_deleteExpense', 'expenseszyx987_hidden_security_deleteexpense');
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        echo 'Invalid user info.';
        exit();
    }
    if((!empty($_POST['expenseszyx987_hidden'])) && $_POST['expenseszyx987_hidden'] === 'Y') {
        $expenseid_temp = empty($_POST['id']) ? 0 : strip_tags(sanitize_text_field($_POST['id']));
        $expenseid = intval($expenseid_temp);
        if($expenseid <= 0) {echo "Invalid id.";exit();}
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $finalresult = '';
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            try{
                $table_name_prefix = 'wp_expenseszyx987';
                $table_name = $table_name_prefix . '_expense';
                $expense = $wpdb->get_results("SELECT * FROM $table_name WHERE status = 1 AND id = $expenseid LIMIT 1");
                $expense2 = $wpdb->get_results("SELECT * FROM $table_name WHERE id = $expenseid LIMIT 1");
                //error_log("at 6629, expense: " . wp_json_encode($expense) . ", expense2: " . wp_json_encode($expense2));
                //error_log("at 6630, count expense2: ". count($expense2).", and count expense:" . count($expense) . ", userid: " . $expense->userid);
                if(count($expense2) > 0 && count($expense) > 0 && intval($expense[0]->userid) === expenseszyx987_getUID()) {
                    $wpdb->dbh->begin_transaction();
                    $result = $wpdb->query($wpdb->prepare("DELETE FROM $table_name WHERE id = %d", $expenseid));
                    //$result = $wpdb->query($wpdb->prepare("UPDATE $table_name SET status = 0 WHERE id = %d", $expenseid));
                    if($result === FALSE) {
                        throw new Exception($finalresult);
                    }
                    $wpdb->dbh->commit();
                } else {
                    $finalresult .= "This expense is not yours.";
                }
            } catch(Exception $e) {
                $wpdb->dbh->rollback();
                $finalresult .= 'Delete expense from DB: Exception Message: ' .$e->getMessage();
            }
            if($finalresult === '') {
                $finalresult = 'Success';
            } else {
                expenseszyx987_saveToLogTable($finalresult, 'Delete expense', 'error', intval($current_user->data->ID));
            }
            echo esc_html($finalresult);
            exit();
        } else {
            $msg = 'This website can not use mysqli. Please contact website admin.';
            expenseszyx987_saveToLogTable($msg, 'Delete expense', 'error', intval($current_user->data->ID));
            echo esc_html($msg);
            exit();
        }
    }
    $msg = "Invalid data.";
    expenseszyx987_saveToLogTable($msg, 'Delete expense', 'error', intval($current_user->data->ID));
    echo esc_html($msg);
    exit();
}

function expenseszyx987_user_has_role($user_id, $role_name) {
    $user_meta = get_userdata($user_id);
    $user_roles = $user_meta->roles;
    return in_array($role_name, $user_roles);
}
?>