<?php
    /*
    Plugin Name: Dragon Ecommerce Reserve Without Online Payment
    Plugin URI:
    Description: Free version. A WordPress ecommerce plugin to let website users to reserve your products online (no online payment) and buy it in your physical store. Please read disclaimer and related documents in the admin plugin setting page before using this software.
    Author: Ming's IT Services Ltd.
    Year: 2020-05-07
    Version: 1.0.2
    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.
    */
global $wpdb; global $dragon_ecommerce_dbResult;
$dragon_ecommerce_dbResult = '';
$timezone=get_option('timezone_string');
if(!empty($timezone)){date_default_timezone_set($timezone);}
define("DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB", "Add reservation to database");
//distance - DECIMAL(10,2)
//weight - DECIMAL(15,2)
//rate - DECIMAL(11,2)
//money has only 2: - DECIMAL(11,2), DECIMAL(15,6)
$table_name = 'wp_dragonecommercereservezyx987';
$charset_collate = $wpdb->get_charset_collate();
function dragonecommercereservezyx987_additional_creation() {
    if(get_role('dragonecommercereservecustomer') === null && get_role('subscriber') !== null) {
        add_role('dragonecommercereservecustomer', __('Dragonecommerce Reserve Customer'), get_role('subscriber')->capabilities);
    }
}

function dragonecommercereservezyx987_createTable_emailmethod() {
    global $table_name;global $charset_collate;
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_emailmethod (
        id INTEGER NOT NULL AUTO_INCREMENT,
        uuid TEXT,
        name TEXT CHARSET utf8,
        description TEXT CHARSET utf8,    
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_emailmethod (name,description,createtimeutc) SELECT * FROM (SELECT 'WordPress Email' as name,'WordPress Email' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_emailmethod WHERE `name`= 'WordPress Email') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_emailmethod (name,description,createtimeutc) SELECT * FROM (SELECT 'Mailgun' as name,'Mailgun' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_emailmethod WHERE `name`= 'Mailgun') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_emailmethod (name,description,createtimeutc) SELECT * FROM (SELECT 'Mailchimp' as name,'Mailchimp' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_emailmethod WHERE `name`= 'Mailchimp') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_emailmethod (name,description,createtimeutc) SELECT * FROM (SELECT 'SendGrid' as name,'Twilio SendGrid' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_emailmethod WHERE `name`= 'SendGrid') LIMIT 1;";
    dbDelta($sql);
}

function dragonecommercereservezyx987_createTable_department() {
    global $table_name;global $charset_collate;
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_department (
        id INTEGER NOT NULL AUTO_INCREMENT,
        name TEXT CHARSET utf8 NOT NULL,
        description TEXT CHARSET utf8,
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_department (name,description,createtimeutc) SELECT * FROM (SELECT 'Grocery' as name,'Grocery department' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_department WHERE `name`= 'Grocery') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_department (name,description,createtimeutc) SELECT * FROM (SELECT 'Electronics' as name,'Electronics department' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_department WHERE `name`= 'Electronics') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_department (name,description,createtimeutc) SELECT * FROM (SELECT 'Toys' as name,'Toys department' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_department WHERE `name`= 'Toys') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_department (name,description,createtimeutc) SELECT * FROM (SELECT 'Home' as name,'Home department' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_department WHERE `name`= 'Home') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_department (name,description,createtimeutc) SELECT * FROM (SELECT 'Baby' as name,'Baby department' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_department WHERE `name`= 'Baby') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_department (name,description,createtimeutc) SELECT * FROM (SELECT 'Furniture' as name,'Furniture department' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_department WHERE `name`= 'Furniture') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_department (name,description,createtimeutc) SELECT * FROM (SELECT 'Appliances' as name,'Appliances department' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_department WHERE `name`= 'Appliances') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_department (name,description,createtimeutc) SELECT * FROM (SELECT 'Sports and recreation' as name,'Sports and recreation department' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_department WHERE `name`= 'Sports and recreation') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_department (name,description,createtimeutc) SELECT * FROM (SELECT 'Women''s clothing' as name,'Women''s clothing department' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_department WHERE `name`= 'Women''s clothing') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_department (name,description,createtimeutc) SELECT * FROM (SELECT 'Kids'' and baby clothing' as name,'Kids'' and baby clothing department' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_department WHERE `name`= 'Kids'' and baby clothing') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_department (name,description,createtimeutc) SELECT * FROM (SELECT 'Men''s clothing' as name,'Men''s clothing department' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_department WHERE `name`= 'Men''s clothing') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_department (name,description,createtimeutc) SELECT * FROM (SELECT 'All clothing, shoes & accessories' as name,'All clothing, shoes & accessories department' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_department WHERE `name`= 'All clothing, shoes & accessories') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_department (name,description,createtimeutc) SELECT * FROM (SELECT 'Health' as name,'Health department' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_department WHERE `name`= 'Health') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_department (name,description,createtimeutc) SELECT * FROM (SELECT 'Personal care' as name,'Personal care department' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_department WHERE `name`= 'Personal care') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_department (name,description,createtimeutc) SELECT * FROM (SELECT 'Beauty' as name,'Beauty department' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_department WHERE `name`= 'Beauty') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_department (name,description,createtimeutc) SELECT * FROM (SELECT 'Video games' as name,'Video games department' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_department WHERE `name`= 'Video games') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_department (name,description,createtimeutc) SELECT * FROM (SELECT 'Outdoor living' as name,'Outdoor living department' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_department WHERE `name`= 'Outdoor living') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_department (name,description,createtimeutc) SELECT * FROM (SELECT 'Pantry and household' as name,'Pantry and household department' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_department WHERE `name`= 'Pantry and household') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_department (name,description,createtimeutc) SELECT * FROM (SELECT 'Jewellery and watches' as name,'Jewellery and watches department' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_department WHERE `name`= 'Jewellery and watches') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_department (name,description,createtimeutc) SELECT * FROM (SELECT 'Automotive' as name,'Automotive department' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_department WHERE `name`= 'Automotive') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_department (name,description,createtimeutc) SELECT * FROM (SELECT 'Pets' as name,'Pets department' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_department WHERE `name`= 'Pets') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_department (name,description,createtimeutc) SELECT * FROM (SELECT 'Gifts and holidays' as name,'Gifts and holidays department' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_department WHERE `name`= 'Gifts and holidays') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_department (name,description,createtimeutc) SELECT * FROM (SELECT 'Office, crafts and party supplies' as name,'Office, crafts and party supplies department' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_department WHERE `name`= 'Office, crafts and party supplies') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_department (name,description,createtimeutc) SELECT * FROM (SELECT 'Gift cards' as name,'Gift cards department' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_department WHERE `name`= 'Gift cards') LIMIT 1;";
    dbDelta($sql);
}

function dragonecommercereservezyx987_createTable_product() {
    global $table_name;global $charset_collate;
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_product (
        id INTEGER NOT NULL AUTO_INCREMENT,
        uuid TEXT,
        departmentid INTEGER,
        name VARCHAR(200) CHARSET utf8 NOT NULL,
        description TEXT CHARSET utf8,
        weightlb DECIMAL(15,2),
        barcode TEXT CHARSET utf8,
        imagefilenames TEXT CHARSET utf8,
        shipfromnearestbranch TINYINT,
        price DECIMAL(11,2) NOT NULL,
        saleprice DECIMAL(11,2),
        onsalestartdateutc DATETIME,
        onsaleenddateutc DATETIME,
        quantity INTEGER,
        originalquantity INTEGER,
        istaxfree TINYINT NOT NULL DEFAULT 0,
        isonsale TINYINT NOT NULL DEFAULT 0,        
        isoutoforder TINYINT NOT NULL DEFAULT 0,
        avoiddepartmentpropertyids TEXT,
        avoidgrouppropertyids TEXT,
        avoiddepartmentpropertyvalueids TEXT,
        avoidgrouppropertyvalueids TEXT,
        extradepartmentpropertyids TEXT,
        extragrouppropertyids TEXT,
        extradepartmentpropertyvalueids TEXT,
        extragrouppropertyvalueids TEXT,
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
}

function dragonecommercereservezyx987_createTable_currency() {
    global $table_name;global $charset_collate;global $wpdb;
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_currency (
        id INTEGER 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,
        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 " . $table_name . "_currency WHERE name = '" . $currency_name . "'");
    if(intval($dbmyid) > 0) {
    } else {    
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_currency (`name`,`sign`,`isocurrencycode`,`createtimeutc`) SELECT * FROM (SELECT %s as 'name', %s as 'sign', %s as 'isocurrencycode', UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $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 " . $table_name . "_currency WHERE name = '" . $currency_name . "'");
    if(intval($dbmyid) > 0) {
    } else {    
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_currency (`name`,`sign`,`isocurrencycode`,`createtimeutc`) SELECT * FROM (SELECT %s as 'name', %s as 'sign', %s as 'isocurrencycode', UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_currency WHERE `name`= '" . $currency_name . "') LIMIT 1", array($currency_name, $currency_sign, $iso_currency_code)));
    }    
    $sql = "INSERT INTO " . $table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'EUR' as 'name', '€' as 'sign', 'EUR' as 'isocurrencycode', 'Euro' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_currency WHERE `name`= 'EUR') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'AFN') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'ALL') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'DZD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'AOA') LIMIT 1;";
    dbDelta($sql);
    
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'XCD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'ARS') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'AMD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'AWG') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'AUD') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'AZN') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'BSD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'BHD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'BDT') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'BBD') LIMIT 1;";
    dbDelta($sql);
    
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'BYR') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'BZD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'XOF') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'BMD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'BTN') LIMIT 1;";
    dbDelta($sql);
    
    $sql = "INSERT INTO " . $table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'INR' as 'name', 'INR₹' as 'sign', 'INR' as 'isocurrencycode', 'Indian Rupee' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_currency WHERE `name`= 'INR') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'BOB') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'BOV') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'BAM') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'BWP') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'NOK') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'BRL') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'BND') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'BGN') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'BIF') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'KHR') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'XAF') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'CVE') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'KYD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'CLF') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'CLP') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'CNY') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'COP') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'COU') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'KMF') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'CDF') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'NZD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'CRC') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'HRK') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'CUC') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'CUP') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'ANG') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'CZK') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'DKK') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'DJF') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'DOP') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'EGP') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'SVC') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'ERN') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'ETB') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'FKP') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'FJD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'XPF') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'GMD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'GEL') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'GHS') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'GIP') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'GTQ') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'GBP' as 'name', '£' as 'sign', 'GBP' as 'isocurrencycode', 'Pound Sterling' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_currency WHERE `name`= 'GBP') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'GNF') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'GYD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'HTG') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'HNL') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'HUF') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'ISK') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'IDR') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'XDR') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'IRR') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'IQD') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'ILS') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'JMD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'JPY') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'JOD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'KZT') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'KES') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'KPW') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'KRW') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'KWD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'KGS') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'LAK') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'LBP') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'LSL') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'ZAR') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'LRD') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'LYD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'CHF') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'MOP') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'MKD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'MGA') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'MWK') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'MYR') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'MVR') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'MRO') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'MUR') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'XUA') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'MXN') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'MXV') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'MDL') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'MNT') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'MAD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'MZN') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'MMK') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'NAD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'NPR') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'NIO') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'NGN') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'OMR') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'PKR') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'PAB') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'PGK') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'PYG') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'PEN') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'PHP') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'PLN') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'QAR') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'RON') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_currency (`name`,`sign`,`isocurrencycode`,`description`,`createtimeutc`) SELECT * FROM (SELECT 'RUB' as 'name', '₽' as 'sign', 'RUB' as 'isocurrencycode', 'Russian Ruble' as 'description', UTC_TIMESTAMP() as 'createtimeutc') AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_currency WHERE `name`= 'RUB') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'RWF') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'SHP') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'WST') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'STD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'SAR') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'RSD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'SCR') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'SLL') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'SGD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'XSU') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'SBD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'SOS') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'SSP') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'LKR') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'SDG') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'SRD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'SZL') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'SEK') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'CHE') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'CHF') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'CHW') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'SYP') LIMIT 1;";
    dbDelta($sql);


    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'TJS') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'TZS') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'THB') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'TOP') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'TTD') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'TND') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'TRY') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'TMT') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'UGX') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'UAH') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'AED') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'UYI') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'USN') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'UYU') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'UZS') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'VUV') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'VEF') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'VND') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'YER') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'ZMW') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $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 " . $table_name . "_currency WHERE `name`= 'ZWL') LIMIT 1;";
    dbDelta($sql);
}

function dragonecommercereservezyx987_createTable_distance() {
    global $table_name;global $charset_collate;global $wpdb;
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_distance (
        id INTEGER NOT NULL AUTO_INCREMENT,
        name TEXT CHARSET utf8 NOT NULL,        
        sign TEXT CHARSET utf8 NOT NULL,
        description TEXT CHARSET utf8,
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
    $distance_name = 'mile';
    $distance_sign = 'mi';
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_distance WHERE name = '" . $distance_name . "'");
    if(intval($dbmyid) > 0) {
    } else {    
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_distance (`name`,`sign`,`createtimeutc`) SELECT * FROM (SELECT %s, %s, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_distance WHERE `name`= '" . $distance_name . "') LIMIT 1", array($distance_name, $distance_sign)));
    }
    $distance_name = 'kilometer';
    $distance_sign = 'km';
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_distance WHERE name = '" . $distance_name . "'");
    if(intval($dbmyid) > 0) {
    } else {    
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_distance (`name`,`sign`,`createtimeutc`) SELECT * FROM (SELECT %s, %s, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_distance WHERE `name`= '" . $distance_name . "') LIMIT 1", array($distance_name, $distance_sign)));
    }
}

function dragonecommercereservezyx987_createTable_weight() {
    global $table_name;global $charset_collate;global $wpdb;        
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_weight (
        id INTEGER NOT NULL AUTO_INCREMENT,
        name TEXT CHARSET utf8 NOT NULL,        
        sign TEXT CHARSET utf8 NOT NULL,
        description TEXT CHARSET utf8,
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
    $weight_name = 'pound';
    $weight_sign = 'lb';
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_weight WHERE name = '" . $weight_name . "'");
    if(intval($dbmyid) > 0) {
    } else {    
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_weight (`name`,`sign`,`createtimeutc`) SELECT * FROM (SELECT %s, %s, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_weight WHERE `name`= '" . $weight_name . "') LIMIT 1", array($weight_name, $weight_sign)));
    }
    $weight_name = 'kilogram';
    $weight_sign = 'kg';
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_weight WHERE name = '" . $weight_name . "'");
    if(intval($dbmyid) > 0) {
    } else {    
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_weight (`name`,`sign`,`createtimeutc`) SELECT * FROM (SELECT %s, %s, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_weight WHERE `name`= '" . $weight_name . "') LIMIT 1", array($weight_name, $weight_sign)));
    }    
}

function dragonecommercereservezyx987_createTable_slideshow() {
    global $table_name;global $charset_collate;    
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_slideshow (
        id INTEGER NOT NULL AUTO_INCREMENT,
        name TEXT CHARSET utf8,
        filename TEXT CHARSET utf8 NOT NULL,
        sequencenumber INT NOT NULL DEFAULT 0,
        description TEXT CHARSET utf8,
        showname TINYINT NOT NULL DEFAULT 0,
        showdescription TINYINT NOT NULL DEFAULT 0,
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
}

function dragonecommercereservezyx987_createTable_country() {
    global $table_name;global $charset_collate;    
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_country (
        id INTEGER NOT NULL AUTO_INCREMENT,
        name TEXT CHARSET utf8 NOT NULL,
        abbreviation TEXT CHARSET utf8 NOT NULL,
        description TEXT CHARSET utf8,        
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'USA' as name, 'US' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'USA') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Canada' as name, 'CA' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Canada') LIMIT 1;";
    dbDelta($sql);
        
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Andorra' as name, 'AD' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Andorra') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'United Arab Emirates' as name, 'AE' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'United Arab Emirates') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Afghanistan' as name, 'AF' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Afghanistan') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Antigua and Barbuda' as name, 'AG' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Antigua and Barbuda') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Anguilla' as name, 'AI' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Anguilla') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Albania' as name, 'AL' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Albania') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Armenia' as name, 'AM' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Armenia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Angola' as name, 'AO' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Angola') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Antarctica' as name, 'AQ' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Antarctica') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Argentina' as name, 'AR' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Argentina') LIMIT 1;";
    dbDelta($sql);
    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'American Samoa' as name, 'AS' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'American Samoa') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Austria' as name, 'AT' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Austria') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Australia' as name, 'AU' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Australia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Aruba' as name, 'AW' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Aruba') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Åland Islands' as name, 'AX' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Åland Islands') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Azerbaijan' as name, 'AZ' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Azerbaijan') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Bosnia and Herzegovina' as name, 'BA' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Bosnia and Herzegovina') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Barbados' as name, 'BB' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Barbados') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Bangladesh' as name, 'BD' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Bangladesh') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Belgium' as name, 'BE' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Belgium') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Burkina Faso' as name, 'BF' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Burkina Faso') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Bulgaria' as name, 'BG' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Bulgaria') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Bahrain' as name, 'BH' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Bahrain') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Burundi' as name, 'BI' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Burundi') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Benin' as name, 'BJ' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Benin') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Saint Barthélemy' as name, 'BL' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Saint Barthélemy') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Bermuda' as name, 'BM' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Bermuda') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Brunei Darussalam' as name, 'BN' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Brunei Darussalam') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Bolivia (Plurinational State of)' as name, 'BO' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Bolivia (Plurinational State of)') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Bonaire, Sint Eustatius and Saba' as name, 'BQ' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Bonaire, Sint Eustatius and Saba') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Brazil' as name, 'BR' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Brazil') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Bahamas' as name, 'BS' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Bahamas') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Bhutan' as name, 'BT' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Bhutan') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Bouvet Island' as name, 'BV' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Bouvet Island') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Botswana' as name, 'BW' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Botswana') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Belarus' as name, 'BY' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Belarus') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Belize' as name, 'BZ' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Belize') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Cocos (Keeling) Islands' as name, 'CC' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Cocos (Keeling) Islands') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Congo, Democratic Republic of the' as name, 'CD' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Congo, Democratic Republic of the') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Central African Republic' as name, 'CF' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Central African Republic') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Congo' as name, 'CG' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Congo') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Switzerland' as name, 'CH' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Switzerland') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Côte d\'Ivoire' as name, 'CI' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Côte d\'Ivoire') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Cook Islands' as name, 'CK' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Cook Islands') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Chile' as name, 'CL' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Chile') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Cameroon' as name, 'CM' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Cameroon') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'China' as name, 'CN' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'China') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Colombia' as name, 'CO' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Colombia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Costa Rica' as name, 'CR' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Costa Rica') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Cuba' as name, 'CU' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Cuba') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Cabo Verde' as name, 'CV' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Cabo Verde') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Curaçao' as name, 'CW' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Curaçao') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Christmas Island' as name, 'CX' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Christmas Island') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Cyprus' as name, 'CY' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Cyprus') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Czechia' as name, 'CZ' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Czechia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Germany' as name, 'DE' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Germany') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Djibouti' as name, 'DJ' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Djibouti') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Denmark' as name, 'DK' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Denmark') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Dominica' as name, 'DM' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Dominica') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Dominican Republic' as name, 'DO' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Dominican Republic') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Algeria' as name, 'DZ' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Algeria') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Ecuador' as name, 'EC' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Ecuador') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Estonia' as name, 'EE' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Estonia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Egypt' as name, 'EG' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Egypt') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Western Sahara' as name, 'EH' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Western Sahara') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Eritrea' as name, 'ER' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Eritrea') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Spain' as name, 'ES' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Spain') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Ethiopia' as name, 'ET' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Ethiopia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Finland' as name, 'FI' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Finland') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Fiji' as name, 'FJ' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Fiji') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Falkland Islands (Malvinas)' as name, 'FK' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Falkland Islands (Malvinas)') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Micronesia (Federated States of)' as name, 'FM' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Micronesia (Federated States of)') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Faroe Islands' as name, 'FO' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Faroe Islands') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'France' as name, 'FR' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'France') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Gabon' as name, 'GA' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Gabon') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'United Kingdom of Great Britain and Northern Ireland' as name, 'GB' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'United Kingdom of Great Britain and Northern Ireland') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Grenada' as name, 'GD' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Grenada') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Georgia' as name, 'GE' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Georgia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'French Guiana' as name, 'GF' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'French Guiana') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Guernsey' as name, 'GG' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Guernsey') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Ghana' as name, 'GH' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Ghana') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Gibraltar' as name, 'GI' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Gibraltar') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Greenland' as name, 'GL' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Greenland') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Gambia' as name, 'GM' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Gambia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Guinea' as name, 'GN' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Guinea') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Guadeloupe' as name, 'GP' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Guadeloupe') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Equatorial Guinea' as name, 'GQ' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Equatorial Guinea') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Greece' as name, 'GR' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Greece') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'South Georgia and the South Sandwich Islands' as name, 'GS' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'South Georgia and the South Sandwich Islands') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Guatemala' as name, 'GT' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Guatemala') LIMIT 1;";
    dbDelta($sql);
    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Guam' as name, 'GU' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Guam') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Guinea-Bissau' as name, 'GW' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Guinea-Bissau') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Guyana' as name, 'GY' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Guyana') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Heard Island and McDonald Islands' as name, 'HM' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Heard Island and McDonald Islands') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Honduras' as name, 'HN' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Honduras') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Croatia' as name, 'HR' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Croatia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Haiti' as name, 'HT' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Haiti') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Hungary' as name, 'HU' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Hungary') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Indonesia' as name, 'ID' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Indonesia') LIMIT 1;";
    dbDelta($sql);
    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Ireland' as name, 'IE' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Ireland') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Israel' as name, 'IL' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Israel') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Isle of Man' as name, 'IM' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Isle of Man') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'India' as name, 'IN' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'India') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'British Indian Ocean Territory' as name, 'IO' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'British Indian Ocean Territory') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Iraq' as name, 'IQ' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Iraq') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Iran (Islamic Republic of)' as name, 'IR' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Iran (Islamic Republic of)') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Iceland' as name, 'IS' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Iceland') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Italy' as name, 'IT' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Italy') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Jersey' as name, 'JE' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Jersey') LIMIT 1;";
    dbDelta($sql);
    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Jamaica' as name, 'JM' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Jamaica') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Jordan' as name, 'JO' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Jordan') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Japan' as name, 'JP' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Japan') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Kenya' as name, 'KE' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Kenya') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Kyrgyzstan' as name, 'KG' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Kyrgyzstan') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Cambodia' as name, 'KH' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Cambodia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Kiribati' as name, 'KI' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Kiribati') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Comoros' as name, 'KM' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Comoros') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Saint Kitts and Nevis' as name, 'KN' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Saint Kitts and Nevis') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Korea (Democratic People\'s Republic of)' as name, 'KP' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Korea (Democratic People\'s Republic of)') LIMIT 1;";
    dbDelta($sql);
        
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Korea, Republic of' as name, 'KR' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Korea, Republic of') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Kuwait' as name, 'KW' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Kuwait') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Cayman Islands' as name, 'KY' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Cayman Islands') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Kazakhstan' as name, 'KZ' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Kazakhstan') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Lao People\'s Democratic Republic' as name, 'LA' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Lao People\'s Democratic Republic') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Lebanon' as name, 'LB' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Lebanon') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Saint Lucia' as name, 'LC' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Saint Lucia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Liechtenstein' as name, 'LI' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Liechtenstein') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Sri Lanka' as name, 'LK' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Sri Lanka') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Liberia' as name, 'LR' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Liberia') LIMIT 1;";
    dbDelta($sql);
        
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Lesotho' as name, 'LS' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Lesotho') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Lithuania' as name, 'LT' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Lithuania') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Luxembourg' as name, 'LU' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Luxembourg') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Latvia' as name, 'LV' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Latvia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Libya' as name, 'LY' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Libya') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Morocco' as name, 'MA' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Morocco') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Monaco' as name, 'MC' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Monaco') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Moldova, Republic of' as name, 'MD' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Moldova, Republic of') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Montenegro' as name, 'ME' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Montenegro') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Saint Martin (French part)' as name, 'MF' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Saint Martin (French part)') LIMIT 1;";
    dbDelta($sql);
    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Madagascar' as name, 'MG' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Madagascar') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Marshall Islands' as name, 'MH' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Marshall Islands') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'North Macedonia' as name, 'MK' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'North Macedonia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Mali' as name, 'ML' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Mali') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Myanmar' as name, 'MM' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Myanmar') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Mongolia' as name, 'MN' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Mongolia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Macao' as name, 'MO' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Macao') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Northern Mariana Islands' as name, 'MP' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Northern Mariana Islands') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Martinique' as name, 'MQ' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Martinique') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Mauritania' as name, 'MR' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Mauritania') LIMIT 1;";
    dbDelta($sql);
        
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Montserrat' as name, 'MS' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Montserrat') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Malta' as name, 'MT' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Malta') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Mauritius' as name, 'MU' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Mauritius') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Maldives' as name, 'MV' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Maldives') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Malawi' as name, 'MW' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Malawi') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Mexico' as name, 'MX' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Mexico') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Malaysia' as name, 'MY' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Malaysia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Mozambique' as name, 'MZ' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Mozambique') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Namibia' as name, 'NA' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Namibia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'New Caledonia' as name, 'NC' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'New Caledonia') LIMIT 1;";
    dbDelta($sql);
        
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Niger' as name, 'NE' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Niger') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Norfolk Island' as name, 'NF' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Norfolk Island') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Nigeria' as name, 'NG' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Nigeria') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Nicaragua' as name, 'NI' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Nicaragua') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Netherlands' as name, 'NL' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Netherlands') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Norway' as name, 'NO' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Norway') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Nepal' as name, 'NP' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Nepal') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Nauru' as name, 'NR' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Nauru') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Niue' as name, 'NU' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Niue') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'New Zealand' as name, 'NZ' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'New Zealand') LIMIT 1;";
    dbDelta($sql);
        
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Oman' as name, 'OM' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Oman') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Panama' as name, 'PA' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Panama') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Peru' as name, 'PE' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Peru') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'French Polynesia' as name, 'PF' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'French Polynesia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Papua New Guinea' as name, 'PG' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Papua New Guinea') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Philippines' as name, 'PH' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Philippines') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Pakistan' as name, 'PK' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Pakistan') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Poland' as name, 'PL' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Poland') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Saint Pierre and Miquelon' as name, 'PM' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Saint Pierre and Miquelon') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Pitcairn' as name, 'PN' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Pitcairn') LIMIT 1;";
    dbDelta($sql);
        
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Puerto Rico' as name, 'PR' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Puerto Rico') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Palestine, State of' as name, 'PS' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Palestine, State of') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Portugal' as name, 'PT' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Portugal') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Palau' as name, 'PW' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Palau') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Paraguay' as name, 'PY' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Paraguay') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Qatar' as name, 'QA' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Qatar') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Réunion' as name, 'RE' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Réunion') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Romania' as name, 'RO' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Romania') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Serbia' as name, 'RS' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Serbia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Russian Federation' as name, 'RU' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Russian Federation') LIMIT 1;";
    dbDelta($sql);
        
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Rwanda' as name, 'RW' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Rwanda') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Saudi Arabia' as name, 'SA' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Saudi Arabia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Solomon Islands' as name, 'SB' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Solomon Islands') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Seychelles' as name, 'SC' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Seychelles') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Sudan' as name, 'SD' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Sudan') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Sweden' as name, 'SE' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Sweden') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Singapore' as name, 'SG' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Singapore') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Saint Helena, Ascension and Tristan da Cunha' as name, 'SH' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Saint Helena, Ascension and Tristan da Cunha') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Slovenia' as name, 'SI' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Slovenia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Svalbard and Jan Mayen' as name, 'SJ' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Svalbard and Jan Mayen') LIMIT 1;";
    dbDelta($sql);
        
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Slovakia' as name, 'SK' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Slovakia') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Sierra Leone' as name, 'SL' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Sierra Leone') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'San Marino' as name, 'SM' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'San Marino') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Senegal' as name, 'SN' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Senegal') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Somalia' as name, 'SO' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Somalia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Suriname' as name, 'SR' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Suriname') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'South Sudan' as name, 'SS' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'South Sudan') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Sao Tome and Principe' as name, 'ST' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Sao Tome and Principe') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'El Salvador' as name, 'SV' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'El Salvador') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Sint Maarten (Dutch part)' as name, 'SX' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Sint Maarten (Dutch part)') LIMIT 1;";
    dbDelta($sql);
        
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Syrian Arab Republic' as name, 'SY' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Syrian Arab Republic') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Eswatini' as name, 'SZ' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Eswatini') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Turks and Caicos Islands' as name, 'TC' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Turks and Caicos Islands') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Chad' as name, 'TD' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Chad') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'French Southern Territories' as name, 'TF' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'French Southern Territories') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Togo' as name, 'TG' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Togo') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Thailand' as name, 'TH' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Thailand') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Tajikistan' as name, 'TJ' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Tajikistan') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Tokelau' as name, 'TK' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Tokelau') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Timor-Leste' as name, 'TL' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Timor-Leste') LIMIT 1;";
    dbDelta($sql);
        
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Turkmenistan' as name, 'TM' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Turkmenistan') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Tunisia' as name, 'TN' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Tunisia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Tonga' as name, 'TO' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Tonga') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Turkey' as name, 'TR' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Turkey') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Trinidad and Tobago' as name, 'TT' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Trinidad and Tobago') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Tuvalu' as name, 'TV' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Tuvalu') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Tanzania, United Republic of' as name, 'TZ' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Tanzania, United Republic of') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Ukraine' as name, 'UA' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Ukraine') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Uganda' as name, 'UG' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Uganda') LIMIT 1;";
    dbDelta($sql);
        
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'United States Minor Outlying Islands' as name, 'UM' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'United States Minor Outlying Islands') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Uruguay' as name, 'UY' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Uruguay') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Uzbekistan' as name, 'UZ' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Uzbekistan') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Holy See' as name, 'VA' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Holy See') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Saint Vincent and the Grenadines' as name, 'VC' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Saint Vincent and the Grenadines') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Venezuela (Bolivarian Republic of)' as name, 'VE' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Venezuela (Bolivarian Republic of)') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Virgin Islands (British)' as name, 'VG' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Virgin Islands (British)') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Virgin Islands (U.S.)' as name, 'VI' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Virgin Islands (U.S.)') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Viet Nam' as name, 'VN' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Viet Nam') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Vanuatu' as name, 'VU' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Vanuatu') LIMIT 1;";
    dbDelta($sql);
        
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Wallis and Futuna' as name, 'WF' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Wallis and Futuna') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Samoa' as name, 'WS' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Samoa') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Yemen' as name, 'YE' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Yemen') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Mayotte' as name, 'YT' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Mayotte') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'South Africa' as name, 'ZA' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'South Africa') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Zambia' as name, 'ZM' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Zambia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country (name,abbreviation,createtimeutc) SELECT * FROM (SELECT 'Zimbabwe' as name, 'ZW' as abbreviation, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_country WHERE `name`= 'Zimbabwe') LIMIT 1;";
    dbDelta($sql);        
}

function dragonecommercereservezyx987_createTable_province() {
    global $table_name;global $charset_collate;global $wpdb;    
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_province (
        id INTEGER NOT NULL AUTO_INCREMENT,
        countryid INTEGER NOT NULL,
        name TEXT CHARSET utf8 NOT NULL,
        description TEXT CHARSET utf8,
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
    $province_name = 'Alabama';
    $alabama_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $alabama_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1) as countryid,'" . $province_name . "' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $alabama_id = $wpdb->insert_id;
    }    
    $province_name = 'Alaska';
    $alaska_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $alaska_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $alaska_id = $wpdb->insert_id;        
    }
    $province_name = 'Arizona';
    $arizona_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $arizona_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $arizona_id = $wpdb->insert_id;        
    }
    $province_name = 'Arkansas';
    $arkansas_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $arkansas_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $arkansas_id = $wpdb->insert_id;        
    }
    $province_name = 'California';
    $california_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $california_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $california_id = $wpdb->insert_id;        
    }
    $province_name = 'Colorado';
    $colorado_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $colorado_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $colorado_id = $wpdb->insert_id;        
    }
    $province_name = 'Connecticut';
    $connecticut_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $connecticut_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $connecticut_id = $wpdb->insert_id;        
    }
    $province_name = 'Delaware';
    $delaware_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $delaware_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $delaware_id = $wpdb->insert_id;        
    }
    $province_name = 'Florida';
    $florida_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $florida_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $florida_id = $wpdb->insert_id;        
    }
    $province_name = 'Georgia';
    $georgia_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $georgia_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $georgia_id = $wpdb->insert_id;        
    }
    $province_name = 'Hawaii';
    $hawaii_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $hawaii_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $hawaii_id = $wpdb->insert_id;        
    }
    $province_name = 'Idaho';
    $idaho_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $idaho_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $idaho_id = $wpdb->insert_id;        
    }
    $province_name = 'Illinois';
    $illinois_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $illinois_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $illinois_id = $wpdb->insert_id;        
    }
    $province_name = 'Indiana';
    $indiana_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $indiana_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $indiana_id = $wpdb->insert_id;        
    }
    $province_name = 'Iowa';
    $iowa_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $iowa_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $iowa_id = $wpdb->insert_id;        
    }
    $province_name = 'Kansas';
    $kansas_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $kansas_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $kansas_id = $wpdb->insert_id;        
    }
    $province_name = 'Kentucky';
    $kentucky_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $kentucky_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $kentucky_id = $wpdb->insert_id;        
    }
    $province_name = 'Louisiana';
    $louisiana_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $louisiana_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $louisiana_id = $wpdb->insert_id;        
    }
    $province_name = 'Maine';
    $maine_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $maine_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $maine_id = $wpdb->insert_id;        
    }
    $province_name = 'Maryland';
    $maryland_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $maryland_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $maryland_id = $wpdb->insert_id;        
    }
    $province_name = 'Massachusetts';
    $massachusetts_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $massachusetts_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $massachusetts_id = $wpdb->insert_id;        
    }
    $province_name = 'Michigan';
    $michigan_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $michigan_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $michigan_id = $wpdb->insert_id;        
    }
    $province_name = 'Minnesota';
    $minnesota_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $minnesota_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $minnesota_id = $wpdb->insert_id;        
    }
    $province_name = 'Mississippi';
    $mississippi_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $mississippi_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $mississippi_id = $wpdb->insert_id;        
    }
    $province_name = 'Missouri';
    $missouri_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $missouri_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $missouri_id = $wpdb->insert_id;        
    }
    $province_name = 'Montana';
    $montana_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $montana_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $montana_id = $wpdb->insert_id;        
    }
    $province_name = 'Nebraska';
    $nebraska_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $nebraska_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $nebraska_id = $wpdb->insert_id;        
    }
    $province_name = 'Nevada';
    $nevada_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $nevada_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $nevada_id = $wpdb->insert_id;        
    }
    $province_name = 'New Hampshire';
    $newhampshire_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $newhampshire_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $newhampshire_id = $wpdb->insert_id;        
    }
    $province_name = 'New Jersey';
    $newjersey_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $newjersey_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $newjersey_id = $wpdb->insert_id;        
    }
    $province_name = 'New Mexico';
    $newmexico_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $newmexico_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $newmexico_id = $wpdb->insert_id;        
    }
    $province_name = 'New York';
    $newyork_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $newyork_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $newyork_id = $wpdb->insert_id;        
    }
    $province_name = 'North Carolina';
    $northcarolina_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $northcarolina_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $northcarolina_id = $wpdb->insert_id;        
    }
    $province_name = 'North Dakota';
    $northdakota_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $northdakota_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $northdakota_id = $wpdb->insert_id;        
    }
    $province_name = 'Ohio';
    $ohio_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $ohio_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $ohio_id = $wpdb->insert_id;        
    }
    $province_name = 'Oklahoma';
    $oklahoma_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $oklahoma_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $oklahoma_id = $wpdb->insert_id;        
    }
    $province_name = 'Oregon';
    $oregon_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $oregon_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $oregon_id = $wpdb->insert_id;        
    }
    $province_name = 'Pennsylvania';
    $pennsylvania_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $pennsylvania_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $pennsylvania_id = $wpdb->insert_id;        
    }
    $province_name = 'Rhode Island';
    $rhodeisland_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $rhodeisland_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $rhodeisland_id = $wpdb->insert_id;        
    }
    $province_name = 'South Carolina';
    $southcarolina_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $southcarolina_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $southcarolina_id = $wpdb->insert_id;        
    }
    $province_name = 'South Dakota';
    $southdakota_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $southdakota_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $southdakota_id = $wpdb->insert_id;        
    }
    $province_name = 'Tennessee';
    $tennessee_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $tennessee_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $tennessee_id = $wpdb->insert_id;        
    }
    $province_name = 'Texas';
    $texas_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $texas_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $texas_id = $wpdb->insert_id;        
    }
    $province_name = 'Utah';
    $utah_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $utah_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $utah_id = $wpdb->insert_id;        
    }
    $province_name = 'Vermont';
    $vermont_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $vermont_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $vermont_id = $wpdb->insert_id;        
    }
    $province_name = 'Virginia';
    $virginia_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $virginia_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $virginia_id = $wpdb->insert_id;        
    }
    $province_name = 'Washington';
    $washington_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $washington_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $washington_id = $wpdb->insert_id;        
    }
    $province_name = 'Washington, D.C.';
    $washingtondc_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $washingtondc_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $washingtondc_id = $wpdb->insert_id;        
    }
    $province_name = 'West Virginia';
    $westvirginia_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $westvirginia_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $westvirginia_id = $wpdb->insert_id;        
    }
    $province_name = 'Wisconsin';
    $wisconsin_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $wisconsin_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $wisconsin_id = $wpdb->insert_id;        
    }
    $province_name = 'Wyoming';
    $wyoming_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $wyoming_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $wyoming_id = $wpdb->insert_id;        
    }
    $province_name = 'Alberta';
    $alberta_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $alberta_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $alberta_id = $wpdb->insert_id;        
    }
    $province_name = 'British Columbia';
    $britishcolumbia_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $britishcolumbia_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $britishcolumbia_id = $wpdb->insert_id;        
    }
    $province_name = 'Manitoba';
    $manitoba_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $manitoba_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $manitoba_id = $wpdb->insert_id;        
    }
    $province_name = 'New Brunswick';
    $newbrunswick_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $newbrunswick_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $newbrunswick_id = $wpdb->insert_id;        
    }
    $province_name = 'Newfoundland and Labrador';
    $newfoundlandandlabrador_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $newfoundlandandlabrador_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $newfoundlandandlabrador_id = $wpdb->insert_id;        
    }
    $province_name = 'Nova Scotia';
    $novascotia_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $novascotia_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $novascotia_id = $wpdb->insert_id;        
    }
    $province_name = 'Ontario';
    $ontario_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $ontario_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $ontario_id = $wpdb->insert_id;        
    }
    $province_name = 'Prince Edward Island';
    $princeedwardisland_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $princeedwardisland_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $princeedwardisland_id = $wpdb->insert_id;        
    }
    $province_name = 'Quebec';
    $quebec_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $quebec_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $quebec_id = $wpdb->insert_id;        
    }
    $province_name = 'Saskatchewan';
    $saskatchewan_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $saskatchewan_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $saskatchewan_id = $wpdb->insert_id;        
    }            
    $province_name = 'Northwest Territories';
    $saskatchewan_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $saskatchewan_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $saskatchewan_id = $wpdb->insert_id;        
    }
    $province_name = 'Nunavut';
    $saskatchewan_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $saskatchewan_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $saskatchewan_id = $wpdb->insert_id;        
    }
    $province_name = 'Yukon';
    $saskatchewan_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $saskatchewan_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $saskatchewan_id = $wpdb->insert_id;        
    }
}

function dragonecommercereservezyx987_createTable_city() {
    global $table_name;global $charset_collate;global $wpdb;    
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_city (
        id INTEGER NOT NULL AUTO_INCREMENT,
        provinceid INTEGER NOT NULL,
        name TEXT CHARSET utf8 NOT NULL,
        description TEXT CHARSET utf8,
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
    $province_name = 'Alabama';
    $alabama_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $alabama_id = intval($dbmyid);
    }    
    $province_name = 'Alaska';
    $alaska_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $alaska_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $alaska_id = $wpdb->insert_id;        
    }
    $province_name = 'Arizona';
    $arizona_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $arizona_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $arizona_id = $wpdb->insert_id;        
    }
    $province_name = 'Arkansas';
    $arkansas_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $arkansas_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $arkansas_id = $wpdb->insert_id;        
    }
    $province_name = 'California';
    $california_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $california_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $california_id = $wpdb->insert_id;        
    }
    $province_name = 'Colorado';
    $colorado_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $colorado_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $colorado_id = $wpdb->insert_id;        
    }
    $province_name = 'Connecticut';
    $connecticut_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $connecticut_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $connecticut_id = $wpdb->insert_id;        
    }
    $province_name = 'Delaware';
    $delaware_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $delaware_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $delaware_id = $wpdb->insert_id;        
    }
    $province_name = 'Florida';
    $florida_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $florida_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $florida_id = $wpdb->insert_id;        
    }
    $province_name = 'Georgia';
    $georgia_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $georgia_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $georgia_id = $wpdb->insert_id;        
    }
    $province_name = 'Hawaii';
    $hawaii_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $hawaii_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $hawaii_id = $wpdb->insert_id;        
    }
    $province_name = 'Idaho';
    $idaho_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $idaho_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $idaho_id = $wpdb->insert_id;        
    }
    $province_name = 'Illinois';
    $illinois_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $illinois_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $illinois_id = $wpdb->insert_id;        
    }
    $province_name = 'Indiana';
    $indiana_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $indiana_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $indiana_id = $wpdb->insert_id;        
    }
    $province_name = 'Iowa';
    $iowa_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $iowa_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $iowa_id = $wpdb->insert_id;        
    }
    $province_name = 'Kansas';
    $kansas_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $kansas_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $kansas_id = $wpdb->insert_id;        
    }
    $province_name = 'Kentucky';
    $kentucky_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $kentucky_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $kentucky_id = $wpdb->insert_id;        
    }
    $province_name = 'Louisiana';
    $louisiana_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $louisiana_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $louisiana_id = $wpdb->insert_id;        
    }
    $province_name = 'Maine';
    $maine_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $maine_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $maine_id = $wpdb->insert_id;        
    }
    $province_name = 'Maryland';
    $maryland_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $maryland_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $maryland_id = $wpdb->insert_id;        
    }
    $province_name = 'Massachusetts';
    $massachusetts_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $massachusetts_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $massachusetts_id = $wpdb->insert_id;        
    }
    $province_name = 'Michigan';
    $michigan_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $michigan_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $michigan_id = $wpdb->insert_id;        
    }
    $province_name = 'Minnesota';
    $minnesota_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $minnesota_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $minnesota_id = $wpdb->insert_id;        
    }
    $province_name = 'Mississippi';
    $mississippi_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $mississippi_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $mississippi_id = $wpdb->insert_id;        
    }
    $province_name = 'Missouri';
    $missouri_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $missouri_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $missouri_id = $wpdb->insert_id;        
    }
    $province_name = 'Montana';
    $montana_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $montana_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $montana_id = $wpdb->insert_id;        
    }
    $province_name = 'Nebraska';
    $nebraska_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $nebraska_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $nebraska_id = $wpdb->insert_id;        
    }
    $province_name = 'Nevada';
    $nevada_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $nevada_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $nevada_id = $wpdb->insert_id;        
    }
    $province_name = 'New Hampshire';
    $newhampshire_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $newhampshire_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $newhampshire_id = $wpdb->insert_id;        
    }
    $province_name = 'New Jersey';
    $newjersey_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $newjersey_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $newjersey_id = $wpdb->insert_id;        
    }
    $province_name = 'New Mexico';
    $newmexico_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $newmexico_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $newmexico_id = $wpdb->insert_id;        
    }
    $province_name = 'New York';
    $newyork_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $newyork_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $newyork_id = $wpdb->insert_id;        
    }
    $province_name = 'North Carolina';
    $northcarolina_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $northcarolina_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $northcarolina_id = $wpdb->insert_id;        
    }
    $province_name = 'North Dakota';
    $northdakota_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $northdakota_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $northdakota_id = $wpdb->insert_id;        
    }
    $province_name = 'Ohio';
    $ohio_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $ohio_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $ohio_id = $wpdb->insert_id;        
    }
    $province_name = 'Oklahoma';
    $oklahoma_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $oklahoma_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $oklahoma_id = $wpdb->insert_id;        
    }
    $province_name = 'Oregon';
    $oregon_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $oregon_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $oregon_id = $wpdb->insert_id;        
    }
    $province_name = 'Pennsylvania';
    $pennsylvania_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $pennsylvania_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $pennsylvania_id = $wpdb->insert_id;        
    }
    $province_name = 'Rhode Island';
    $rhodeisland_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $rhodeisland_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $rhodeisland_id = $wpdb->insert_id;        
    }
    $province_name = 'South Carolina';
    $southcarolina_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $southcarolina_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $southcarolina_id = $wpdb->insert_id;        
    }
    $province_name = 'South Dakota';
    $southdakota_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $southdakota_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $southdakota_id = $wpdb->insert_id;        
    }
    $province_name = 'Tennessee';
    $tennessee_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $tennessee_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $tennessee_id = $wpdb->insert_id;        
    }
    $province_name = 'Texas';
    $texas_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $texas_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $texas_id = $wpdb->insert_id;        
    }
    $province_name = 'Utah';
    $utah_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $utah_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $utah_id = $wpdb->insert_id;        
    }
    $province_name = 'Vermont';
    $vermont_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $vermont_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $vermont_id = $wpdb->insert_id;        
    }
    $province_name = 'Virginia';
    $virginia_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $virginia_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $virginia_id = $wpdb->insert_id;        
    }
    $province_name = 'Washington';
    $washington_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $washington_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $washington_id = $wpdb->insert_id;        
    }
    $province_name = 'Washington, D.C.';
    $washingtondc_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $washingtondc_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $washingtondc_id = $wpdb->insert_id;        
    }
    $province_name = 'West Virginia';
    $westvirginia_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $westvirginia_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $westvirginia_id = $wpdb->insert_id;        
    }
    $province_name = 'Wisconsin';
    $wisconsin_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $wisconsin_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $wisconsin_id = $wpdb->insert_id;        
    }
    $province_name = 'Wyoming';
    $wyoming_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $wyoming_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'USA' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $wyoming_id = $wpdb->insert_id;        
    }
    $province_name = 'Alberta';
    $alberta_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $alberta_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $alberta_id = $wpdb->insert_id;        
    }
    $province_name = 'British Columbia';
    $britishcolumbia_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $britishcolumbia_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $britishcolumbia_id = $wpdb->insert_id;        
    }
    $province_name = 'Manitoba';
    $manitoba_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $manitoba_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $manitoba_id = $wpdb->insert_id;        
    }
    $province_name = 'New Brunswick';
    $newbrunswick_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $newbrunswick_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $newbrunswick_id = $wpdb->insert_id;        
    }
    $province_name = 'Newfoundland and Labrador';
    $newfoundlandandlabrador_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $newfoundlandandlabrador_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $newfoundlandandlabrador_id = $wpdb->insert_id;        
    }
    $province_name = 'Nova Scotia';
    $novascotia_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $novascotia_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $novascotia_id = $wpdb->insert_id;        
    }
    $province_name = 'Ontario';
    $ontario_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $ontario_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $ontario_id = $wpdb->insert_id;        
    }
    $province_name = 'Prince Edward Island';
    $princeedwardisland_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $princeedwardisland_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $princeedwardisland_id = $wpdb->insert_id;        
    }
    $province_name = 'Quebec';
    $quebec_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $quebec_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $quebec_id = $wpdb->insert_id;        
    }
    $province_name = 'Saskatchewan';
    $saskatchewan_id = 0;
    $dbmyid = $wpdb->get_var("SELECT id FROM " . $table_name . "_province WHERE name = '" . $province_name . "' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1)");
    if($dbmyid !== null && intval($dbmyid) > 0) {
        $saskatchewan_id = intval($dbmyid);
    } else {
        $mytemp = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_name . "_province (countryid,name,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_country WHERE name = 'Canada' LIMIT 1),'" . $province_name . "',UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_province WHERE `name`= '" . $province_name . "') LIMIT 1;"));
        $saskatchewan_id = $wpdb->insert_id;        
    }

    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $california_id as provinceid,'Los Angeles' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Los Angeles' and `provinceid` = $california_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $california_id as provinceid,'San Francisco' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'San Francisco' and `provinceid` = $california_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $california_id as provinceid,'San Diego' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'San Diego' and `provinceid` = $california_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $california_id as provinceid,'San Jose' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'San Jose' and `provinceid` = $california_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $california_id as provinceid,'Fresno' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Fresno' and `provinceid` = $california_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $california_id as provinceid,'Sacramento' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Sacramento' and `provinceid` = $california_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $california_id as provinceid,'Long Beach' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Long Beach' and `provinceid` = $california_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $california_id as provinceid,'Oakland' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Oakland' and `provinceid` = $california_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $texas_id as provinceid,'Houston' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Houston' and `provinceid` = $texas_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $texas_id as provinceid,'San Antonio' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'San Antonio' and `provinceid` = $texas_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $texas_id as provinceid,'Dallas' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Dallas' and `provinceid` = $texas_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $texas_id as provinceid,'Austin' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Austin' and `provinceid` = $texas_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $texas_id as provinceid,'Fort Worth' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Fort Worth' and `provinceid` = $texas_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $texas_id as provinceid,'El Paso' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'El Paso' and `provinceid` = $texas_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $texas_id as provinceid,'Arlington' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Arlington' and `provinceid` = $texas_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $texas_id as provinceid,'Corpus Christi' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Corpus Christi' and `provinceid` = $texas_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $florida_id as provinceid,'Jacksonville' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Jacksonville' and `provinceid` = $florida_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $florida_id as provinceid,'Miami' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Miami' and `provinceid` = $florida_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $florida_id as provinceid,'Tampa' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Tampa' and `provinceid` = $florida_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $florida_id as provinceid,'Orlando' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Orlando' and `provinceid` = $florida_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $florida_id as provinceid,'St. Petersburg' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'St. Petersburg' and `provinceid` = $florida_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $florida_id as provinceid,'Hialeah' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Hialeah' and `provinceid` = $florida_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $florida_id as provinceid,'Port St. Lucie' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Port St. Lucie' and `provinceid` = $florida_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $florida_id as provinceid,'Cape Coral' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Cape Coral' and `provinceid` = $florida_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $louisiana_id as provinceid,'New Orleans' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'New Orleans' and `provinceid` = $louisiana_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $louisiana_id as provinceid,'Baton Rouge' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Baton Rouge' and `provinceid` = $louisiana_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $louisiana_id as provinceid,'Shreveport' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Shreveport' and `provinceid` = $louisiana_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $louisiana_id as provinceid,'Lafayette' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Lafayette' and `provinceid` = $louisiana_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $louisiana_id as provinceid,'Lake Charles' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Lake Charles' and `provinceid` = $louisiana_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $louisiana_id as provinceid,'Bossier City' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Bossier City' and `provinceid` = $louisiana_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $louisiana_id as provinceid,'Kenner' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Kenner' and `provinceid` = $louisiana_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $louisiana_id as provinceid,'Monroe' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Monroe' and `provinceid` = $louisiana_id ) LIMIT 1;";
    dbDelta($sql);        
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $washington_id as provinceid,'Seattle' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Seattle' and `provinceid` = $washington_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $washington_id as provinceid,'Spokane' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Spokane' and `provinceid` = $washington_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $washington_id as provinceid,'Tacoma' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Tacoma' and `provinceid` = $washington_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $washington_id as provinceid,'Vancouver' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Vancouver' and `provinceid` = $washington_id ) LIMIT 1;";
    dbDelta($sql);        
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $arizona_id as provinceid,'Phoenix' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Phoenix' and `provinceid` = $arizona_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $arizona_id as provinceid,'Tucson' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Tucson' and `provinceid` = $arizona_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $newyork_id as provinceid,'New York City' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'New York City' and `provinceid` = $newyork_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $newyork_id as provinceid,'Buffalo' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Buffalo' and `provinceid` = $newyork_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $newyork_id as provinceid,'Rochester' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Rochester' and `provinceid` = $newyork_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $newyork_id as provinceid,'Yonkers' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Yonkers' and `provinceid` = $newyork_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $newyork_id as provinceid,'Syracuse' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Syracuse' and `provinceid` = $newyork_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $newyork_id as provinceid,'Albany' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Albany' and `provinceid` = $newyork_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $newyork_id as provinceid,'New Rochelle' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'New Rochelle' and `provinceid` = $newyork_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $newyork_id as provinceid,'Cheektowaga' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Cheektowaga' and `provinceid` = $newyork_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $massachusetts_id as provinceid,'Boston' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Boston' and `provinceid` = $massachusetts_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $massachusetts_id as provinceid,'Worcester' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Worcester' and `provinceid` = $massachusetts_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $massachusetts_id as provinceid,'Springfield' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Springfield' and `provinceid` = $massachusetts_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $massachusetts_id as provinceid,'Cambridge' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Cambridge' and `provinceid` = $massachusetts_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $massachusetts_id as provinceid,'Lowell' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Lowell' and `provinceid` = $massachusetts_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $massachusetts_id as provinceid,'Brockton' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Brockton' and `provinceid` = $massachusetts_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $massachusetts_id as provinceid,'Lynn' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Lynn' and `provinceid` = $massachusetts_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $massachusetts_id as provinceid,'New Bedford' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'New Bedford' and `provinceid` = $massachusetts_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $connecticut_id as provinceid,'Bridgeport' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Bridgeport' and `provinceid` = $connecticut_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $connecticut_id as provinceid,'Stamford' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Stamford' and `provinceid` = $connecticut_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $connecticut_id as provinceid,'New Haven' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'New Haven' and `provinceid` = $connecticut_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $connecticut_id as provinceid,'Hartford' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Hartford' and `provinceid` = $connecticut_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $connecticut_id as provinceid,'Waterbury' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Waterbury' and `provinceid` = $connecticut_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $connecticut_id as provinceid,'Norwalk' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Norwalk' and `provinceid` = $connecticut_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $connecticut_id as provinceid,'Danbury' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Danbury' and `provinceid` = $connecticut_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $connecticut_id as provinceid,'New Britain' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'New Britain' and `provinceid` = $connecticut_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $newjersey_id as provinceid,'Newark' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Newark' and `provinceid` = $newjersey_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $newjersey_id as provinceid,'Jersey City' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Jersey City' and `provinceid` = $newjersey_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $newjersey_id as provinceid,'Paterson' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Paterson' and `provinceid` = $newjersey_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $newjersey_id as provinceid,'Elizabeth' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Elizabeth' and `provinceid` = $newjersey_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $pennsylvania_id as provinceid,'Philadelphia' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Philadelphia' and `provinceid` = $pennsylvania_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $pennsylvania_id as provinceid,'Pittsburgh' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Pittsburgh' and `provinceid` = $pennsylvania_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $pennsylvania_id as provinceid,'Allentown' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Allentown' and `provinceid` = $pennsylvania_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $pennsylvania_id as provinceid,'Erie' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Erie' and `provinceid` = $pennsylvania_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $pennsylvania_id as provinceid,'Reading' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Reading' and `provinceid` = $pennsylvania_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $pennsylvania_id as provinceid,'Scranton' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Scranton' and `provinceid` = $pennsylvania_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $pennsylvania_id as provinceid,'Bethlehem' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Bethlehem' and `provinceid` = $pennsylvania_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $pennsylvania_id as provinceid,'Lancaster' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Lancaster' and `provinceid` = $pennsylvania_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $illinois_id as provinceid,'Chicago' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Chicago' and `provinceid` = $illinois_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $illinois_id as provinceid,'Aurora' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Aurora' and `provinceid` = $illinois_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $illinois_id as provinceid,'Rockford' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Rockford' and `provinceid` = $illinois_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $illinois_id as provinceid,'Joliet' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Joliet' and `provinceid` = $illinois_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $illinois_id as provinceid,'Naperville' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Naperville' and `provinceid` = $illinois_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $illinois_id as provinceid,'Springfield' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Springfield' and `provinceid` = $illinois_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $illinois_id as provinceid,'Peoria' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Peoria' and `provinceid` = $illinois_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $illinois_id as provinceid,'North Peoria' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'North Peoria' and `provinceid` = $illinois_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $illinois_id as provinceid,'Elgin' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Elgin' and `provinceid` = $illinois_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $illinois_id as provinceid,'Waukegan' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Waukegan' and `provinceid` = $illinois_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $illinois_id as provinceid,'Champaign' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Champaign' and `provinceid` = $illinois_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $illinois_id as provinceid,'Cicero' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Cicero' and `provinceid` = $illinois_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $michigan_id as provinceid,'Detroit' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Detroit' and `provinceid` = $michigan_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $michigan_id as provinceid,'Grand Rapids' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Grand Rapids' and `provinceid` = $michigan_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $michigan_id as provinceid,'Warren' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Warren' and `provinceid` = $michigan_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $michigan_id as provinceid,'Sterling Heights' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Sterling Heights' and `provinceid` = $michigan_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $michigan_id as provinceid,'Ann Arbor' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Ann Arbor' and `provinceid` = $michigan_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $michigan_id as provinceid,'Lansing' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Lansing' and `provinceid` = $michigan_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $michigan_id as provinceid,'Flint' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Flint' and `provinceid` = $michigan_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $michigan_id as provinceid,'Dearborn' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Dearborn' and `provinceid` = $michigan_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $michigan_id as provinceid,'Livonia' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Livonia' and `provinceid` = $michigan_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $michigan_id as provinceid,'Troy' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Troy' and `provinceid` = $michigan_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $michigan_id as provinceid,'Westland' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Westland' and `provinceid` = $michigan_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $michigan_id as provinceid,'Farmington Hills' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Farmington Hills' and `provinceid` = $michigan_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $ohio_id as provinceid,'Columbus' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Columbus' and `provinceid` = $ohio_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $ohio_id as provinceid,'Cleveland' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Cleveland' and `provinceid` = $ohio_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $ohio_id as provinceid,'Cincinnati' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Cincinnati' and `provinceid` = $ohio_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $ohio_id as provinceid,'Toledo' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Toledo' and `provinceid` = $ohio_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $ohio_id as provinceid,'Akron' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Akron' and `provinceid` = $ohio_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $ohio_id as provinceid,'Dayton' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Dayton' and `provinceid` = $ohio_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $ohio_id as provinceid,'Parma' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Parma' and `provinceid` = $ohio_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $ohio_id as provinceid,'Canton' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Canton' and `provinceid` = $ohio_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $ohio_id as provinceid,'Youngstown' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Youngstown' and `provinceid` = $ohio_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $ohio_id as provinceid,'Lorain' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Lorain' and `provinceid` = $ohio_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $colorado_id as provinceid,'Denver' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Denver' and `provinceid` = $colorado_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $colorado_id as provinceid,'Colorado Springs' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Colorado Springs' and `provinceid` = $colorado_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $colorado_id as provinceid,'Aurora' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Aurora' and `provinceid` = $colorado_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $colorado_id as provinceid,'Fort Collins' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Fort Collins' and `provinceid` = $colorado_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $colorado_id as provinceid,'Lakewood' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Lakewood' and `provinceid` = $colorado_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $colorado_id as provinceid,'Thornton' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Thornton' and `provinceid` = $colorado_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $colorado_id as provinceid,'Arvada' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Arvada' and `provinceid` = $colorado_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $colorado_id as provinceid,'Westminster' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Westminster' and `provinceid` = $colorado_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $colorado_id as provinceid,'Pueblo' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Pueblo' and `provinceid` = $colorado_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $colorado_id as provinceid,'Centennial' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Centennial' and `provinceid` = $colorado_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $wisconsin_id as provinceid,'Milwaukee' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Milwaukee' and `provinceid` = $wisconsin_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $wisconsin_id as provinceid,'Madison' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Madison' and `provinceid` = $wisconsin_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $wisconsin_id as provinceid,'Green Bay' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Green Bay' and `provinceid` = $wisconsin_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $wisconsin_id as provinceid,'Kenosha' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Kenosha' and `provinceid` = $wisconsin_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $wisconsin_id as provinceid,'Racine' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Racine' and `provinceid` = $wisconsin_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $wisconsin_id as provinceid,'Appleton' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Appleton' and `provinceid` = $wisconsin_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $wisconsin_id as provinceid,'Waukesha' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Waukesha' and `provinceid` = $wisconsin_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $wisconsin_id as provinceid,'Eau Claire' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Eau Claire' and `provinceid` = $wisconsin_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $wisconsin_id as provinceid,'Oshkosh' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Oshkosh' and `provinceid` = $wisconsin_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $wisconsin_id as provinceid,'Janesville' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Janesville' and `provinceid` = $wisconsin_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $utah_id as provinceid,'Salt Lake City' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Salt Lake City' and `provinceid` = $utah_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $utah_id as provinceid,'West Valley City' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'West Valley City' and `provinceid` = $utah_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $utah_id as provinceid,'Provo' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Provo' and `provinceid` = $utah_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $utah_id as provinceid,'West Jordan' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'West Jordan' and `provinceid` = $utah_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $utah_id as provinceid,'Orem' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Orem' and `provinceid` = $utah_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $utah_id as provinceid,'Sandy' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Sandy' and `provinceid` = $utah_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $utah_id as provinceid,'Ogden' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Ogden' and `provinceid` = $utah_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $utah_id as provinceid,'St. George' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'St. George' and `provinceid` = $utah_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $utah_id as provinceid,'Layton' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Layton' and `provinceid` = $utah_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $utah_id as provinceid,'Millcreek' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Millcreek' and `provinceid` = $utah_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $virginia_id as provinceid,'Virginia Beach' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Virginia Beach' and `provinceid` = $virginia_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $virginia_id as provinceid,'Norfolk' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Norfolk' and `provinceid` = $virginia_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $virginia_id as provinceid,'Chesapeake' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Chesapeake' and `provinceid` = $virginia_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $virginia_id as provinceid,'Richmond' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Richmond' and `provinceid` = $virginia_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $northcarolina_id as provinceid,'Charlotte' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Charlotte' and `provinceid` = $northcarolina_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $northcarolina_id as provinceid,'Raleigh' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Raleigh' and `provinceid` = $northcarolina_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $northcarolina_id as provinceid,'Greensboro' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Greensboro' and `provinceid` = $northcarolina_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $northcarolina_id as provinceid,'Durham' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Durham' and `provinceid` = $northcarolina_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $northcarolina_id as provinceid,'Winston-Salem' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Winston-Salem' and `provinceid` = $northcarolina_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $northcarolina_id as provinceid,'Fayetteville' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Fayetteville' and `provinceid` = $northcarolina_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $northcarolina_id as provinceid,'Cary' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Cary' and `provinceid` = $northcarolina_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $northcarolina_id as provinceid,'Wilmington' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Wilmington' and `provinceid` = $northcarolina_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $northcarolina_id as provinceid,'High Point' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'High Point' and `provinceid` = $northcarolina_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $northcarolina_id as provinceid,'Greenville' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Greenville' and `provinceid` = $northcarolina_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $southcarolina_id as provinceid,'Columbia' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Columbia' and `provinceid` = $southcarolina_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $southcarolina_id as provinceid,'Charleston' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Charleston' and `provinceid` = $southcarolina_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $southcarolina_id as provinceid,'North Charleston' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'North Charleston' and `provinceid` = $southcarolina_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $southcarolina_id as provinceid,'Mt. Pleasant' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Mt. Pleasant' and `provinceid` = $southcarolina_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $southcarolina_id as provinceid,'Rock Hill' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Rock Hill' and `provinceid` = $southcarolina_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $southcarolina_id as provinceid,'Greenville' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Greenville' and `provinceid` = $southcarolina_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $southcarolina_id as provinceid,'Summerville' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Summerville' and `provinceid` = $southcarolina_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $southcarolina_id as provinceid,'Sumter' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Sumter' and `provinceid` = $southcarolina_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $southcarolina_id as provinceid,'Goose Creek' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Goose Creek' and `provinceid` = $southcarolina_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $southcarolina_id as provinceid,'Hilton Head Island' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Hilton Head Island' and `provinceid` = $southcarolina_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $georgia_id as provinceid,'Atlanta' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Atlanta' and `provinceid` = $georgia_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $georgia_id as provinceid,'Columbus' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Columbus' and `provinceid` = $georgia_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $georgia_id as provinceid,'Augusta' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Augusta' and `provinceid` = $georgia_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $georgia_id as provinceid,'Macon' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Macon' and `provinceid` = $georgia_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $georgia_id as provinceid,'Savannah' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Savannah' and `provinceid` = $georgia_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $georgia_id as provinceid,'Athens' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Athens' and `provinceid` = $georgia_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $georgia_id as provinceid,'Sandy Springs' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Sandy Springs' and `provinceid` = $georgia_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $georgia_id as provinceid,'Roswell' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Roswell' and `provinceid` = $georgia_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $georgia_id as provinceid,'Johns Creek' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Johns Creek' and `provinceid` = $georgia_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $georgia_id as provinceid,'Albany' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Albany' and `provinceid` = $georgia_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $alabama_id as provinceid,'Birmingham' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Birmingham' and `provinceid` = $alabama_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $alabama_id as provinceid,'Huntsville' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Huntsville' and `provinceid` = $alabama_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $alabama_id as provinceid,'Montgomery' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Montgomery' and `provinceid` = $alabama_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $alabama_id as provinceid,'Mobile' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Mobile' and `provinceid` = $alabama_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $alabama_id as provinceid,'Tuscaloosa' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Tuscaloosa' and `provinceid` = $alabama_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $alabama_id as provinceid,'Hoover' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Hoover' and `provinceid` = $alabama_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $alabama_id as provinceid,'Dothan' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Dothan' and `provinceid` = $alabama_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $alabama_id as provinceid,'Auburn' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Auburn' and `provinceid` = $alabama_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $ontario_id as provinceid,'Toronto' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Toronto' and `provinceid` = $ontario_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $ontario_id as provinceid,'Ottawa' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Ottawa' and `provinceid` = $ontario_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $ontario_id as provinceid,'Mississauga' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Mississauga' and `provinceid` = $ontario_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $ontario_id as provinceid,'Brampton' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Brampton' and `provinceid` = $ontario_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $ontario_id as provinceid,'Hamilton' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Hamilton' and `provinceid` = $ontario_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $ontario_id as provinceid,'London' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'London' and `provinceid` = $ontario_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $ontario_id as provinceid,'Markham' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Markham' and `provinceid` = $ontario_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $ontario_id as provinceid,'Vaughan' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Vaughan' and `provinceid` = $ontario_id ) LIMIT 1;";
    dbDelta($sql);        
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $ontario_id as provinceid,'Kitchener' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Kitchener' and `provinceid` = $ontario_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $ontario_id as provinceid,'Windsor' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Windsor' and `provinceid` = $ontario_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $britishcolumbia_id as provinceid,'Vancouver' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Vancouver' and `provinceid` = $britishcolumbia_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $britishcolumbia_id as provinceid,'Surrey' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Surrey' and `provinceid` = $britishcolumbia_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $britishcolumbia_id as provinceid,'Burnaby' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Burnaby' and `provinceid` = $britishcolumbia_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $britishcolumbia_id as provinceid,'Richmond' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Richmond' and `provinceid` = $britishcolumbia_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $britishcolumbia_id as provinceid,'Abbotsford' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Abbotsford' and `provinceid` = $britishcolumbia_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $britishcolumbia_id as provinceid,'Coquitlam' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Coquitlam' and `provinceid` = $britishcolumbia_id ) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $britishcolumbia_id as provinceid,'Kelowna' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Kelowna' and `provinceid` = $britishcolumbia_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $britishcolumbia_id as provinceid,'Langley Township' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Langley Township' and `provinceid` = $britishcolumbia_id ) LIMIT 1;";
    dbDelta($sql);        
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $britishcolumbia_id as provinceid,'Saanich' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Saanich' and `provinceid` = $britishcolumbia_id ) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_city (provinceid,name,createtimeutc) SELECT * FROM (SELECT $britishcolumbia_id as provinceid,'Delta' as name,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_city WHERE `name`= 'Delta' and `provinceid` = $britishcolumbia_id ) LIMIT 1;";
    dbDelta($sql);    
}

function dragonecommercereservezyx987_createTable_country_province_city_distance() {
    global $table_name;global $charset_collate;        
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_country_province_city_distance (
        id INTEGER NOT NULL AUTO_INCREMENT,
        city1id INTEGER,
        province1id INTEGER,
        country1id INTEGER,
        city2id INTEGER,
        province2id INTEGER,
        country2id INTEGER,
        flydistancemile DECIMAL(10,2),
        flydistancekm DECIMAL(10,2),
        cardrivedistancemile DECIMAL(10,2),
        cardrivedistancekm DECIMAL(10,2),
        boatdistancemile DECIMAL(10,2),
        boatdistancekm DECIMAL(10,2),
        description TEXT CHARSET utf8,                
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country_province_city_distance (country1id,province1id,country2id,province2id,flydistancemile,flydistancekm,cardrivedistancemile,cardrivedistancekm,createtimeutc) SELECT * FROM (SELECT a.countryid AS country1id,a.id AS province1id,b.countryid AS country2id,b.id AS province2id,2850, 4587, 3775.8, 6077,UTC_TIMESTAMP() FROM " . $table_name . "_province a, " . $table_name . "_province b where a.name='Alabama' and b.name='Alaska') AS tmp WHERE NOT (EXISTS (SELECT * FROM " . $table_name . "_country_province_city_distance a JOIN " . $table_name . "_province b on a.province1id = b.id JOIN " . $table_name . "_province c on a.province1id = c.id WHERE b.`name` = 'Alabama' and c.`name` = 'Alaska') OR EXISTS (SELECT * FROM " . $table_name . "_country_province_city_distance a JOIN " . $table_name . "_province b on a.province1id = b.id JOIN " . $table_name . "_province c on a.province1id = c.id WHERE b.`name` = 'Alaska' and c.`name` = 'Alabama'))  LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_country_province_city_distance (country1id,province1id,country2id,province2id,flydistancemile,flydistancekm,cardrivedistancemile,cardrivedistancekm,createtimeutc) SELECT * FROM (SELECT a.countryid AS country1id,a.id AS province1id,b.countryid AS country2id,b.id AS province2id,1501.9, 2417.1, 1712.5, 2756,UTC_TIMESTAMP() FROM " . $table_name . "_province a, " . $table_name . "_province b where a.name='Alabama' and b.name='Arizona') AS tmp WHERE NOT (EXISTS (SELECT * FROM " . $table_name . "_country_province_city_distance a JOIN " . $table_name . "_province b on a.province1id = b.id JOIN " . $table_name . "_province c on a.province1id = c.id WHERE b.`name` = 'Arizona' and c.`name` = 'Alabama') OR EXISTS (SELECT * FROM " . $table_name . "_country_province_city_distance a JOIN " . $table_name . "_province b on a.province1id = b.id JOIN " . $table_name . "_province c on a.province1id = c.id WHERE b.`name` = 'Alabama' and c.`name` = 'Arizona'))  LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_country_province_city_distance (country1id,province1id,country2id,province2id,flydistancemile,flydistancekm,cardrivedistancemile,cardrivedistancekm,createtimeutc) SELECT * FROM (SELECT a.countryid AS country1id,a.id AS province1id,b.countryid AS country2id,b.id AS province2id, 381, 613.16, 470.4, 757.04,UTC_TIMESTAMP() FROM " . $table_name . "_province a, " . $table_name . "_province b where a.name='Alabama' and b.name='Arkansas') AS tmp WHERE NOT (EXISTS (SELECT * FROM " . $table_name . "_country_province_city_distance a JOIN " . $table_name . "_province b on a.province1id = b.id JOIN " . $table_name . "_province c on a.province1id = c.id WHERE b.`name` = 'Arkansas' and c.`name` = 'Alabama') OR EXISTS (SELECT * FROM " . $table_name . "_country_province_city_distance a JOIN " . $table_name . "_province b on a.province1id = b.id JOIN " . $table_name . "_province c on a.province1id = c.id WHERE b.`name` = 'Alabama' and c.`name` = 'Arkansas'))  LIMIT 1;";
    dbDelta($sql);
}

function dragonecommercereservezyx987_createTable_store() {
    global $table_name;global $charset_collate;
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_store (
        id INTEGER NOT NULL AUTO_INCREMENT,
        countryid INTEGER,
        provinceid INTEGER,
        cityid INTEGER,
        name TEXT CHARSET utf8,
        description TEXT CHARSET utf8,        
        address1 TEXT CHARSET utf8 NOT NULL,
        address2 TEXT CHARSET utf8,
        province TEXT CHARSET utf8 NOT NULL,
        country TEXT CHARSET utf8 NOT NULL,
        postalcode TEXT NOT NULL,
        emailaddress TEXT,
        phonenumber TEXT,        
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
}

function dragonecommercereservezyx987_createTable_product_store() {
    global $table_name;global $charset_collate;
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_product_store (
        id INTEGER NOT NULL AUTO_INCREMENT,
        productid INTEGER NOT NULL,
        storeid INTEGER,
        productquantity INTEGER,                
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
}

function dragonecommercereservezyx987_createTable_groupcategory() {
    global $table_name;global $charset_collate;
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_groupcategory (
        id INTEGER NOT NULL AUTO_INCREMENT,
        name TEXT CHARSET utf8 NOT NULL,
        description TEXT CHARSET utf8,
        priority INTEGER,
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        mandatory TINYINT NOT NULL DEFAULT 1,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_groupcategory (name,description,createtimeutc) SELECT * FROM (SELECT 'productdetailsforcustomertochoose' as name,'product details for customer to choose group category' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_groupcategory WHERE `name`= 'productdetailsforcustomertochoose') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_groupcategory (name,description,createtimeutc) SELECT * FROM (SELECT 'ordershippingdetailsforcustomertochoose' as name,'order shipping details for customer to choose group category' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_groupcategory WHERE `name`= 'ordershippingdetailsforcustomertochoose') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_groupcategory (name,description,createtimeutc) SELECT * FROM (SELECT 'orderhandlingdetailsforcustomertochoose' as name,'order handling details for customer to choose group category' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_groupcategory WHERE `name`= 'orderhandlingdetailsforcustomertochoose') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_groupcategory (name,description,createtimeutc) SELECT * FROM (SELECT 'ordertaxdetailsforcustomertochoose' as name,'order tax details for customer to choose group category' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_groupcategory WHERE `name`= 'ordertaxdetailsforcustomertochoose') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_groupcategory (name,description,createtimeutc) SELECT * FROM (SELECT 'preorderandgotostoretobuyandpickup' as name,'preorder and go to store to buy and pickup' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_groupcategory WHERE `name`= 'preorderandgotostoretobuyandpickup') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_groupcategory (name,description,createtimeutc) SELECT * FROM (SELECT 'discount' as name,'discount group category' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_groupcategory WHERE `name`= 'discount') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_groupcategory (name,description,createtimeutc) SELECT * FROM (SELECT 'coupon' as name,'coupon group category' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_groupcategory WHERE `name`= 'coupon') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_groupcategory (name,description,createtimeutc) SELECT * FROM (SELECT 'onsale' as name,'onsale group category' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_groupcategory WHERE `name`= 'onsale') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_groupcategory (name,description,createtimeutc) SELECT * FROM (SELECT 'clearance' as name,'clearance group category' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_groupcategory WHERE `name`= 'clearance') LIMIT 1;";
    dbDelta($sql);                
    $sql = "INSERT INTO " . $table_name . "_groupcategory (name,description,createtimeutc) SELECT * FROM (SELECT 'clothing' as name,'clothing group category' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_groupcategory WHERE `name`= 'clothing') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_groupcategory (name,description,createtimeutc) SELECT * FROM (SELECT 'shirts' as name,'shirts group category' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_groupcategory WHERE `name`= 'shirts') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_groupcategory (name,description,createtimeutc) SELECT * FROM (SELECT 'pants' as name,'pants group category' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_groupcategory WHERE `name`= 'pants') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_groupcategory (name,description,createtimeutc) SELECT * FROM (SELECT 'men' as name,'men group category' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_groupcategory WHERE `name`= 'men') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_groupcategory (name,description,createtimeutc) SELECT * FROM (SELECT 'women' as name,'women group category' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_groupcategory WHERE `name`= 'women') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_groupcategory (name,description,createtimeutc) SELECT * FROM (SELECT 'children' as name,'children group category' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_groupcategory WHERE `name`= 'children') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_groupcategory (name,description,createtimeutc) SELECT * FROM (SELECT 'newarrival' as name,'newarrival group category' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_groupcategory WHERE `name`= 'newarrival') LIMIT 1;";
    dbDelta($sql);
}

function dragonecommercereservezyx987_createTable_setting() {
    global $table_name;global $charset_collate;
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_setting (
        id INTEGER NOT NULL AUTO_INCREMENT,
        name TEXT CHARSET utf8 NOT NULL,
        value TEXT CHARSET utf8,
        description TEXT CHARSET utf8,
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'COMPANY_NAME' as name, 'Company Name' as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'COMPANY_NAME') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'COMPANY_ADDRESS' as name, 'Company Address' as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'COMPANY_ADDRESS') LIMIT 1;";
    dbDelta($sql);
    //$sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'COMPANY_TIMEZONE' as name, 'America/New_York' as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'COMPANY_TIMEZONE') LIMIT 1;";
    //dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'COMPANY_TIMEZONE_HOURS' as name, '-05:00' as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'COMPANY_TIMEZONE_HOURS') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'RESERVE_NEED_ADMIN_APPROVE' as name,'0' as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'RESERVE_NEED_ADMIN_APPROVE') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'GROUP_CATEGORY_ID_FOR_CUSTOMER_CHOOSE_PRODUCT_DETAILS' as name, (SELECT CAST(id AS CHAR) from " . $table_name . "_groupcategory WHERE name = 'productdetailsforcustomertochoose') as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'GROUP_CATEGORY_ID_FOR_CUSTOMER_CHOOSE_PRODUCT_DETAILS') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'GROUP_CATEGORY_ID_FOR_ORDER_SHIPPING_DETAILS' as name, (SELECT CAST(id AS CHAR) from " . $table_name . "_groupcategory WHERE name = 'ordershippingdetailsforcustomertochoose') as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'GROUP_CATEGORY_ID_FOR_ORDER_SHIPPING_DETAILS') LIMIT 1;";
    dbDelta($sql);        
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'GROUP_CATEGORY_ID_FOR_ORDER_HANDLING_DETAILS' as name, (SELECT CAST(id AS CHAR) from " . $table_name . "_groupcategory WHERE name = 'orderhandlingdetailsforcustomertochoose') as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'GROUP_CATEGORY_ID_FOR_ORDER_HANDLING_DETAILS') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'GROUP_CATEGORY_ID_FOR_ORDER_TAX_DETAILS' as name, (SELECT CAST(id AS CHAR) from " . $table_name . "_groupcategory WHERE name = 'ordertaxdetailsforcustomertochoose') as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'GROUP_CATEGORY_ID_FOR_ORDER_TAX_DETAILS') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'GROUP_CATEGORY_ID_FOR_PREORDER_AND_STORE_BUYPICKUP_DETAILS' as name, (SELECT CAST(id AS CHAR) from " . $table_name . "_groupcategory WHERE name = 'preorderandgotostoretobuyandpickup') as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'GROUP_CATEGORY_ID_FOR_PREORDER_AND_STORE_BUYPICKUP_DETAILS') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'GROUP_CATEGORY_ID_FOR_DISCOUNT' as name, (SELECT CAST(id AS CHAR) from " . $table_name . "_groupcategory WHERE name = 'discount') as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'GROUP_CATEGORY_ID_FOR_DISCOUNT') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'GROUP_CATEGORY_ID_FOR_COUPON' as name, (SELECT CAST(id AS CHAR) from " . $table_name . "_groupcategory WHERE name = 'coupon') as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'GROUP_CATEGORY_ID_FOR_COUPON') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'GROUP_ID_FOR_ORDER_SHIPPING_DETAILS' as name, (SELECT CAST(id AS CHAR) from " . $table_name . "_group WHERE name = 'shippingchargedbytime') as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'GROUP_ID_FOR_ORDER_SHIPPING_DETAILS') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'GROUP_ID_FOR_ORDER_HANDLING_DETAILS' as name, (SELECT CAST(id AS CHAR) from " . $table_name . "_group WHERE name = 'handlingchargedbytime') as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'GROUP_ID_FOR_ORDER_HANDLING_DETAILS') LIMIT 1;";
    dbDelta($sql);
    
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'CURRENCY_UNIT_ID_DEFAULT' as name, (SELECT CAST(id AS CHAR) from " . $table_name . "_currency WHERE name = 'USD') as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'CURRENCY_UNIT_ID_DEFAULT') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'DISTANCE_UNIT_ID_DEFAULT' as name, (SELECT CAST(id AS CHAR) from " . $table_name . "_distance WHERE name = 'mile') as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'DISTANCE_UNIT_ID_DEFAULT') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'WEIGHT_UNIT_ID_DEFAULT' as name, (SELECT CAST(id AS CHAR) from " . $table_name . "_weight WHERE name = 'pound') as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'WEIGHT_UNIT_ID_DEFAULT') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'MAX_PROMOTION_PER_ORDER' as name, '-1' as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'MAX_PROMOTION_PER_ORDER') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'MAX_DISCOUNT_PER_ORDER' as name, '-1' as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'MAX_DISCOUNT_PER_ORDER') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'MAX_COUPON_PER_ORDER' as name, '-1' as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'MAX_COUPON_PER_ORDER') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'ENABLE_PRODUCT_QUANTITY_AUTO_DEDUCT' as name,'0' as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'ENABLE_PRODUCT_QUANTITY_AUTO_DEDUCT') LIMIT 1;";
    dbDelta($sql);
    
    $warn_product_quantity = '10';
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'WARN_PRODUCT_QUANTITY' as name,$warn_product_quantity as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'WARN_PRODUCT_QUANTITY') LIMIT 1;";
    dbDelta($sql);

    $amount_per_page = '40';
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'AMOUNT_PER_PAGE' as name,$amount_per_page as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'AMOUNT_PER_PAGE') LIMIT 1;";
    dbDelta($sql);

    $product_image_size = '800';
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'PRODUCT_IMAGE_SIZE' as name,$product_image_size as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'PRODUCT_IMAGE_SIZE') LIMIT 1;";
    dbDelta($sql);
            
    $product_image_size = '300';
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'DESKTOP_PRODUCT_IMAGE_SIZE' as name,$product_image_size as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'DESKTOP_PRODUCT_IMAGE_SIZE') LIMIT 1;";
    dbDelta($sql);

    $product_image_size = '300';
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'TABLET_PRODUCT_IMAGE_SIZE' as name,$product_image_size as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'TABLET_PRODUCT_IMAGE_SIZE') LIMIT 1;";
    dbDelta($sql);

    $product_image_size = '200';
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'CELLPHONE_PRODUCT_IMAGE_SIZE' as name,$product_image_size as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'CELLPHONE_PRODUCT_IMAGE_SIZE') LIMIT 1;";
    dbDelta($sql);    
    
    
    $product_per_row_quantity = '4';
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'PRODUCT_PER_ROW_LARGE' as name,$product_per_row_quantity as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'PRODUCT_PER_ROW_LARGE') LIMIT 1;";
    dbDelta($sql);

    $product_per_row_quantity = '4';
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'PRODUCT_PER_ROW_MEDIUM' as name,$product_per_row_quantity as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'PRODUCT_PER_ROW_MEDIUM') LIMIT 1;";
    dbDelta($sql);

    $product_per_row_quantity = '2';
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'PRODUCT_PER_ROW_SMALL' as name,$product_per_row_quantity as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'PRODUCT_PER_ROW_SMALL') LIMIT 1;";
    dbDelta($sql);

    $product_per_row_quantity = '2';
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'PRODUCT_PER_ROW_EXTRA_SMALL' as name,$product_per_row_quantity as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'PRODUCT_PER_ROW_EXTRA_SMALL') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'EMAIL_METHOD' as name,(SELECT GROUP_CONCAT(a.id order by id ASC SEPARATOR '|') FROM (SELECT '1' as temp, id FROM " . $table_name . "_emailmethod WHERE name IN ('WordPress Email') order BY id ) a GROUP BY a.temp) as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'EMAIL_METHOD') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'MAILGUN_APIKEY' as name,'' as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'MAILGUN_APIKEY') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'MAILGUN_API_URL' as name,'https://api.mailgun.net/v3/' as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'MAILGUN_API_URL') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'MAILGUN_DOMAIN' as name,'' as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'MAILGUN_DOMAIN') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'MAILGUN_FROMNAME' as name,'' as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'MAILGUN_FROMNAME') LIMIT 1;";
    dbDelta($sql);    
    
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'MAILCHIMP_APIKEY' as name,'' as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'MAILCHIMP_APIKEY') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'MAILCHIMP_API_URL' as name,'https://mandrillapp.com/api/1.0/messages/send' as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'MAILCHIMP_API_URL') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'MAILCHIMP_FROMEMAIL' as name,'' as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'MAILCHIMP_FROMEMAIL') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'MAILCHIMP_FROMNAME' as name,'' as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'MAILCHIMP_FROMNAME') LIMIT 1;";
    dbDelta($sql);    
    
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'SENDGRID_APIKEY' as name,'' as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'SENDGRID_APIKEY') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'SENDGRID_API_URL' as name,'https://api.sendgrid.com/v3/mail/send' as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'SENDGRID_API_URL') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'SENDGRID_FROMEMAIL' as name,'' as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'SENDGRID_FROMEMAIL') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'SENDGRID_FROMNAME' as name,'' as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'SENDGRID_FROMNAME') LIMIT 1;";
    dbDelta($sql);    
        
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'ENABLE_SHIPPING_CHARGE' as name,'1' as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'ENABLE_SHIPPING_CHARGE') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'ENABLE_HANDLING_CHARGE' as name,'0' as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'ENABLE_HANDLING_CHARGE') LIMIT 1;";
    dbDelta($sql);
        
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'USE_GOOGLE_ANALYTICS' as name,'0' as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'USE_GOOGLE_ANALYTICS') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'GOOGLE_ANALYTICS_MEASUREMENT_ID' as name,'' as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'GOOGLE_ANALYTICS_MEASUREMENT_ID') LIMIT 1;";
    dbDelta($sql);            
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'USE_GOOGLE_RECAPTCHA' as name,'0' as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'USE_GOOGLE_RECAPTCHA') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_setting (name,value,createtimeutc) SELECT * FROM (SELECT 'GOOGLE_RECAPTCHA_SITEKEY' as name,'' as value,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_setting WHERE `name`= 'GOOGLE_RECAPTCHA_SITEKEY') LIMIT 1;";
    dbDelta($sql);    
}

function dragonecommercereservezyx987_createTable_chargetype() {
    global $table_name;global $charset_collate;    
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_chargetype (
        id INTEGER NOT NULL AUTO_INCREMENT,
        name TEXT CHARSET utf8 NOT NULL,
        description TEXT CHARSET utf8,
        priority INTEGER,
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_chargetype (name, description,createtimeutc) SELECT * FROM (SELECT 'fixedfees' as name, 'Charge by fixed fees.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_chargetype WHERE `name`= 'fixedfees') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_chargetype (name, description,createtimeutc) SELECT * FROM (SELECT 'time' as name, 'Charge by time..' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_chargetype WHERE `name`= 'time') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_chargetype (name, description,createtimeutc) SELECT * FROM (SELECT 'location' as name, 'Charge by location.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_chargetype WHERE `name`= 'location') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_chargetype (name, description,createtimeutc) SELECT * FROM (SELECT 'subtotal' as name, 'Charge by subtotal.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_chargetype WHERE `name`= 'subtotal') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_chargetype (name, description,createtimeutc) SELECT * FROM (SELECT 'weightandsubtotal' as name, 'Charge by weight and subtotal.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_chargetype WHERE `name`= 'weightandsubtotal') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_chargetype (name, description,createtimeutc) SELECT * FROM (SELECT 'distance' as name, 'Charge by distance.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_chargetype WHERE `name`= 'distance') LIMIT 1;";
    dbDelta($sql);
}

function dragonecommercereservezyx987_createTable_group() {
    global $table_name;global $charset_collate;    
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_group (
        id INTEGER NOT NULL AUTO_INCREMENT,
        groupcategoryid INTEGER,
        name TEXT CHARSET utf8 NOT NULL,
        description TEXT CHARSET utf8,
        priority INTEGER,
        searchable TINYINT NOT NULL DEFAULT 1,
        forallproduct TINYINT NOT NULL DEFAULT 1,
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_group (groupcategoryid,name, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_groupcategory WHERE name = 'productdetailsforcustomertochoose'),'waistlengthcolor_pants' as name,'This pants group has waist, length and color for customers to choose from.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group WHERE `name`= 'waistlengthcolor_pants') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_group (groupcategoryid,name, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_groupcategory WHERE name = 'productdetailsforcustomertochoose'),'topping_pizza' as name,'This pizza group has toppings for customers to choose from.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group WHERE `name`= 'topping_pizza') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_group (groupcategoryid,name, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_groupcategory WHERE name = 'productdetailsforcustomertochoose'),'sizecolor_shirt' as name,'This shirt group has size and color for customers to choose from.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group WHERE `name`= 'sizecolor_shirt') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_group (groupcategoryid,name, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_groupcategory WHERE name = 'productdetailsforcustomertochoose'),'stylewaistlengthcolor_jeans' as name,'This jeans group has style, waist, length and color for customers to choose from.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group WHERE `name`= 'stylewaistlengthcolor_jeans') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_group (groupcategoryid,name, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_groupcategory WHERE name = 'ordershippingdetailsforcustomertochoose'),'shippingchargedbyfixedfees' as name,'Shipping fee is the same for all the shipment.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group WHERE `name`= 'shippingchargedbyfixedfees') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_group (groupcategoryid,name, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_groupcategory WHERE name = 'ordershippingdetailsforcustomertochoose'),'shippingchargedbytime' as name,'Shipping is charged by time.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group WHERE `name`= 'shippingchargedbytime') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_group (groupcategoryid,name, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_groupcategory WHERE name = 'ordershippingdetailsforcustomertochoose'),'shippingchargedbylocation' as name,'Shipping is charged by location.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group WHERE `name`= 'shippingchargedbylocation') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_group (groupcategoryid,name, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_groupcategory WHERE name = 'ordershippingdetailsforcustomertochoose'),'shippingchargedbysubtotal' as name,'Shipping is charged by subtotal.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group WHERE `name`= 'shippingchargedbysubtotal') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_group (groupcategoryid,name, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_groupcategory WHERE name = 'ordershippingdetailsforcustomertochoose'),'shippingchargedbyweightandsubtotal' as name,'Shipping is charged by weight and subtotal.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group WHERE `name`= 'shippingchargedbyweightandsubtotal') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_group (groupcategoryid,name, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_groupcategory WHERE name = 'ordershippingdetailsforcustomertochoose'),'shippingchargedbydistance' as name,'Shipping is charged by distance.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group WHERE `name`= 'shippingchargedbydistance') LIMIT 1;";
    dbDelta($sql);
    //handling
    $sql = "INSERT INTO " . $table_name . "_group (groupcategoryid,name, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_groupcategory WHERE name = 'orderhandlingdetailsforcustomertochoose'),'handlingchargedbyfixedfees' as name,'Handling fee is the same for all the shipment.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group WHERE `name`= 'handlingchargedbyfixedfees') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_group (groupcategoryid,name, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_groupcategory WHERE name = 'orderhandlingdetailsforcustomertochoose'),'handlingchargedbytime' as name,'Handling is charged by time.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group WHERE `name`= 'handlingchargedbytime') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_group (groupcategoryid,name, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_groupcategory WHERE name = 'orderhandlingdetailsforcustomertochoose'),'handlingchargedbylocation' as name,'Handling is charged by location.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group WHERE `name`= 'handlingchargedbylocation') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_group (groupcategoryid,name, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_groupcategory WHERE name = 'orderhandlingdetailsforcustomertochoose'),'handlingchargedbysubtotal' as name,'Handling is charged by subtotal.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group WHERE `name`= 'handlingchargedbysubtotal') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_group (groupcategoryid,name, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_groupcategory WHERE name = 'orderhandlingdetailsforcustomertochoose'),'handlingchargedbyweightandsubtotal' as name,'Handling is charged by weight and subtotal.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group WHERE `name`= 'handlingchargedbyweightandsubtotal') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_group (groupcategoryid,name, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_groupcategory WHERE name = 'orderhandlingdetailsforcustomertochoose'),'handlingchargedbydistance' as name,'Handling is charged by distance.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group WHERE `name`= 'handlingchargedbydistance') LIMIT 1;";
    dbDelta($sql);        
    //tax by location
    $sql = "INSERT INTO " . $table_name . "_group (groupcategoryid,name, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_groupcategory WHERE name = 'ordertaxdetailsforcustomertochoose'),'taxchargedbylocation' as name,'Tax is charged by location.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group WHERE `name`= 'taxchargedbylocation') LIMIT 1;";
    dbDelta($sql);    
    //pre-order and go to store to buy and pickup
    $sql = "INSERT INTO " . $table_name . "_group (groupcategoryid,name, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_groupcategory WHERE name = 'preorderandgotostoretobuyandpickup'),'preorderandgotostoretobuyandpickup' as name,'Pre-order and go to store to buy and pickup.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group WHERE `name`= 'preorderandgotostoretobuyandpickup') LIMIT 1;";
    dbDelta($sql);
    //discount and coupon
    $sql = "INSERT INTO " . $table_name . "_group (groupcategoryid,name, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_groupcategory WHERE name = 'discount'),'discount' as name,'Discount.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group WHERE `name`= 'discount') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_group (groupcategoryid,name, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_groupcategory WHERE name = 'coupon'),'coupon' as name,'Coupon.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group WHERE `name`= 'coupon') LIMIT 1;";
    dbDelta($sql);        
}

function dragonecommercereservezyx987_createTable_property() {
    global $table_name;global $charset_collate;        
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_property (
        id INTEGER NOT NULL AUTO_INCREMENT,
        chargetypeid INTEGER,
        name TEXT CHARSET utf8 NOT NULL,
        shownname TEXT CHARSET utf8 NOT NULL,
        description TEXT CHARSET utf8,
        priority INTEGER,
        forallproduct TINYINT NOT NULL DEFAULT 0,
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        mandatory TINYINT NOT NULL DEFAULT 1,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_property (name,shownname,description,createtimeutc) SELECT * FROM (SELECT 'color' as name,'color' as shownname,'color such as red, blue, grey, black, navy' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_property WHERE `name`= 'color') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_property (name,shownname,description,createtimeutc) SELECT * FROM (SELECT 'waistsize' as name,'waist' as shownname,'waist such as 32, 33, 34' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_property WHERE `name`= 'waistsize') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_property (name,shownname,description,createtimeutc) SELECT * FROM (SELECT 'length' as name,'length' as shownname,'length such as 32, 33, 34' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_property WHERE `name`= 'length') LIMIT 1;";
    dbDelta($sql);
    
    $sql = "INSERT INTO " . $table_name . "_property (chargetypeid, name,shownname,description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_chargetype WHERE name = 'fixedfees' LIMIT 1) as chargetypeid, 'shippingchargedbyfixedfees' as name,'shippingchargedbyfixedfees' as shownname,'Shipping fee is the same for all the shipment.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_property WHERE `name`= 'shippingchargedbyfixedfees') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_property (chargetypeid, name,shownname,description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_chargetype WHERE name = 'time' LIMIT 1) as chargetypeid, 'shippingchargedbytime' as name,'shippingchargedbytime' as shownname,'Shipping is charged by time. For example, shipping for 3-5 days charges $7 to customer.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_property WHERE `name`= 'shippingchargedbytime') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_property (chargetypeid, name,shownname,description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_chargetype WHERE name = 'location' LIMIT 1) as chargetypeid, 'shippingchargedbylocation' as name,'shippingchargedbylocation' as shownname,'Shipping is charged by location. For example, charge by customer''s located province/state.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_property WHERE `name`= 'shippingchargedbylocation') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_property (chargetypeid, name,shownname,description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_chargetype WHERE name = 'subtotal' LIMIT 1) as chargetypeid, 'shippingchargedbysubtotal' as name,'shippingchargedbysubtotal' as shownname,'Shipping is charged by subtotal. For example, order below $35, charge $6. Order above $35, free shipping.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_property WHERE `name`= 'shippingchargedbysubtotal') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_property (chargetypeid, name,shownname,description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_chargetype WHERE name = 'weightandsubtotal' LIMIT 1) as chargetypeid, 'shippingchargedbyweightandsubtotal' as name,'shippingchargedbyweightandsubtotal' as shownname,'Shipping is charged by weight and subtotal.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_property WHERE `name`= 'shippingchargedbyweightandsubtotal') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_property (chargetypeid, name,shownname,description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_chargetype WHERE name = 'distance' LIMIT 1) as chargetypeid, 'shippingchargedbydistance' as name,'shippingchargedbydistance' as shownname,'Shipping is charged by distance.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_property WHERE `name`= 'shippingchargedbydistance') LIMIT 1;";
    dbDelta($sql);

    //handling
    $sql = "INSERT INTO " . $table_name . "_property (chargetypeid, name,shownname,description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_chargetype WHERE name = 'fixedfees' LIMIT 1) as chargetypeid, 'handlingchargedbyfixedfees' as name,'handlingchargedbyfixedfees' as shownname,'Handling fee is the same for all the shipment.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_property WHERE `name`= 'handlingchargedbyfixedfees') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_property (chargetypeid, name,shownname,description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_chargetype WHERE name = 'time' LIMIT 1) as chargetypeid, 'handlingchargedbytime' as name,'handlingchargedbytime' as shownname,'Handling is charged by time. For example, handling for 3-5 days charges $7 to customer.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_property WHERE `name`= 'handlingchargedbytime') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_property (chargetypeid, name,shownname,description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_chargetype WHERE name = 'location' LIMIT 1) as chargetypeid, 'handlingchargedbylocation' as name,'handlingchargedbylocation' as shownname,'Handling is charged by location. For example, charge by customer''s located province/state.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_property WHERE `name`= 'handlingchargedbylocation') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_property (chargetypeid, name,shownname,description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_chargetype WHERE name = 'subtotal' LIMIT 1) as chargetypeid, 'handlingchargedbysubtotal' as name,'handlingchargedbysubtotal' as shownname,'Handling is charged by subtotal. For example, order below $35, charge $6. Order above $35, free handling.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_property WHERE `name`= 'handlingchargedbysubtotal') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_property (chargetypeid, name,shownname,description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_chargetype WHERE name = 'weightandsubtotal' LIMIT 1) as chargetypeid, 'handlingchargedbyweightandsubtotal' as name,'handlingchargedbyweightandsubtotal' as shownname,'Handling is charged by weight and subtotal.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_property WHERE `name`= 'handlingchargedbyweightandsubtotal') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_property (chargetypeid, name,shownname,description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_chargetype WHERE name = 'distance' LIMIT 1) as chargetypeid, 'handlingchargedbydistance' as name,'handlingchargedbydistance' as shownname,'Handling is charged by distance.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_property WHERE `name`= 'handlingchargedbydistance') LIMIT 1;";
    dbDelta($sql);

    //tax by location
    $sql = "INSERT INTO " . $table_name . "_property (chargetypeid, name,shownname,description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_chargetype WHERE name = 'location' LIMIT 1) as chargetypeid, 'taxchargedbylocation' as name,'taxchargedbylocation' as shownname,'Tax is charged by location.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_property WHERE `name`= 'taxchargedbylocation') LIMIT 1;";
    dbDelta($sql);
    
    //pre-order and go to store to buy and pickup
    $sql = "INSERT INTO " . $table_name . "_property (name,shownname,description,createtimeutc) SELECT * FROM (SELECT 'preorderandgotostoretobuyandpickup' as name,'preorderandgotostoretobuyandpickup' as shownname,'Pre-order and go to store to buy and pickup.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_property WHERE `name`= 'preorderandgotostoretobuyandpickup') LIMIT 1;";
    dbDelta($sql);

    //discount and coupon
    $sql = "INSERT INTO " . $table_name . "_property (name,shownname,description,createtimeutc) SELECT * FROM (SELECT 'discount' as name,'discount' as shownname,'Discount.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_property WHERE `name`= 'discount') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_property (name,shownname,description,createtimeutc) SELECT * FROM (SELECT 'coupon' as name,'coupon' as shownname,'Coupon.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_property WHERE `name`= 'coupon') LIMIT 1;";
    dbDelta($sql);
        
    $sql = "INSERT INTO " . $table_name . "_property (name,shownname,description,createtimeutc) SELECT * FROM (SELECT 'clothingsize' as name,'size' as shownname,'size such as XL, L, Medium, Small, XS' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_property WHERE `name`= 'clothingsize') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_property (name,shownname,description,createtimeutc) SELECT * FROM (SELECT 'necksize' as name,'size' as shownname,'necksize such as 14 1/2, 15, 15 1/2' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_property WHERE `name`= 'necksize') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_property (name,shownname,description,createtimeutc) SELECT * FROM (SELECT 'pantstype' as name,'type' as shownname,'pants type such as relaxed, slim, skinny, straight, athletic taper, joggers and sweatpants' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_property WHERE `name`= 'pantstype') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_property (name,shownname,description,createtimeutc,mandatory) SELECT * FROM (SELECT 'warranty' as name,'warranty' as shownname,'warranty such as 3 month warranty, 1 year warranty, 3 year warranty' as description,UTC_TIMESTAMP(),0) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_property WHERE `name`= 'warranty') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_property (name,shownname,description,createtimeutc) SELECT * FROM (SELECT 'untailored' as name,'untailored' as shownname,'untailored such as pants length is not tailored yet' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_property WHERE `name`= 'untailored') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_property (name,shownname,description,createtimeutc) SELECT * FROM (SELECT 'shoesize' as name,'size' as shownname,'shoes size such as 39, 40, 41, 41 1/2, 43' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_property WHERE `name`= 'shoesize') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_property (name,shownname,description,createtimeutc) SELECT * FROM (SELECT 'spicylevel' as name,'spicy' as shownname,'spicy level for restaurant food such as not spicy, less spicy, medium spicy, very spicy, extra spicy' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_property WHERE `name`= 'spicylevel') LIMIT 1;";
    dbDelta($sql);
}

function dragonecommercereservezyx987_createTable_group_property() {
    global $table_name;global $charset_collate;    
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_group_property (
        id INTEGER NOT NULL AUTO_INCREMENT,
        groupid INTEGER NOT NULL,
        propertyid INTEGER NOT NULL,
        priority INTEGER,
        description TEXT CHARSET utf8,
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
    //waistlengthcolor_pants
    $sql = "INSERT INTO " . $table_name . "_group_property (groupid,propertyid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_group WHERE name = 'waistlengthcolor_pants' LIMIT 1) as groupid,(SELECT id from " . $table_name . "_property WHERE name = 'color' LIMIT 1) as propertyid, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group_property WHERE `groupid`= (SELECT id from " . $table_name . "_group WHERE name = 'waistlengthcolor_pants' LIMIT 1) AND `propertyid` = (SELECT id from " . $table_name . "_property WHERE name = 'color' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_group_property (groupid,propertyid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_group WHERE name = 'waistlengthcolor_pants' LIMIT 1) as groupid,(SELECT id from " . $table_name . "_property WHERE name = 'waistsize' LIMIT 1) as propertyid, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group_property WHERE `groupid`= (SELECT id from " . $table_name . "_group WHERE name = 'waistlengthcolor_pants' LIMIT 1) AND `propertyid` = (SELECT id from " . $table_name . "_property WHERE name = 'waistsize' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_group_property (groupid,propertyid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_group WHERE name = 'waistlengthcolor_pants' LIMIT 1) as groupid,(SELECT id from " . $table_name . "_property WHERE name = 'length' LIMIT 1) as propertyid, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group_property WHERE `groupid`= (SELECT id from " . $table_name . "_group WHERE name = 'waistlengthcolor_pants' LIMIT 1) AND `propertyid` = (SELECT id from " . $table_name . "_property WHERE name = 'length' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);    
    //shipping
    $sql = "INSERT INTO " . $table_name . "_group_property (groupid,propertyid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_group WHERE name = 'shippingchargedbyfixedfees' LIMIT 1) as groupid,(SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbyfixedfees' LIMIT 1) as propertyid, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group_property WHERE `groupid`= (SELECT id from " . $table_name . "_group WHERE name = 'shippingchargedbyfixedfees' LIMIT 1) AND `propertyid` = (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbyfixedfees' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_group_property (groupid,propertyid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_group WHERE name = 'shippingchargedbytime' LIMIT 1) as groupid,(SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbytime' LIMIT 1) as propertyid, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group_property WHERE `groupid`= (SELECT id from " . $table_name . "_group WHERE name = 'shippingchargedbytime' LIMIT 1) AND `propertyid` = (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbytime' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_group_property (groupid,propertyid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_group WHERE name = 'shippingchargedbylocation' LIMIT 1) as groupid,(SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group_property WHERE `groupid`= (SELECT id from " . $table_name . "_group WHERE name = 'shippingchargedbylocation' LIMIT 1) AND `propertyid` = (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_group_property (groupid,propertyid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_group WHERE name = 'shippingchargedbysubtotal' LIMIT 1) as groupid,(SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbysubtotal' LIMIT 1) as propertyid, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group_property WHERE `groupid`= (SELECT id from " . $table_name . "_group WHERE name = 'shippingchargedbysubtotal' LIMIT 1) AND `propertyid` = (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbysubtotal' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_group_property (groupid,propertyid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_group WHERE name = 'shippingchargedbyweightandsubtotal' LIMIT 1) as groupid,(SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbyweightandsubtotal' LIMIT 1) as propertyid, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group_property WHERE `groupid`= (SELECT id from " . $table_name . "_group WHERE name = 'shippingchargedbyweightandsubtotal' LIMIT 1) AND `propertyid` = (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbyweightandsubtotal' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_group_property (groupid,propertyid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_group WHERE name = 'shippingchargedbydistance' LIMIT 1) as groupid,(SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbydistance' LIMIT 1) as propertyid, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group_property WHERE `groupid`= (SELECT id from " . $table_name . "_group WHERE name = 'shippingchargedbydistance' LIMIT 1) AND `propertyid` = (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbydistance' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);
    //handling
    $sql = "INSERT INTO " . $table_name . "_group_property (groupid,propertyid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_group WHERE name = 'handlingchargedbyfixedfees' LIMIT 1) as groupid,(SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbyfixedfees' LIMIT 1) as propertyid, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group_property WHERE `groupid`= (SELECT id from " . $table_name . "_group WHERE name = 'handlingchargedbyfixedfees' LIMIT 1) AND `propertyid` = (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbyfixedfees' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_group_property (groupid,propertyid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_group WHERE name = 'handlingchargedbytime' LIMIT 1) as groupid,(SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbytime' LIMIT 1) as propertyid, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group_property WHERE `groupid`= (SELECT id from " . $table_name . "_group WHERE name = 'handlingchargedbytime' LIMIT 1) AND `propertyid` = (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbytime' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_group_property (groupid,propertyid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_group WHERE name = 'handlingchargedbylocation' LIMIT 1) as groupid,(SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group_property WHERE `groupid`= (SELECT id from " . $table_name . "_group WHERE name = 'handlingchargedbylocation' LIMIT 1) AND `propertyid` = (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_group_property (groupid,propertyid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_group WHERE name = 'handlingchargedbysubtotal' LIMIT 1) as groupid,(SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbysubtotal' LIMIT 1) as propertyid, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group_property WHERE `groupid`= (SELECT id from " . $table_name . "_group WHERE name = 'handlingchargedbysubtotal' LIMIT 1) AND `propertyid` = (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbysubtotal' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_group_property (groupid,propertyid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_group WHERE name = 'handlingchargedbyweightandsubtotal' LIMIT 1) as groupid,(SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbyweightandsubtotal' LIMIT 1) as propertyid, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group_property WHERE `groupid`= (SELECT id from " . $table_name . "_group WHERE name = 'handlingchargedbyweightandsubtotal' LIMIT 1) AND `propertyid` = (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbyweightandsubtotal' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_group_property (groupid,propertyid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_group WHERE name = 'handlingchargedbydistance' LIMIT 1) as groupid,(SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbydistance' LIMIT 1) as propertyid, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group_property WHERE `groupid`= (SELECT id from " . $table_name . "_group WHERE name = 'handlingchargedbydistance' LIMIT 1) AND `propertyid` = (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbydistance' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);
    //tax by location
    $sql = "INSERT INTO " . $table_name . "_group_property (groupid,propertyid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_group WHERE name = 'taxchargedbylocation' LIMIT 1) as groupid,(SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group_property WHERE `groupid`= (SELECT id from " . $table_name . "_group WHERE name = 'taxchargedbylocation' LIMIT 1) AND `propertyid` = (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);    
    //pre-order and go to store to buy and pickup
    $sql = "INSERT INTO " . $table_name . "_group_property (groupid,propertyid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_group WHERE name = 'preorderandgotostoretobuyandpickup' LIMIT 1) as groupid,(SELECT id from " . $table_name . "_property WHERE name = 'preorderandgotostoretobuyandpickup' LIMIT 1) as propertyid, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group_property WHERE `groupid`= (SELECT id from " . $table_name . "_group WHERE name = 'preorderandgotostoretobuyandpickup' LIMIT 1) AND `propertyid` = (SELECT id from " . $table_name . "_property WHERE name = 'preorderandgotostoretobuyandpickup' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);    
    //discount and coupon
    $sql = "INSERT INTO " . $table_name . "_group_property (groupid,propertyid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_group WHERE name = 'discount' LIMIT 1) as groupid,(SELECT id from " . $table_name . "_property WHERE name = 'discount' LIMIT 1) as propertyid, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group_property WHERE `groupid`= (SELECT id from " . $table_name . "_group WHERE name = 'discount' LIMIT 1) AND `propertyid` = (SELECT id from " . $table_name . "_property WHERE name = 'discount' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_group_property (groupid,propertyid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_group WHERE name = 'coupon' LIMIT 1) as groupid,(SELECT id from " . $table_name . "_property WHERE name = 'coupon' LIMIT 1) as propertyid, UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_group_property WHERE `groupid`= (SELECT id from " . $table_name . "_group WHERE name = 'coupon' LIMIT 1) AND `propertyid` = (SELECT id from " . $table_name . "_property WHERE name = 'coupon' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);
}

function dragonecommercereservezyx987_createTable_propertyvalue() {
    global $table_name;global $charset_collate;    
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_propertyvalue (
        id INTEGER NOT NULL AUTO_INCREMENT,
        propertyid INTEGER NOT NULL,
        name TEXT CHARSET utf8 NOT NULL,
        shownname TEXT CHARSET utf8 NOT NULL,
        description TEXT CHARSET utf8,
        priority INTEGER,        
        start DATETIME,
        end DATETIME,
        minorderweight DECIMAL(15,2),
        maxorderweight DECIMAL(15,2),                
        flyshippingfee DECIMAL(11,2),
        cardriveshippingfee DECIMAL(11,2),
        boatshippingfee DECIMAL(11,2),
        fee DECIMAL(11,2),
        rate DECIMAL(11,2),
        rateperweightunit DECIMAL(15,2),
        lowerweightlimit DECIMAL(15,2),        
        usefee TINYINT NOT NULL DEFAULT 0,
        userate TINYINT NOT NULL DEFAULT 0,        
        additionalfixedcost DECIMAL(11,2),
        chargepercentageofsubtotal DECIMAL(11,2),
        fromcountryid INTEGER,
        fromstateprovinceid INTEGER,
        fromcityid INTEGER,
        fromcountyid INTEGER,        
        tocountryid INTEGER,
        tostateprovinceid INTEGER,
        tocityid INTEGER,
        tocountyid INTEGER,                
        ischargedbytime TINYINT,
        ischargedbylocation TINYINT,
        ischargedbydistance TINYINT,
        ischargedbysubtotal TINYINT,        
        ischargedbyweightandsubtotal TINYINT,        
        ischargedbyfixedfees TINYINT,            
        ischargedbyoriginlocation TINYINT,
        ischargedbydestinationlocation TINYINT,                                
        minshippingdays INTEGER,
        maxshippingdays INTEGER,        
        mindistance DECIMAL(10,2),
        maxdistance DECIMAL(10,2),
        minordersubtotal DECIMAL(11,2),
        maxordersubtotal DECIMAL(11,2),
        taxincludeshipping TINYINT NOT NULL DEFAULT 1,
        taxincludehandling TINYINT NOT NULL DEFAULT 1,
        isdiscount TINYINT NOT NULL DEFAULT 0,
        iscoupon TINYINT NOT NULL DEFAULT 0,
        forallproduct TINYINT NOT NULL DEFAULT 1,        
        code TEXT CHARSET utf8,
        needcode TINYINT NOT NULL DEFAULT 0,                
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
    //color
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'color' LIMIT 1) as propertyid,'red' as name,'Mike''s ''red'' \"blue\" color' as shownname,'red color' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'red' AND propertyid = (SELECT id from " . $table_name . "_property WHERE name = 'color' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'color' LIMIT 1) as propertyid,'blue' as name,'blue' as shownname,'blue color' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'blue' AND propertyid = (SELECT id from " . $table_name . "_property WHERE name = 'color' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'color' LIMIT 1) as propertyid,'white' as name,'white' as shownname,'white color' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'white' AND propertyid = (SELECT id from " . $table_name . "_property WHERE name = 'color' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'color' LIMIT 1) as propertyid,'black' as name,'black' as shownname,'black color' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'black' AND propertyid = (SELECT id from " . $table_name . "_property WHERE name = 'color' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'color' LIMIT 1) as propertyid,'green' as name,'green' as shownname,'green color' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'green' AND propertyid = (SELECT id from " . $table_name . "_property WHERE name = 'color' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);    
    //waistsize    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'waistsize' LIMIT 1) as propertyid,'32' as name,'32' as shownname,'32 waistsize' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= '32' AND propertyid = (SELECT id from " . $table_name . "_property WHERE name = 'waistsize' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'waistsize' LIMIT 1) as propertyid,'34' as name,'34' as shownname,'34 waistsize' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= '34' AND propertyid = (SELECT id from " . $table_name . "_property WHERE name = 'waistsize' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'waistsize' LIMIT 1) as propertyid,'34 1/2' as name,'34 1/2' as shownname,'34 1/2 waistsize' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= '34 1/2' AND propertyid = (SELECT id from " . $table_name . "_property WHERE name = 'waistsize' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'waistsize' LIMIT 1) as propertyid,'35' as name,'35' as shownname,'35 waistsize' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= '35' AND propertyid = (SELECT id from " . $table_name . "_property WHERE name = 'waistsize' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'waistsize' LIMIT 1) as propertyid,'36' as name,'36' as shownname,'36 waistsize' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= '36' AND propertyid = (SELECT id from " . $table_name . "_property WHERE name = 'waistsize' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);
    //length    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'length' LIMIT 1) as propertyid,'32' as name,'32' as shownname,'32 length' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= '32' AND propertyid = (SELECT id from " . $table_name . "_property WHERE name = 'length' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'length' LIMIT 1) as propertyid,'33' as name,'33' as shownname,'33 length' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= '33' AND propertyid = (SELECT id from " . $table_name . "_property WHERE name = 'length' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'length' LIMIT 1) as propertyid,'34' as name,'34' as shownname,'34 length' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= '34' AND propertyid = (SELECT id from " . $table_name . "_property WHERE name = 'length' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'length' LIMIT 1) as propertyid,'35' as name,'35' as shownname,'35 length' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= '35' AND propertyid = (SELECT id from " . $table_name . "_property WHERE name = 'length' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'length' LIMIT 1) as propertyid,'36' as name,'36' as shownname,'36 length' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= '36' AND propertyid = (SELECT id from " . $table_name . "_property WHERE name = 'length' LIMIT 1)) LIMIT 1;";
    dbDelta($sql);    
    //shipping
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbyfixedfees' LIMIT 1) as propertyid,'shippingchargedbyfixedfees5' as name,'Shipping fee $5' as shownname,'Shipping is charged by fixed fees 5.' as description,5,1,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbyfixedfees5') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbyfixedfees' LIMIT 1) as propertyid,'shippingchargedbyfixedfees10' as name,'Shipping fee $10' as shownname,'Shipping is charged by fixed fees 10.' as description,10,1,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbyfixedfees10') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbyfixedfees' LIMIT 1) as propertyid,'shippingchargedbyfixedfees15' as name,'Shipping fee $15' as shownname,'Shipping is charged by fixed fees 15.' as description,15,1,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbyfixedfees15') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbyfixedfees' LIMIT 1) as propertyid,'shippingchargedbyfixedfees20' as name,'Shipping fee $20' as shownname,'Shipping is charged by fixed fees 20.' as description,20,1,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbyfixedfees20') LIMIT 1;";
    dbDelta($sql);    
    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minshippingdays,maxshippingdays,minordersubtotal,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbytime' LIMIT 1) as propertyid,'shippingchargedbytime5to7daysfree50' as name,'Shipping is 0 for 5 to 7 days and subtotal over 50' as shownname,'Shipping is charged by time 5 to 7 business days and free for subtotal over 50.' as description,0 as fee,1 as usefee,5 as minshippingdays,7 as maxshippingdays,50 as minordersubtotal,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbytime5to7daysfree50') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minshippingdays,maxshippingdays,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbytime' LIMIT 1) as propertyid,'shippingchargedbytime3to5days7' as name,'Shipping is $7 for 3 to 5 days' as shownname,'Shipping is charged by time 3 to 5 business days for 7.' as description,7 as fee,1 as usefee,3 as minshippingdays,5 as maxshippingdays,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbytime3to5days7') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minshippingdays,maxshippingdays,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbytime' LIMIT 1) as propertyid,'shippingchargedbytime2to3days17' as name,'Shipping is $17 for 2 to 3 days' as shownname,'Shipping is charged by time 2 to 3 business days for 17.' as description,17 as fee,1 as usefee,2 as minshippingdays,3 as maxshippingdays,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbytime2to3days17') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minshippingdays,maxshippingdays,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbytime' LIMIT 1) as propertyid,'shippingchargedbytime1to2days22' as name,'Shipping is $22 for 1 to 2 days' as shownname,'Shipping is charged by time 1 to 2 business days for 22.' as description,22 as fee,1 as usefee,1 as minshippingdays,2 as maxshippingdays,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbytime1to2days22') LIMIT 1;";
    dbDelta($sql);            
    //shippingchargedbylocation
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincealabama' as name,'Shipping to Alabama' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Alabama' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincealabama') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincealaska' as name,'Shipping to Alaska' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Alaska' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincealaska') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincearizona' as name,'Shipping to Arizona' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Arizona' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincearizona') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincearkansas' as name,'Shipping to Arkansas' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Arkansas' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincearkansas') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincecalifornia' as name,'Shipping to California' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'California' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincecalifornia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincecolorado' as name,'Shipping to Colorado' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Colorado' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincecolorado') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovinceconnecticut' as name,'Shipping to Connecticut' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Connecticut' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovinceconnecticut') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincedelaware' as name,'Shipping to Delaware' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Delaware' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincedelaware') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovinceflorida' as name,'Shipping to Florida' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Florida' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovinceflorida') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincegeorgia' as name,'Shipping to Georgia' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Georgia' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincegeorgia') LIMIT 1;";
    dbDelta($sql);
    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincehawaii' as name,'Shipping to Hawaii' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Hawaii' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincehawaii') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovinceidaho' as name,'Shipping to Idaho' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Idaho' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovinceidaho') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovinceillinois' as name,'Shipping to Illinois' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Illinois' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovinceillinois') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovinceindiana' as name,'Shipping to Indiana' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Indiana' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovinceindiana') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovinceiowa' as name,'Shipping to Iowa' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Iowa' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovinceiowa') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincekansas' as name,'Shipping to Kansas' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Kansas' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincekansas') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincekentucky' as name,'Shipping to Kentucky' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Kentucky' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincekentucky') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincelouisiana' as name,'Shipping to Louisiana' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Louisiana' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincelouisiana') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincemaine' as name,'Shipping to Maine' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Maine' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincemaine') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincemaryland' as name,'Shipping to Maryland' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Maryland' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincemaryland') LIMIT 1;";
    dbDelta($sql);
    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincemassachusetts' as name,'Shipping to Massachusetts' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Massachusetts' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincemassachusetts') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincemichigan' as name,'Shipping to Michigan' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Michigan' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincemichigan') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovinceminnesota' as name,'Shipping to Minnesota' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Minnesota' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovinceminnesota') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincemississippi' as name,'Shipping to Mississippi' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Mississippi' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincemississippi') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincemissouri' as name,'Shipping to Missouri' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Missouri' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincemissouri') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincemontana' as name,'Shipping to Montana' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Montana' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincemontana') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincenebraska' as name,'Shipping to Nebraska' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Nebraska' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincenebraska') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincenevada' as name,'Shipping to Nevada' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Nevada' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincenevada') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincenewhampshire' as name,'Shipping to New Hampshire' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'New Hampshire' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincenewhampshire') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincenewjersey' as name,'Shipping to New Jersey' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'New Jersey' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincenewjersey') LIMIT 1;";
    dbDelta($sql);
    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincenewmexico' as name,'Shipping to New Mexico' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'New Mexico' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincenewmexico') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincenewyork' as name,'Shipping to New York' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'New York' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincenewyork') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincenorthcarolina' as name,'Shipping to North Carolina' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'North Carolina' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincenorthcarolina') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincenorthdakota' as name,'Shipping to North Dakota' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'North Dakota' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincenorthdakota') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovinceohio' as name,'Shipping to Ohio' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Ohio' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovinceohio') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovinceoklahoma' as name,'Shipping to Oklahoma' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Oklahoma' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovinceoklahoma') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovinceoregon' as name,'Shipping to Oregon' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Oregon' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovinceoregon') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincepennsylvania' as name,'Shipping to Pennsylvania' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Pennsylvania' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincepennsylvania') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincerhodeisland' as name,'Shipping to Rhode Island' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Rhode Island' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincerhodeisland') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincesouthcarolina' as name,'Shipping to South Carolina' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'South Carolina' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincesouthcarolina') LIMIT 1;";
    dbDelta($sql);
    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincesouthdakota' as name,'Shipping to South Dakota' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'South Dakota' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincesouthdakota') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincetennessee' as name,'Shipping to Tennessee' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Tennessee' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincetennessee') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincetexas' as name,'Shipping to Texas' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Texas' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincetexas') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovinceutah' as name,'Shipping to Utah' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Utah' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovinceutah') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincevermont' as name,'Shipping to Vermont' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Vermont' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincevermont') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincevirginia' as name,'Shipping to Virginia' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Virginia' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincevirginia') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincewashington' as name,'Shipping to Washington' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Washington' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincewashington') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincewashingtondc' as name,'Shipping to Washington, D.C.' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Washington, D.C.' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincewashingtondc') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincewestvirginia' as name,'Shipping to West Virginia' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'West Virginia' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincewestvirginia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincewisconsin' as name,'Shipping to Wisconsin' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Wisconsin' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincewisconsin') LIMIT 1;";
    dbDelta($sql);
    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincewyoming' as name,'Shipping to Wyoming' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Wyoming' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincewyoming') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincealberta' as name,'Shipping to Alberta' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Alberta' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincealberta') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincebritishcolumbia' as name,'Shipping to British Columbia' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'British Columbia' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincebritishcolumbia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincemanitoba' as name,'Shipping to Manitoba' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Manitoba' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincemanitoba') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincenewbrunswick' as name,'Shipping to New Brunswick' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'New Brunswick' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincenewbrunswick') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincenewfoundlandandlabrador' as name,'Shipping to Newfoundland and Labrador' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Newfoundland and Labrador' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincenewfoundlandandlabrador') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincenovascotia' as name,'Shipping to Nova Scotia' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Nova Scotia' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincenovascotia') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovinceontario' as name,'Shipping to Ontario' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Ontario' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovinceontario') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovinceprinceedwardisland' as name,'Shipping to Prince Edward Island' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Prince Edward Island' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovinceprinceedwardisland') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincequebec' as name,'Shipping to Quebec' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Quebec' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincequebec') LIMIT 1;";
    dbDelta($sql);
    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincesaskatchewan' as name,'Shipping to Saskatchewan' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Saskatchewan' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincesaskatchewan') LIMIT 1;";
    dbDelta($sql);
    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincenorthwestterritories' as name,'Shipping to Northwest Territories' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Northwest Territories' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincenorthwestterritories') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovincenunavut' as name,'Shipping to Nunavut' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Nunavut' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovincenunavut') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbylocation' LIMIT 1) as propertyid,'shippingchargedbylocationstateprovinceyukon' as name,'Shipping to Yukon' as shownname,'Shipping is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Yukon' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbylocationstateprovinceyukon') LIMIT 1;";
    dbDelta($sql);
    
    //shippingchargedbysubtotal    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,maxordersubtotal,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbysubtotal' LIMIT 1) as propertyid,'shippingchargedbysubtotalbelow35charge8' as name,'Shipping is $8 for order below $35' as shownname,'Shipping is charged by subtotal. Order subtotal below 35 charge 8.' as description,8 as fee,1 as usefee, 35 as maxordersubtotal, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbysubtotalbelow35charge8') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minordersubtotal,maxordersubtotal,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbysubtotal' LIMIT 1) as propertyid,'shippingchargedbysubtotalabove35below60charge4' as name,'Shipping is $4 for order between $35 and $60' as shownname,'Shipping is charged by subtotal. Order subtotal above 35 below 60 charge 4.' as description,4 as fee,1 as usefee, 35 as minordersubtotal, 60 as maxordersubtotal, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbysubtotalabove35below60charge4') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minordersubtotal,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbysubtotal' LIMIT 1) as propertyid,'shippingchargedbysubtotalabove60charge0' as name,'Shipping is 0 for order above $60' as shownname,'Shipping is charged by subtotal. Order subtotal above 60 charge 0.' as description,0 as fee,1 as usefee, 60 as minordersubtotal, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbysubtotalabove60charge0') LIMIT 1;";
    dbDelta($sql);

    //shippingchargedbyweightandsubtotal
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,maxordersubtotal,maxorderweight,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbyweightandsubtotal' LIMIT 1) as propertyid,'shippingchargedbyweightandsubtotalsubtotalbelow35weightbelow5charge8' as name,'Shipping is $8 for order below $35 and weight below 5 lbs' as shownname,'Shipping is charged by weight and subtotal. Order subtotal below 35 and weight below 5 charge 8.' as description,8 as fee,1 as usefee, 35 as maxordersubtotal, 5 as maxorderweight, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbyweightandsubtotalsubtotalbelow35weightbelow5charge8') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,maxordersubtotal,minorderweight,maxorderweight,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbyweightandsubtotal' LIMIT 1) as propertyid,'shippingchargedbyweightandsubtotalsubtotalbelow35weightabove5below25charge16' as name,'Shipping is $16 for order below $35 and weight between 5 and 25 lbs' as shownname,'Shipping is charged by weight and subtotal. Order subtotal below 35 and weight above 5 below 25 charge 16.' as description,16 as fee,1 as usefee, 35 as maxordersubtotal, 5 as minorderweight, 25 as maxorderweight, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbyweightandsubtotalsubtotalbelow35weightabove5below25charge16') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,maxordersubtotal,minorderweight,maxorderweight,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbyweightandsubtotal' LIMIT 1) as propertyid,'shippingchargedbyweightandsubtotalsubtotalbelow35weightabove25below50charge24' as name,'Shipping is $24 for order below $35 and weight between 25 and 50 lbs' as shownname,'Shipping is charged by weight and subtotal. Order subtotal below 35 and weight above 25 below 50 charge 24.' as description,24 as fee,1 as usefee, 35 as maxordersubtotal, 25 as minorderweight, 50 as maxorderweight, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbyweightandsubtotalsubtotalbelow35weightabove25below50charge24') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,maxordersubtotal,minorderweight,maxorderweight,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbyweightandsubtotal' LIMIT 1) as propertyid,'shippingchargedbyweightandsubtotalsubtotalbelow35weightabove50below100charge50' as name,'Shipping is $50 for order below $35 and weight between 50 and 100 lbs' as shownname,'Shipping is charged by weight and subtotal. Order subtotal below 35 and weight above 50 below 100 charge 50.' as description,50 as fee,1 as usefee, 35 as maxordersubtotal, 50 as minorderweight, 100 as maxorderweight, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbyweightandsubtotalsubtotalbelow35weightabove50below100charge50') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,maxordersubtotal,minorderweight,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbyweightandsubtotal' LIMIT 1) as propertyid,'shippingchargedbyweightandsubtotalsubtotalbelow35weightabove100charge70' as name,'Shipping is $70 for order below $35 and weight above 100 lbs' as shownname,'Shipping is charged by weight and subtotal. Order subtotal below 35 and weight above 100 charge 70.' as description,70 as fee,1 as usefee, 35 as maxordersubtotal, 100 as minorderweight, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbyweightandsubtotalsubtotalbelow35weightabove100charge70') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minordersubtotal,maxordersubtotal,maxorderweight,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbyweightandsubtotal' LIMIT 1) as propertyid,'shippingchargedbyweightandsubtotalsubtotalabove35below60weightbelow5charge4' as name,'Shipping is $4 for order between $35 and $60 and weight below 5 lbs' as shownname,'Shipping is charged by weight and subtotal. Order subtotal above 35 and below 60 and weight below 5 charge 4.' as description,4 as fee,1 as usefee, 35 as minordersubtotal, 60 as maxordersubtotal, 5 as maxorderweight, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbyweightandsubtotalsubtotalabove35below60weightbelow5charge4') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minordersubtotal,maxordersubtotal,minorderweight,maxorderweight,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbyweightandsubtotal' LIMIT 1) as propertyid,'shippingchargedbyweightandsubtotalsubtotalabove35below60weightabove5below25charge8' as name,'Shipping is $8 for order between $35 and $60 and weight between 5 and 25 lbs' as shownname,'Shipping is charged by weight and subtotal. Order subtotal above 35 and below 60 and weight above 5 and below 25 charge 8.' as description,8 as fee,1 as usefee, 35 as minordersubtotal, 60 as maxordersubtotal, 5 as minorderweight, 25 as maxorderweight, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbyweightandsubtotalsubtotalabove35below60weightabove5below25charge8') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minordersubtotal,maxordersubtotal,minorderweight,maxorderweight,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbyweightandsubtotal' LIMIT 1) as propertyid,'shippingchargedbyweightandsubtotalsubtotalabove35below60weightabove25below50charge12' as name,'Shipping is $12 for order between $35 and $60 and weight between 25 and 50 lbs' as shownname,'Shipping is charged by weight and subtotal. Order subtotal above 35 and below 60 and weight above 25 and below 50 charge 12.' as description,12 as fee,1 as usefee, 35 as minordersubtotal, 60 as maxordersubtotal, 25 as minorderweight, 50 as maxorderweight, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbyweightandsubtotalsubtotalabove35below60weightabove25below50charge12') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minordersubtotal,maxordersubtotal,minorderweight,maxorderweight,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbyweightandsubtotal' LIMIT 1) as propertyid,'shippingchargedbyweightandsubtotalsubtotalabove35below60weightabove50below100charge16' as name,'Shipping is $16 for order between $35 and $60 and weight between 50 and 100 lbs' as shownname,'Shipping is charged by weight and subtotal. Order subtotal above 35 and below 60 and weight above 50 and below 100 charge 16.' as description,16 as fee,1 as usefee, 35 as minordersubtotal, 60 as maxordersubtotal, 50 as minorderweight, 100 as maxorderweight, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbyweightandsubtotalsubtotalabove35below60weightabove50below100charge16') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minordersubtotal,maxordersubtotal,minorderweight,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbyweightandsubtotal' LIMIT 1) as propertyid,'shippingchargedbyweightandsubtotalsubtotalabove35below60weightabove100charge24' as name,'Shipping is $24 for order between $35 and $60 and weight above 100 lbs' as shownname,'Shipping is charged by weight and subtotal. Order subtotal above 35 and below 60 and weight above 100 charge 24.' as description,24 as fee,1 as usefee, 35 as minordersubtotal, 60 as maxordersubtotal, 100 as minorderweight, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbyweightandsubtotalsubtotalabove35below60weightabove100charge24') LIMIT 1;";
    dbDelta($sql);    
        
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minordersubtotal,maxorderweight,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbyweightandsubtotal' LIMIT 1) as propertyid,'shippingchargedbyweightandsubtotalsubtotalabove60weightbelow5charge2' as name,'Shipping is $2 for order above $60 and weight below 5 lbs' as shownname,'Shipping is charged by weight and subtotal. Order subtotal above 60 and weight below 5 charge 2.' as description,2 as fee,1 as usefee, 60 as minordersubtotal, 5 as maxorderweight, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbyweightandsubtotalsubtotalabove60weightbelow5charge2') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minordersubtotal,minorderweight,maxorderweight,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbyweightandsubtotal' LIMIT 1) as propertyid,'shippingchargedbyweightandsubtotalsubtotalabove60weightabove5below25charge4' as name,'Shipping is $4 for order above $60 and weight between 5 and 25 lbs' as shownname,'Shipping is charged by weight and subtotal. Order subtotal above 60 and weight above 5 and below 25 charge 4.' as description,4 as fee,1 as usefee, 60 as minordersubtotal, 5 as minorderweight, 25 as maxorderweight, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbyweightandsubtotalsubtotalabove60weightabove5below25charge4') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minordersubtotal,minorderweight,maxorderweight,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbyweightandsubtotal' LIMIT 1) as propertyid,'shippingchargedbyweightandsubtotalsubtotalabove60weightabove25below50charge6' as name,'Shipping is $6 for order above $60 and weight between 25 and 50 lbs' as shownname,'Shipping is charged by weight and subtotal. Order subtotal above 60 and weight above 25 and below 50 charge 6.' as description,6 as fee,1 as usefee, 60 as minordersubtotal, 25 as minorderweight, 50 as maxorderweight, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbyweightandsubtotalsubtotalabove60weightabove25below50charge6') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minordersubtotal,minorderweight,maxorderweight,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbyweightandsubtotal' LIMIT 1) as propertyid,'shippingchargedbyweightandsubtotalsubtotalabove60weightabove50below100charge8' as name,'Shipping is $8 for order above $60 and weight between 50 and 100 lbs' as shownname,'Shipping is charged by weight and subtotal. Order subtotal above 60 and weight above 50 and below 100 charge 8.' as description,8 as fee,1 as usefee, 60 as minordersubtotal, 50 as minorderweight, 100 as maxorderweight, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbyweightandsubtotalsubtotalabove60weightabove50below100charge8') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minordersubtotal,minorderweight,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbyweightandsubtotal' LIMIT 1) as propertyid,'shippingchargedbyweightandsubtotalsubtotalabove60weightabove100charge0' as name,'Shipping is 0 for order above $60 and weight above 100 lbs' as shownname,'Shipping is charged by weight and subtotal. Order subtotal above 60 and weight above 100 charge 0.' as description,0 as fee,1 as usefee, 60 as minordersubtotal, 100 as minorderweight, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbyweightandsubtotalsubtotalabove60weightabove100charge0') LIMIT 1;";
    dbDelta($sql);

    //shippingchargedbydistance
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,maxdistance,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbydistance' LIMIT 1) as propertyid,'shippingchargedbydistancebelow50charge4' as name,'Shipping is $4 for distance below 50 miles' as shownname,'Shipping is charged by distance. Order distance below 50 charge 4.' as description,4 as fee,1 as usefee, 50 as maxdistance, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbydistancebelow50charge4') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,mindistance,maxdistance,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbydistance' LIMIT 1) as propertyid,'shippingchargedbydistanceabove50below100charge8' as name,'Shipping is $8 for distance between 50 and 100 miles' as shownname,'Shipping is charged by distance. Order distance above 50 and below 100 charge 8.' as description,8 as fee,1 as usefee, 50 as mindistance, 100 as maxdistance, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbydistanceabove50below100charge8') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,mindistance,maxdistance,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbydistance' LIMIT 1) as propertyid,'shippingchargedbydistanceabove100below200charge12' as name,'Shipping is $12 for distance between 100 and 200 miles' as shownname,'Shipping is charged by distance. Order distance above 100 and below 200 charge 12.' as description,12 as fee,1 as usefee, 100 as mindistance, 200 as maxdistance, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbydistanceabove100below200charge12') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,mindistance,maxdistance,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbydistance' LIMIT 1) as propertyid,'shippingchargedbydistanceabove200below500charge16' as name,'Shipping is $16 for distance between 200 and 500 miles' as shownname,'Shipping is charged by distance. Order distance above 200 and below 500 charge 16.' as description,16 as fee,1 as usefee, 200 as mindistance, 500 as maxdistance, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbydistanceabove200below500charge16') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,mindistance,maxdistance,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbydistance' LIMIT 1) as propertyid,'shippingchargedbydistanceabove500below1000charge20' as name,'Shipping is $20 for distance between 500 and 1000 miles' as shownname,'Shipping is charged by distance. Order distance above 500 and below 1000 charge 20.' as description,20 as fee,1 as usefee, 500 as mindistance, 1000 as maxdistance, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbydistanceabove500below1000charge20') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,mindistance,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'shippingchargedbydistance' LIMIT 1) as propertyid,'shippingchargedbydistanceabove1000charge25' as name,'Shipping is $25 for distance above 1000 miles' as shownname,'Shipping is charged by distance. Order distance above 1000 charge 25.' as description,25 as fee,1 as usefee, 1000 as mindistance, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'shippingchargedbydistanceabove1000charge25') LIMIT 1;";
    dbDelta($sql);
    //handling
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbyfixedfees' LIMIT 1) as propertyid,'handlingchargedbyfixedfees5' as name,'Handling $5' as shownname,'Handling is charged by fixed fees 5.' as description,5,1,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbyfixedfees5') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbyfixedfees' LIMIT 1) as propertyid,'handlingchargedbyfixedfees10' as name,'Handling $10' as shownname,'Handling is charged by fixed fees 10.' as description,10,1,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbyfixedfees10') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbyfixedfees' LIMIT 1) as propertyid,'handlingchargedbyfixedfees15' as name,'Handling $15' as shownname,'Handling is charged by fixed fees 15.' as description,15,1,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbyfixedfees15') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbyfixedfees' LIMIT 1) as propertyid,'handlingchargedbyfixedfees20' as name,'Handling $20' as shownname,'Handling is charged by fixed fees 20.' as description,20,1,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbyfixedfees20') LIMIT 1;";
    dbDelta($sql);    
    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minshippingdays,maxshippingdays,minordersubtotal,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbytime' LIMIT 1) as propertyid,'handlingchargedbytime5to7daysfree50' as name,'Handling is 0 for 5 to 7 days and order above $50' as shownname,'Handling is charged by time 5 to 7 business days and free for subtotal over 50.' as description,0 as fee,1 as usefee,5 as minshippingdays,7 as maxshippingdays,50 as minordersubtotal,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbytime5to7daysfree50') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minshippingdays,maxshippingdays,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbytime' LIMIT 1) as propertyid,'handlingchargedbytime3to5days7' as name,'Handling is $7 for 3 to 5 days' as shownname,'Handling is charged by time 3 to 5 business days for 7.' as description,7 as fee,1 as usefee,3 as minshippingdays,5 as maxshippingdays,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbytime3to5days7') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minshippingdays,maxshippingdays,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbytime' LIMIT 1) as propertyid,'handlingchargedbytime2to3days17' as name,'Handling is $17 for 2 to 3 days' as shownname,'Handling is charged by time 2 to 3 business days for 17.' as description,17 as fee,1 as usefee,2 as minshippingdays,3 as maxshippingdays,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbytime2to3days17') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minshippingdays,maxshippingdays,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbytime' LIMIT 1) as propertyid,'handlingchargedbytime1to2days22' as name,'Handling is $22 for 1 to 2 days' as shownname,'Handling is charged by time 1 to 2 business days for 22.' as description,22 as fee,1 as usefee,1 as minshippingdays,2 as maxshippingdays,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbytime1to2days22') LIMIT 1;";
    dbDelta($sql);            
    //handlingchargedbylocation
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincealabama' as name,'Handling to Alabama' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Alabama' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincealabama') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincealaska' as name,'Handling to Alaska' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Alaska' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincealaska') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincearizona' as name,'Handling to Arizona' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Arizona' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincearizona') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincearkansas' as name,'Handling to Arkansas' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Arkansas' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincearkansas') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincecalifornia' as name,'Handling to California' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'California' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincecalifornia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincecolorado' as name,'Handling to Colorado' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Colorado' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincecolorado') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovinceconnecticut' as name,'Handling to Connecticut' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Connecticut' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovinceconnecticut') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincedelaware' as name,'Handling to Delaware' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Delaware' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincedelaware') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovinceflorida' as name,'Handling to Florida' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Florida' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovinceflorida') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincegeorgia' as name,'Handling to Georgia' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Georgia' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincegeorgia') LIMIT 1;";
    dbDelta($sql);
    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincehawaii' as name,'Handling to Hawaii' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Hawaii' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincehawaii') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovinceidaho' as name,'Handling to Idaho' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Idaho' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovinceidaho') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovinceillinois' as name,'Handling to Illinois' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Illinois' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovinceillinois') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovinceindiana' as name,'Handling to Indiana' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Indiana' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovinceindiana') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovinceiowa' as name,'Handling to Iowa' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Iowa' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovinceiowa') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincekansas' as name,'Handling to Kansas' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Kansas' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincekansas') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincekentucky' as name,'Handling to Kentucky' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Kentucky' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincekentucky') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincelouisiana' as name,'Handling to Louisiana' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Louisiana' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincelouisiana') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincemaine' as name,'Handling to Maine' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Maine' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincemaine') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincemaryland' as name,'Handling to Maryland' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Maryland' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincemaryland') LIMIT 1;";
    dbDelta($sql);
    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincemassachusetts' as name,'Handling to Massachusetts' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Massachusetts' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincemassachusetts') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincemichigan' as name,'Handling to Michigan' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Michigan' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincemichigan') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovinceminnesota' as name,'Handling to Minnesota' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Minnesota' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovinceminnesota') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincemississippi' as name,'Handling to Mississippi' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Mississippi' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincemississippi') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincemissouri' as name,'Handling to Missouri' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Missouri' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincemissouri') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincemontana' as name,'Handling to Montana' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Montana' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincemontana') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincenebraska' as name,'Handling to Nebraska' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Nebraska' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincenebraska') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincenevada' as name,'Handling to Nevada' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Nevada' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincenevada') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincenewhampshire' as name,'Handling to New Hampshire' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'New Hampshire' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincenewhampshire') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincenewjersey' as name,'Handling to New Jersey' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'New Jersey' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincenewjersey') LIMIT 1;";
    dbDelta($sql);
    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincenewmexico' as name,'Handling to New Mexico' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'New Mexico' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincenewmexico') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincenewyork' as name,'Handling to New York' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'New York' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincenewyork') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincenorthcarolina' as name,'Handling to North Carolina' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'North Carolina' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincenorthcarolina') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincenorthdakota' as name,'Handling to North Dakota' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'North Dakota' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincenorthdakota') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovinceohio' as name,'Handling to Ohio' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Ohio' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovinceohio') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovinceoklahoma' as name,'Handling to Oklahoma' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Oklahoma' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovinceoklahoma') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovinceoregon' as name,'Handling to Oregon' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Oregon' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovinceoregon') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincepennsylvania' as name,'Handling to Pennsylvania' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Pennsylvania' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincepennsylvania') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincerhodeisland' as name,'Handling to Rhode Island' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Rhode Island' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincerhodeisland') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincesouthcarolina' as name,'Handling to South Carolina' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'South Carolina' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincesouthcarolina') LIMIT 1;";
    dbDelta($sql);
    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincesouthdakota' as name,'Handling to South Dakota' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'South Dakota' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincesouthdakota') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincetennessee' as name,'Handling to Tennessee' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Tennessee' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincetennessee') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincetexas' as name,'Handling to Texas' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Texas' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincetexas') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovinceutah' as name,'Handling to Utah' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Utah' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovinceutah') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincevermont' as name,'Handling to Vermont' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Vermont' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincevermont') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincevirginia' as name,'Handling to Virginia' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Virginia' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincevirginia') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincewashington' as name,'Handling to Washington' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Washington' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincewashington') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincewashingtondc' as name,'Handling to Washington, D.C.' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Washington, D.C.' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincewashingtondc') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincewestvirginia' as name,'Handling to West Virginia' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'West Virginia' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincewestvirginia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincewisconsin' as name,'Handling to Wisconsin' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Wisconsin' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincewisconsin') LIMIT 1;";
    dbDelta($sql);
    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincewyoming' as name,'Handling to Wyoming' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Wyoming' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincewyoming') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincealberta' as name,'Handling to Alberta' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Alberta' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincealberta') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincebritishcolumbia' as name,'Handling to British Columbia' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'British Columbia' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincebritishcolumbia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincemanitoba' as name,'Handling to Manitoba' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Manitoba' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincemanitoba') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincenewbrunswick' as name,'Handling to New Brunswick' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'New Brunswick' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincenewbrunswick') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincenewfoundlandandlabrador' as name,'Handling to Newfoundland and Labrador' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Newfoundland and Labrador' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincenewfoundlandandlabrador') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincenovascotia' as name,'Handling to Nova Scotia' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Nova Scotia' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincenovascotia') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovinceontario' as name,'Handling to Ontario' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Ontario' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovinceontario') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovinceprinceedwardisland' as name,'Handling to Prince Edward Island' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Prince Edward Island' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovinceprinceedwardisland') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincequebec' as name,'Handling to Quebec' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Quebec' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincequebec') LIMIT 1;";
    dbDelta($sql);
    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincesaskatchewan' as name,'Handling to Saskatchewan' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Saskatchewan' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincesaskatchewan') LIMIT 1;";
    dbDelta($sql);
    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincenorthwestterritories' as name,'Handling to Northwest Territories' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Northwest Territories' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincenorthwestterritories') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovincenunavut' as name,'Handling to Nunavut' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Nunavut' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovincenunavut') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,tocountryid,tostateprovinceid,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbylocation' LIMIT 1) as propertyid,'handlingchargedbylocationstateprovinceyukon' as name,'Handling to Yukon' as shownname,'Handling is charged by location state province.' as description,25 as fee,1 as usefee,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Yukon' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbylocationstateprovinceyukon') LIMIT 1;";
    dbDelta($sql);    
    
    //handlingchargedbysubtotal
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,maxordersubtotal,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbysubtotal' LIMIT 1) as propertyid,'handlingchargedbysubtotalbelow35charge8' as name,'Handling is $8 for order below 35' as shownname,'Handling is charged by subtotal. Order subtotal below 35 charge 8.' as description,8 as fee,1 as usefee, 35 as maxordersubtotal, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbysubtotalbelow35charge8') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minordersubtotal,maxordersubtotal,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbysubtotal' LIMIT 1) as propertyid,'handlingchargedbysubtotalabove35below60charge4' as name,'Handling is $4 for order between 35 and 60' as shownname,'Handling is charged by subtotal. Order subtotal above 35 below 60 charge 4.' as description,4 as fee,1 as usefee, 35 as minordersubtotal, 60 as maxordersubtotal, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbysubtotalabove35below60charge4') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minordersubtotal,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbysubtotal' LIMIT 1) as propertyid,'handlingchargedbysubtotalabove60charge0' as name,'Handling is 0 for order above 60' as shownname,'Handling is charged by subtotal. Order subtotal above 60 charge 0.' as description,0 as fee,1 as usefee, 60 as minordersubtotal, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbysubtotalabove60charge0') LIMIT 1;";
    dbDelta($sql);    
    //handlingchargedbyweightandsubtotal
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,maxordersubtotal,maxorderweight,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbyweightandsubtotal' LIMIT 1) as propertyid,'handlingchargedbyweightandsubtotalsubtotalbelow35weightbelow5charge8' as name,'Handling is $8 for order below $35 and weight below 5 lbs' as shownname,'Handling is charged by weight and subtotal. Order subtotal below 35 and weight below 5 charge 8.' as description,8 as fee,1 as usefee, 35 as maxordersubtotal, 5 as maxorderweight, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbyweightandsubtotalsubtotalbelow35weightbelow5charge8') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,maxordersubtotal,minorderweight,maxorderweight,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbyweightandsubtotal' LIMIT 1) as propertyid,'handlingchargedbyweightandsubtotalsubtotalbelow35weightabove5below25charge16' as name,'Handling is $16 for order below $35 and weight between 5 and 25 lbs' as shownname,'Handling is charged by weight and subtotal. Order subtotal below 35 and weight above 5 below 25 charge 16.' as description,16 as fee,1 as usefee, 35 as maxordersubtotal, 5 as minorderweight, 25 as maxorderweight, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbyweightandsubtotalsubtotalbelow35weightabove5below25charge16') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,maxordersubtotal,minorderweight,maxorderweight,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbyweightandsubtotal' LIMIT 1) as propertyid,'handlingchargedbyweightandsubtotalsubtotalbelow35weightabove25below50charge24' as name,'Handling is $24 for order below $35 and weight between 25 and 50 lbs' as shownname,'Handling is charged by weight and subtotal. Order subtotal below 35 and weight above 25 below 50 charge 24.' as description,24 as fee,1 as usefee, 35 as maxordersubtotal, 25 as minorderweight, 50 as maxorderweight, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbyweightandsubtotalsubtotalbelow35weightabove25below50charge24') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,maxordersubtotal,minorderweight,maxorderweight,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbyweightandsubtotal' LIMIT 1) as propertyid,'handlingchargedbyweightandsubtotalsubtotalbelow35weightabove50below100charge50' as name,'Handling is $50 for order below $35 and weight between 50 and 100 lbs' as shownname,'Handling is charged by weight and subtotal. Order subtotal below 35 and weight above 50 below 100 charge 50.' as description,50 as fee,1 as usefee, 35 as maxordersubtotal, 50 as minorderweight, 100 as maxorderweight, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbyweightandsubtotalsubtotalbelow35weightabove50below100charge50') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,maxordersubtotal,minorderweight,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbyweightandsubtotal' LIMIT 1) as propertyid,'handlingchargedbyweightandsubtotalsubtotalbelow35weightabove100charge70' as name,'Handling is $70 for order below $35 and weight above 100 lbs' as shownname,'Handling is charged by weight and subtotal. Order subtotal below 35 and weight above 100 charge 70.' as description,70 as fee,1 as usefee, 35 as maxordersubtotal, 100 as minorderweight, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbyweightandsubtotalsubtotalbelow35weightabove100charge70') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minordersubtotal,maxordersubtotal,maxorderweight,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbyweightandsubtotal' LIMIT 1) as propertyid,'handlingchargedbyweightandsubtotalsubtotalabove35below60weightbelow5charge4' as name,'Handling is $4 for order between $35 and $60 and weight below 5 lbs' as shownname,'Handling is charged by weight and subtotal. Order subtotal above 35 and below 60 and weight below 5 charge 4.' as description,4 as fee,1 as usefee, 35 as minordersubtotal, 60 as maxordersubtotal, 5 as maxorderweight, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbyweightandsubtotalsubtotalabove35below60weightbelow5charge4') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minordersubtotal,maxordersubtotal,minorderweight,maxorderweight,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbyweightandsubtotal' LIMIT 1) as propertyid,'handlingchargedbyweightandsubtotalsubtotalabove35below60weightabove5below25charge8' as name,'Handling is $8 for order between $35 and $60 and weight between 5 and 25 lbs' as shownname,'Handling is charged by weight and subtotal. Order subtotal above 35 and below 60 and weight above 5 and below 25 charge 8.' as description,8 as fee,1 as usefee, 35 as minordersubtotal, 60 as maxordersubtotal, 5 as minorderweight, 25 as maxorderweight, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbyweightandsubtotalsubtotalabove35below60weightabove5below25charge8') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minordersubtotal,maxordersubtotal,minorderweight,maxorderweight,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbyweightandsubtotal' LIMIT 1) as propertyid,'handlingchargedbyweightandsubtotalsubtotalabove35below60weightabove25below50charge12' as name,'Handling is $12 for order between $35 and $60 and weight between 25 and 50 lbs' as shownname,'Handling is charged by weight and subtotal. Order subtotal above 35 and below 60 and weight above 25 and below 50 charge 12.' as description,12 as fee,1 as usefee, 35 as minordersubtotal, 60 as maxordersubtotal, 25 as minorderweight, 50 as maxorderweight, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbyweightandsubtotalsubtotalabove35below60weightabove25below50charge12') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minordersubtotal,maxordersubtotal,minorderweight,maxorderweight,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbyweightandsubtotal' LIMIT 1) as propertyid,'handlingchargedbyweightandsubtotalsubtotalabove35below60weightabove50below100charge16' as name,'Handling is $16 for order between $35 and $60 and weight between 50 and 100 lbs' as shownname,'Handling is charged by weight and subtotal. Order subtotal above 35 and below 60 and weight above 50 and below 100 charge 16.' as description,16 as fee,1 as usefee, 35 as minordersubtotal, 60 as maxordersubtotal, 50 as minorderweight, 100 as maxorderweight, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbyweightandsubtotalsubtotalabove35below60weightabove50below100charge16') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minordersubtotal,maxordersubtotal,minorderweight,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbyweightandsubtotal' LIMIT 1) as propertyid,'handlingchargedbyweightandsubtotalsubtotalabove35below60weightabove100charge24' as name,'Handling is $24 for order between $35 and $60 and weight above 100 lbs' as shownname,'Handling is charged by weight and subtotal. Order subtotal above 35 and below 60 and weight above 100 charge 24.' as description,24 as fee,1 as usefee, 35 as minordersubtotal, 60 as maxordersubtotal, 100 as minorderweight, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbyweightandsubtotalsubtotalabove35below60weightabove100charge24') LIMIT 1;";
    dbDelta($sql);    
        
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minordersubtotal,maxorderweight,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbyweightandsubtotal' LIMIT 1) as propertyid,'handlingchargedbyweightandsubtotalsubtotalabove60weightbelow5charge2' as name,'Handling is $2 for order above $60 and weight below 5 lbs' as shownname,'Handling is charged by weight and subtotal. Order subtotal above 60 and weight below 5 charge 2.' as description,2 as fee,1 as usefee, 60 as minordersubtotal, 5 as maxorderweight, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbyweightandsubtotalsubtotalabove60weightbelow5charge2') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minordersubtotal,minorderweight,maxorderweight,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbyweightandsubtotal' LIMIT 1) as propertyid,'handlingchargedbyweightandsubtotalsubtotalabove60weightabove5below25charge4' as name,'Handling is $4 for order above $60 and weight between 5 and 25 lbs' as shownname,'Handling is charged by weight and subtotal. Order subtotal above 60 and weight above 5 and below 25 charge 4.' as description,4 as fee,1 as usefee, 60 as minordersubtotal, 5 as minorderweight, 25 as maxorderweight, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbyweightandsubtotalsubtotalabove60weightabove5below25charge4') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minordersubtotal,minorderweight,maxorderweight,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbyweightandsubtotal' LIMIT 1) as propertyid,'handlingchargedbyweightandsubtotalsubtotalabove60weightabove25below50charge6' as name,'Handling is $6 for order above $60 and weight between 25 and 50 lbs' as shownname,'Handling is charged by weight and subtotal. Order subtotal above 60 and weight above 25 and below 50 charge 6.' as description,6 as fee,1 as usefee, 60 as minordersubtotal, 25 as minorderweight, 50 as maxorderweight, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbyweightandsubtotalsubtotalabove60weightabove25below50charge6') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minordersubtotal,minorderweight,maxorderweight,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbyweightandsubtotal' LIMIT 1) as propertyid,'handlingchargedbyweightandsubtotalsubtotalabove60weightabove50below100charge8' as name,'Handling is $8 for order above $60 and weight between 50 and 100 lbs' as shownname,'Handling is charged by weight and subtotal. Order subtotal above 60 and weight above 50 and below 100 charge 8.' as description,8 as fee,1 as usefee, 60 as minordersubtotal, 50 as minorderweight, 100 as maxorderweight, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbyweightandsubtotalsubtotalabove60weightabove50below100charge8') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,minordersubtotal,minorderweight,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbyweightandsubtotal' LIMIT 1) as propertyid,'handlingchargedbyweightandsubtotalsubtotalabove60weightabove100charge0' as name,'Handling is 0 for order above $60 and weight above 100 lbs' as shownname,'Handling is charged by weight and subtotal. Order subtotal above 60 and weight above 100 charge 0.' as description,0 as fee,1 as usefee, 60 as minordersubtotal, 100 as minorderweight, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbyweightandsubtotalsubtotalabove60weightabove100charge0') LIMIT 1;";
    dbDelta($sql);
    //handlingchargedbydistance
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,maxdistance,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbydistance' LIMIT 1) as propertyid,'handlingchargedbydistancebelow50charge4' as name,'Handling is $4 for distance below 50 miles' as shownname,'Handling is charged by distance. Order distance below 50 charge 4.' as description,4 as fee,1 as usefee, 50 as maxdistance, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbydistancebelow50charge4') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,mindistance,maxdistance,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbydistance' LIMIT 1) as propertyid,'handlingchargedbydistanceabove50below100charge8' as name,'Handling is $8 for distance between 50 and 100 miles' as shownname,'Handling is charged by distance. Order distance above 50 and below 100 charge 8.' as description,8 as fee,1 as usefee, 50 as mindistance, 100 as maxdistance, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbydistanceabove50below100charge8') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,mindistance,maxdistance,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbydistance' LIMIT 1) as propertyid,'handlingchargedbydistanceabove100below200charge12' as name,'Handling is $12 for distance between 100 and 200 miles' as shownname,'Handling is charged by distance. Order distance above 100 and below 200 charge 12.' as description,12 as fee,1 as usefee, 100 as mindistance, 200 as maxdistance, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbydistanceabove100below200charge12') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,mindistance,maxdistance,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbydistance' LIMIT 1) as propertyid,'handlingchargedbydistanceabove200below500charge16' as name,'Handling is $16 for distance between 200 and 500 miles' as shownname,'Handling is charged by distance. Order distance above 200 and below 500 charge 16.' as description,16 as fee,1 as usefee, 200 as mindistance, 500 as maxdistance, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbydistanceabove200below500charge16') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,mindistance,maxdistance,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbydistance' LIMIT 1) as propertyid,'handlingchargedbydistanceabove500below1000charge20' as name,'Handling is $20 for distance between 500 and 1000 miles' as shownname,'Handling is charged by distance. Order distance above 500 and below 1000 charge 20.' as description,20 as fee,1 as usefee, 500 as mindistance, 1000 as maxdistance, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbydistanceabove500below1000charge20') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,mindistance,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'handlingchargedbydistance' LIMIT 1) as propertyid,'handlingchargedbydistanceabove1000charge25' as name,'Handling is $25 for distance above 1000 miles' as shownname,'Handling is charged by distance. Order distance above 1000 charge 25.' as description,25 as fee,1 as usefee, 1000 as mindistance, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'handlingchargedbydistanceabove1000charge25') LIMIT 1;";
    dbDelta($sql);        
    //tax by location
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincealabama' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.04 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Alabama' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincealabama') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincealaska' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Alaska' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincealaska') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincearizona' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.056 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Arizona' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincearizona') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincearkansas' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.065 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Arkansas' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincearkansas') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincecalifornia' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.0725 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'California' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincecalifornia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincecolorado' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.029 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Colorado' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincecolorado') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovinceconnecticut' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.0635 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Connecticut' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovinceconnecticut') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincedelaware' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Delaware' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincedelaware') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovinceflorida' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.06 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Florida' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovinceflorida') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincegeorgia' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.04 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Georgia' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincegeorgia') LIMIT 1;";
    dbDelta($sql);
    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincehawaii' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.04166 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Hawaii' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincehawaii') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovinceidaho' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.06 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Idaho' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovinceidaho') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovinceillinois' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.0625 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Illinois' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovinceillinois') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovinceindiana' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.07 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Indiana' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovinceindiana') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovinceiowa' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.06 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Iowa' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovinceiowa') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincekansas' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.065 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Kansas' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincekansas') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincekentucky' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.06 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Kentucky' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincekentucky') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincelouisiana' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.0445 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Louisiana' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincelouisiana') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincemaine' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.055 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Maine' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincemaine') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincemaryland' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.06 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Maryland' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincemaryland') LIMIT 1;";
    dbDelta($sql);
    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincemassachusetts' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.0625 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Massachusetts' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincemassachusetts') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincemichigan' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.06 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Michigan' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincemichigan') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovinceminnesota' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.06875 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Minnesota' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovinceminnesota') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincemississippi' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.07 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Mississippi' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincemississippi') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincemissouri' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.04225 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Missouri' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincemissouri') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincemontana' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Montana' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincemontana') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincenebraska' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.055 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Nebraska' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincenebraska') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincenevada' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.0685 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Nevada' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincenevada') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincenewhampshire' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'New Hampshire' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincenewhampshire') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincenewjersey' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.06625 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'New Jersey' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincenewjersey') LIMIT 1;";
    dbDelta($sql);
    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincenewmexico' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.05125 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'New Mexico' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincenewmexico') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincenewyork' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.04 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'New York' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincenewyork') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincenorthcarolina' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.0475 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'North Carolina' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincenorthcarolina') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincenorthdakota' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.05 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'North Dakota' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincenorthdakota') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovinceohio' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.0575 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Ohio' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovinceohio') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovinceoklahoma' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.045 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Oklahoma' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovinceoklahoma') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovinceoregon' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Oregon' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovinceoregon') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincepennsylvania' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.06 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Pennsylvania' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincepennsylvania') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincerhodeisland' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.07 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Rhode Island' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincerhodeisland') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincesouthcarolina' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.06 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'South Carolina' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincesouthcarolina') LIMIT 1;";
    dbDelta($sql);
    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincesouthdakota' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.04 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'South Dakota' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincesouthdakota') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincetennessee' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.07 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Tennessee' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincetennessee') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincetexas' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.0625 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Texas' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincetexas') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovinceutah' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.0595 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Utah' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovinceutah') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincevermont' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.06 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Vermont' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincevermont') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincevirginia' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.053 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Virginia' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincevirginia') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincewashington' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.065 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Washington' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincewashington') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincewashingtondc' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.06 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Washington, D.C.' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincewashingtondc') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincewestvirginia' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.06 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'West Virginia' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincewestvirginia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincewisconsin' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.05 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Wisconsin' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincewisconsin') LIMIT 1;";
    dbDelta($sql);
    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincewyoming' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.04 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'USA') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Wyoming' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'USA')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincewyoming') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincealberta' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.05 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Alberta' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincealberta') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincebritishcolumbia' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.12 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'British Columbia' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincebritishcolumbia') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincemanitoba' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.12 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Manitoba' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincemanitoba') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincenewbrunswick' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.15 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'New Brunswick' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincenewbrunswick') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincenewfoundlandandlabrador' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.15 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Newfoundland and Labrador' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincenewfoundlandandlabrador') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincenovascotia' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.15 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Nova Scotia' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincenovascotia') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovinceontario' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.13 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Ontario' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovinceontario') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovinceprinceedwardisland' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.15 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Prince Edward Island' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovinceprinceedwardisland') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincequebec' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.14975 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Quebec' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincequebec') LIMIT 1;";
    dbDelta($sql);
    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincesaskatchewan' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.11 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Saskatchewan' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincesaskatchewan') LIMIT 1;";
    dbDelta($sql);

    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincenorthwestterritories' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.05 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Northwest Territories' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincenorthwestterritories') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovincenunavut' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.05 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Nunavut' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovincenunavut') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,tocountryid,tostateprovinceid,taxincludeshipping,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'taxchargedbylocation' LIMIT 1) as propertyid,'taxchargedbylocationstateprovinceyukon' as name,'Tax' as shownname,'Tax is charged by location state province.' as description,0.05 as rate,1 as userate,(SELECT id from " . $table_name . "_country WHERE name = 'Canada') as tocountryid,(SELECT id from " . $table_name . "_province WHERE name = 'Yukon' and countryid = (SELECT id from " . $table_name . "_country WHERE name = 'Canada')) as tostateprovinceid,1,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'taxchargedbylocationstateprovinceyukon') LIMIT 1;";
    dbDelta($sql);
    
    //pre-order and go to store to buy and pickup    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'preorderandgotostoretobuyandpickup' LIMIT 1) as propertyid,'preorderandgotostoretobuyandpickup' as name,'Pre-order and go to store to buy and pickup' as shownname,'Pre-order and go to store to buy and pickup.' as description,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'preorderandgotostoretobuyandpickup') LIMIT 1;";
    dbDelta($sql);    
    //discount and coupon    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,isdiscount,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'discount' LIMIT 1) as propertyid,'discount1' as name,'Discount' as shownname,'Discount.' as description, 0.9 as rate,1 as userate, 1 as isdiscount,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'discount1') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,minordersubtotal,isdiscount,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'discount' LIMIT 1) as propertyid,'discount2' as name,'Discount' as shownname,'Discount.' as description, 0.8 as rate,1 as userate, 100 as minordersubtotal, 1 as isdiscount,UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'discount2') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,fee,usefee,iscoupon,code,needcode,minordersubtotal,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'coupon' LIMIT 1) as propertyid,'coupon1' as name,'Coupon' as shownname,'Coupon.' as description,10 as fee, 1 as usefee, 1 as iscoupon, 'DRAGON2021' as code, 1 as needcode, 50 as minordersubtotal, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'coupon1') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_propertyvalue (propertyid, name, shownname, description,rate,userate,iscoupon,code,needcode,minordersubtotal,createtimeutc) SELECT * FROM (SELECT (SELECT id from " . $table_name . "_property WHERE name = 'coupon' LIMIT 1) as propertyid,'coupon2' as name,'Coupon' as shownname,'Coupon.' as description,0.90 as rate, 1 as userate, 1 as iscoupon, 'DRAGON2022' as code, 1 as needcode, 50 as minordersubtotal, UTC_TIMESTAMP() as createtimeutc) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_propertyvalue WHERE `name`= 'coupon2') LIMIT 1;";
    dbDelta($sql);    
}

function dragonecommercereservezyx987_createTable_address() {
    global $table_name;global $charset_collate;        
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_address (
        id INTEGER NOT NULL AUTO_INCREMENT,
        uuid TEXT,
        description TEXT CHARSET utf8,
        firstname TEXT CHARSET utf8,
        lastname TEXT CHARSET utf8,
        companyname TEXT CHARSET utf8,
        address1 TEXT CHARSET utf8,
        address2 TEXT CHARSET utf8,
        county TEXT CHARSET utf8,
        city TEXT CHARSET utf8,
        stateprovinceid INTEGER NOT NULL,
        countryid INTEGER NOT NULL,
        zippostalcode TEXT CHARSET utf8,
        phonenumber TEXT CHARSET utf8,
        faxnumber TEXT CHARSET utf8,
        email TEXT CHARSET utf8,
        customattributes TEXT CHARSET utf8,
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
}

function dragonecommercereservezyx987_createTable_language() {
    global $table_name;global $charset_collate;
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_language (
        id INTEGER NOT NULL AUTO_INCREMENT,
        uuid TEXT,
        name TEXT CHARSET utf8,
        languageculture TEXT CHARSET utf8,
        uniqueseocode TEXT CHARSET utf8,
        flagimagefilename TEXT CHARSET utf8,
        limitedtostores TEXT CHARSET utf8,
        defaultcurrencyid INTEGER,
        displayorder INTEGER,
        description TEXT CHARSET utf8,    
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
}

function dragonecommercereservezyx987_createTable_currencyexchangerate() {
    global $table_name;global $charset_collate;
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_currencyexchangerate (
        id INTEGER NOT NULL AUTO_INCREMENT,
        uuid TEXT,
        name TEXT CHARSET utf8,
        description TEXT CHARSET utf8,
        fromcurrencyid INTEGER NOT NULL,
        tocurrencyid INTEGER NOT NULL,
        rate DECIMAL(11,2) NOT NULL,
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
}

function dragonecommercereservezyx987_createTable_order() {
    global $table_name;global $charset_collate;
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_order (
        id INTEGER NOT NULL AUTO_INCREMENT,
        uuid TEXT,
        subtotal DECIMAL(15,6) NOT NULL,
        shippingfee DECIMAL(15,6) NOT NULL,
        handlingfee DECIMAL(15,6) NOT NULL,
        tax DECIMAL(15,6) NOT NULL,
        totalfee DECIMAL(11,2) NOT NULL,
        discountfee DECIMAL(15,6),
        couponfee DECIMAL(15,6),        
        discountids TEXT CHARSET utf8,
        couponids TEXT CHARSET utf8,
        discountdescription TEXT CHARSET utf8,
        discountdescriptionforuser TEXT CHARSET utf8,
        coupondescription TEXT CHARSET utf8,
        coupondescriptionforuser TEXT CHARSET utf8,
        shippingdescription TEXT CHARSET utf8,
        handlingdescription TEXT CHARSET utf8,        
        refundedamount DECIMAL(15,6) NOT NULL,    
        rewardsearned DECIMAL(15,6) NOT NULL,        
        userid INTEGER,
        customeripaddress TEXT CHARSET utf8,
        customerlanguageid INTEGER,
        braintreeresponse TEXT CHARSET utf8,
        braintreeid TEXT CHARSET utf8,
        paypalid TEXT CHARSET utf8,
        stripeid TEXT CHARSET utf8,
        description TEXT CHARSET utf8,        
        shippingfirstname TEXT CHARSET utf8 NOT NULL,
        shippinglastname TEXT CHARSET utf8 NOT NULL,
        shippingname TEXT CHARSET utf8 NOT NULL,
        shippingaddress1 TEXT CHARSET utf8 NOT NULL,
        shippingaddress2 TEXT CHARSET utf8,
        shippingcounty TEXT CHARSET utf8,
        shippingcity TEXT CHARSET utf8 NOT NULL,
        shippingstateprovince TEXT CHARSET utf8 NOT NULL,        
        shippingstateprovinceid INTEGER NOT NULL,
        shippingcountry TEXT CHARSET utf8 NOT NULL,
        shippingcountryid INTEGER NOT NULL,
        shippingzippostalcode TEXT CHARSET utf8,
        shippingphonenumber TEXT CHARSET utf8,
        shippingfaxnumber TEXT CHARSET utf8,
        shippingemail TEXT CHARSET utf8,
        billingfirstname TEXT CHARSET utf8 NOT NULL,
        billinglastname TEXT CHARSET utf8 NOT NULL,
        billingname TEXT CHARSET utf8 NOT NULL,
        billingaddress1 TEXT CHARSET utf8 NOT NULL,
        billingaddress2 TEXT CHARSET utf8,
        billingcounty TEXT CHARSET utf8,
        billingcity TEXT CHARSET utf8 NOT NULL,
        billingstateprovince TEXT CHARSET utf8 NOT NULL,
        billingcountry TEXT CHARSET utf8 NOT NULL,
        billingzippostalcode TEXT CHARSET utf8,
        billingphonenumber TEXT CHARSET utf8,
        billingfaxnumber TEXT CHARSET utf8,
        billingemail TEXT CHARSET utf8,                        
        pickupaddressid INTEGER,
        storeid INTEGER,
        pickupinstore TINYINT NOT NULL DEFAULT 0,
        barcode TEXT CHARSET utf8,
        shipperchargedshippingfee DECIMAL(15,6),
        shippeddate DATETIME,
        orderstatusid INTEGER,
        shippingstatusid INTEGER,
        paymentstatusid INTEGER,
        paymentmethodid INTEGER,
        customercurrencyid INTEGER NOT NULL,
        currencyexchangerateid INTEGER NOT NULL,
        paiddateutc DATETIME,
        shippingmethodid INTEGER,
        processsdescription TEXT CHARSET utf8,        
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        emailsent TINYINT NOT NULL DEFAULT 0,
        isreserve TINYINT NOT NULL DEFAULT 0,
        ordercancelemailsent TINYINT NOT NULL DEFAULT 0,
        ordercanceltimeutc DATETIME,        
        ordercancelrefunded TINYINT NOT NULL DEFAULT 0,
        ordercancelrefundtimeutc DATETIME,                
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
}

function dragonecommercereservezyx987_createTable_product_order() {
    global $table_name;global $charset_collate;
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_product_order (
        id INTEGER NOT NULL AUTO_INCREMENT,
        uuid TEXT,
        orderid INTEGER NOT NULL,
        productid INTEGER NOT NULL,
        productpropertyvalueids TEXT CHARSET utf8 NOT NULL,    
        productdescription TEXT CHARSET utf8 NOT NULL,    
        quantity INTEGER NOT NULL,
        unitpriceincltax DECIMAL(15,6) NOT NULL,
        unitpriceexcltax DECIMAL(15,6) NOT NULL,
        priceincltax DECIMAL(15,6) NOT NULL,
        priceexcltax DECIMAL(15,6) NOT NULL,
        discountamountincltax DECIMAL(15,6) NOT NULL,
        discountamountexcltax DECIMAL(15,6) NOT NULL,
        originalproductcost DECIMAL(15,6) NOT NULL,
        downloadcount INTEGER,
        isdownloadactivated TINYINT NOT NULL DEFAULT 0,
        licensedownloadid INTEGER,
        itemweight DECIMAL(15,2),
        rentalstartdateutc DATETIME,
        rentalenddateutc DATETIME,    
        description TEXT CHARSET utf8,
        isonsale TINYINT NOT NULL DEFAULT 0,        
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
}

function dragonecommercereservezyx987_createTable_order_propertyvalue() {
    global $table_name;global $charset_collate;
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_order_propertyvalue (
        id INTEGER NOT NULL AUTO_INCREMENT,
        orderid INTEGER NOT NULL,
        productid INTEGER,
        propertyvalueid INTEGER NOT NULL,
        propertyvalueids TEXT,        
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
}

function dragonecommercereservezyx987_createTable_order_group() {
    global $table_name;global $charset_collate;
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_order_group (
        id INTEGER NOT NULL AUTO_INCREMENT,
        orderid INTEGER NOT NULL,
        groupid INTEGER NOT NULL,
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
}

function dragonecommercereservezyx987_createTable_processstatus() {
    global $table_name;global $charset_collate;
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_processstatus (
        id INTEGER NOT NULL AUTO_INCREMENT,
        name TEXT CHARSET utf8 NOT NULL,
        description TEXT CHARSET utf8,
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_processstatus (name,description,createtimeutc) SELECT * FROM (SELECT 'reserved' as name,'Reserved but not shipped' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_processstatus WHERE `name`= 'reserved') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_processstatus (name,description,createtimeutc) SELECT * FROM (SELECT 'shipped' as name,'Shipped but not received' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_processstatus WHERE `name`= 'shipped') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_processstatus (name,description,createtimeutc) SELECT * FROM (SELECT 'received' as name,'Received' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_processstatus WHERE `name`= 'received') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_processstatus (name,description,createtimeutc) SELECT * FROM (SELECT 'cancelled' as name,'Cancelled' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_processstatus WHERE `name`= 'cancelled') LIMIT 1;";
    dbDelta($sql);
    $sql = "INSERT INTO " . $table_name . "_processstatus (name,description,createtimeutc) SELECT * FROM (SELECT 'refundedproductnotreturned' as name,'Refunded. But not received product return.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_processstatus WHERE `name`= 'refundedproductnotreturned') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_processstatus (name,description,createtimeutc) SELECT * FROM (SELECT 'refundedproductreturned' as name,'Refunded. Received product return.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_processstatus WHERE `name`= 'refundedproductreturned') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_processstatus (name,description,createtimeutc) SELECT * FROM (SELECT 'lawsuit' as name,'In lawsuit.Not finalized.' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_processstatus WHERE `name`= 'lawsuit') LIMIT 1;";
    dbDelta($sql);    
    $sql = "INSERT INTO " . $table_name . "_processstatus (name,description,createtimeutc) SELECT * FROM (SELECT 'other' as name,'' as description,UTC_TIMESTAMP()) AS tmp WHERE NOT EXISTS (SELECT * FROM " . $table_name . "_processstatus WHERE `name`= 'other') LIMIT 1;";
    dbDelta($sql);
}

function dragonecommercereservezyx987_createTable_product_group() {
    global $table_name;global $charset_collate;
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_product_group (
        id INTEGER NOT NULL AUTO_INCREMENT,
        productid INTEGER NOT NULL,
        groupid INTEGER NOT NULL,
        priority INTEGER,
        description TEXT CHARSET utf8,        
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
}

function dragonecommercereservezyx987_createTable_product_propertyvalue() {
    global $table_name;global $charset_collate;
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_product_propertyvalue (
        id INTEGER NOT NULL AUTO_INCREMENT,
        productid INTEGER NOT NULL,
        propertyvalueids TEXT,
        propertyvalueid INTEGER,
        quantity INTEGER,    
        originalquantity INTEGER,        
        barcode TEXT CHARSET utf8,                
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
}

function dragonecommercereservezyx987_createTable_product_propertyvalue_store() {
    global $table_name;global $charset_collate;
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_product_propertyvalue_store (
        id INTEGER NOT NULL AUTO_INCREMENT,
        productid INTEGER NOT NULL,
        productpropertyvalueid INTEGER NOT NULL,
        storeid INTEGER NOT NULL,
        quantity INTEGER NOT NULL DEFAULT 0,        
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
}

function dragonecommercereservezyx987_createTable_product_quantity_alert() {
    global $table_name;global $charset_collate;
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_product_quantity_alert (
        id INTEGER NOT NULL AUTO_INCREMENT,
        productid INTEGER NOT NULL,
        storeid INTEGER,
        quantity INTEGER,
        size VARCHAR(20) CHARSET utf8,
        waist VARCHAR(20) CHARSET utf8,
        length VARCHAR(20) CHARSET utf8,
        color VARCHAR(20) CHARSET utf8,
        other1 VARCHAR(20) CHARSET utf8,
        other2 VARCHAR(20) CHARSET utf8,
        other3 VARCHAR(20) CHARSET utf8,
        other4 VARCHAR(20) CHARSET utf8,
        other5 VARCHAR(20) CHARSET utf8,
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);    
}

function dragonecommercereservezyx987_createTable_user_token() {
    global $table_name;global $charset_collate;
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_user_token (
        id INTEGER NOT NULL AUTO_INCREMENT,
        userid INTEGER NOT NULL,
        tokenpurpose TEXT,
        token TEXT NOT NULL,        
        tokensentdatetimeutc DATETIME,
        tokenverified TINYINT NOT NULL DEFAULT 0,
        tokenverifiedtimeutc DATETIME,
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
}

function dragonecommercereservezyx987_createTable_user_status() {
    global $table_name;global $charset_collate;
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "_user_status (
        id INTEGER NOT NULL AUTO_INCREMENT,
        userid INTEGER NOT NULL,
        description TEXT,
        user_status TINYINT NOT NULL DEFAULT 0,
        admin_approved TINYINT NOT NULL DEFAULT 0,
        createtimeutc DATETIME NOT NULL,
        updatetimeutc DATETIME,
        status TINYINT NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
    ) $charset_collate;";
    dbDelta($sql);
}

function dragonecommercereservezyx987_createTable_log() {
    global $table_name;global $charset_collate;
    $sql = "CREATE TABLE IF NOT EXISTS " . $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 dragonecommercereservezyx987_create_db() {
    global $wpdb;global $table_name;global $charset_collate;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_dragonecommercereservezyx987';
    dragonecommercereservezyx987_createTable_emailmethod();
    dragonecommercereservezyx987_createTable_department();
    dragonecommercereservezyx987_createTable_product();
    dragonecommercereservezyx987_createTable_currency();
    dragonecommercereservezyx987_createTable_distance();
    dragonecommercereservezyx987_createTable_weight();
    dragonecommercereservezyx987_createTable_slideshow();
    dragonecommercereservezyx987_createTable_country();
    dragonecommercereservezyx987_createTable_province();
    dragonecommercereservezyx987_createTable_city();
    dragonecommercereservezyx987_createTable_country_province_city_distance();
    dragonecommercereservezyx987_createTable_store();
    dragonecommercereservezyx987_createTable_product_store();
    dragonecommercereservezyx987_createTable_groupcategory();
    dragonecommercereservezyx987_createTable_chargetype();
    dragonecommercereservezyx987_createTable_property();
    dragonecommercereservezyx987_createTable_group();
    dragonecommercereservezyx987_createTable_group_property();
    dragonecommercereservezyx987_createTable_propertyvalue();
    dragonecommercereservezyx987_createTable_address();
    dragonecommercereservezyx987_createTable_language();
    dragonecommercereservezyx987_createTable_currencyexchangerate();
    dragonecommercereservezyx987_createTable_order();
    dragonecommercereservezyx987_createTable_product_order();
    dragonecommercereservezyx987_createTable_order_propertyvalue();
    dragonecommercereservezyx987_createTable_order_group();
    dragonecommercereservezyx987_createTable_processstatus();
    dragonecommercereservezyx987_createTable_product_group();
    dragonecommercereservezyx987_createTable_product_propertyvalue();
    dragonecommercereservezyx987_createTable_product_propertyvalue_store();
    dragonecommercereservezyx987_createTable_product_quantity_alert();
    dragonecommercereservezyx987_createTable_user_token();
    dragonecommercereservezyx987_createTable_user_status();
    dragonecommercereservezyx987_createTable_log();
    dragonecommercereservezyx987_createTable_setting();
    
    dragonecommercereservezyx987_additional_creation();
}

register_activation_hook(__FILE__, 'dragonecommercereservezyx987_create_db');

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

function dragonecommercereservezyx987_admin_actions() {
    add_options_page("Dragon Ecommerce Reserve", "Dragon Ecommerce Reserve", 1, "Dragon Ecommerce Reserve", "dragonecommercereservezyx987_admin");
}

add_action('admin_menu', 'dragonecommercereservezyx987_admin_actions');

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

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

function dragonecommercereservezyx987_upload_url() { 
    $upload = wp_upload_dir();
    $upload_url = $upload['baseurl'];
    $upload_url = $upload_url . '/dragonecommercereserve';
    return $upload_url;
}

function dragonecommercereservezyx987_getProducts_not_by_ajax($amountperpage, $pagenumber, $myoffset, $mysortby, $myorder, $searchwords, $departmentid, $minprice, $maxprice) {
    $startDate = empty($_GET['start']) ? '' : sanitize_text_field($_GET['start']);
    $startDate = strip_tags($startDate);
    $startDate = sanitize_text_field(str_ireplace("T"," ",$startDate));
    $startDate = sanitize_text_field(str_ireplace("Z","",$startDate));    
    $endDate = empty($_GET['end']) ? '' : sanitize_text_field($_GET['end']);
    $endDate = strip_tags($endDate);    
    $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_dragonecommercereservezyx987_product';
    $table_name2 = 'wp_dragonecommercereservezyx987_department';
    $table_name5 = 'wp_dragonecommercereservezyx987_currency';                
    $table_name7 = 'wp_dragonecommercereservezyx987_setting';
    $table_name13 = 'wp_dragonecommercereservezyx987_weight';
    $table_name14 = 'wp_dragonecommercereservezyx987_distance';
    $storedprocedure_name = 'wp_dragonecommercereservezyx987_getProductList';
    $productstatus = 1;                                                
    $barcode = "";
    $fromdate = '1000-01-01 00:00:00';            
    $todate = '9999-12-31 23:59:59';        
    if($wpdb->use_mysqli) {
        if($wpdb->dbh->connect_error) {
            die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
        }
        $query = "CALL " . $storedprocedure_name . "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, @outvalue, @outvalue2);";
        $stmt = $wpdb->dbh->prepare($query);
        $types = '';
        $parameterArray = array('');

        $types .= 'i';
        $isonsale = -1;
        $parameterArray[] = &$isonsale;

        $types .= 'i';
        $istaxfree = -1;
        $parameterArray[] = &$istaxfree;
        
        $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[] = &$barcode;
        
        $types .= 'i';
        $parameterArray[] = &$departmentid;        

        $types .= 'd';
        $minprice2 = floatval($minprice);
        $parameterArray[] = &$minprice2;    

        $types .= 'd';
        $maxprice2 = floatval($maxprice);
        $parameterArray[] = &$maxprice2;

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

        $types .= 's';
        $parameterArray[] = &$todate;                
        
        $types .= 'i'; //0: inactive, 1: active, -1: both
        $parameterArray[] = &$productstatus;                    
        
        $parameterArray[0] = $types;
        call_user_func_array(array($stmt, 'bind_param'), $parameterArray);                                
        $stmt->execute();
        $myresult = $stmt->get_result();
        $products = $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();

        $stmt4 = $wpdb->dbh->prepare('SELECT @outvalue2');
        $stmt4->execute();
        $myresult4 = $stmt4->get_result();
        $maxpriceObjArr = $myresult4 === FALSE ? array() : $myresult4->fetch_all(MYSQLI_ASSOC);
        $stmt4->close();
        
        $query = "SELECT s.name AS 'settingname', s.value AS 'settingvalue', c.name AS 'currencyname',c.sign AS 'currencysign',w.name AS 'weightname', w.sign AS 'weightsign',d.name AS 'distancename', d.sign AS 'distancesign' "
                . " FROM $table_name7 s LEFT JOIN $table_name5 c ON c.id = (SELECT CAST(value AS UNSIGNED) AS 'id' FROM $table_name7 "
                . " WHERE name = 'CURRENCY_UNIT_ID_DEFAULT' ) LEFT JOIN $table_name13 w ON w.id = (SELECT CAST(value AS UNSIGNED) AS 'id' FROM $table_name7 "
                . " WHERE name = 'WEIGHT_UNIT_ID_DEFAULT') LEFT JOIN $table_name14 d ON d.id = (SELECT CAST(value AS UNSIGNED) AS 'id' FROM $table_name7 "
                . " WHERE name = 'DISTANCE_UNIT_ID_DEFAULT') where s.status = 1 AND c.status = 1";
        $stmt3 = $wpdb->dbh->prepare($query);
        $stmt3->execute();
        $myresult = $stmt3->get_result();
        $result3 = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
        $stmt3->close();                
                        
        $total = "0";
        foreach ($totalObjArr[0] as $key => $value) {
            if($key === '@outvalue') {
                $total = $value == null ? "0" : $value;
            }    
        }        
        $highestprice = "0";
        foreach ($maxpriceObjArr[0] as $key => $value) {
            if($key === '@outvalue2') {
                $highestprice = $value == null ? "0" : $value;
            }    
        }
        //if product isonsale = 1, onsalestartdateutc > UTC_TIMESTAMP() or a.onsaleenddateutc < UTC_TIMESTAMP(), then use price, not saleprice for customer to buy, isonsale set to 0 on the webpage
        //error_log("at 4450, products: " . json_encode($products));
        for ($i=0; $i<count($products); $i++) {
            if($products[$i]["isonsale"] === 1) {
                if($products[$i]["onsalestartdateutc"] !== null && $products[$i]["onsalestartdateutc"] !== '' && $products[$i]["onsalestartdateutc"] > gmdate("Y-m-d H:i:s")) {
                    $products[$i]["isonsale"] = 0;
                } elseif($products[$i]["onsaleenddateutc"] !== null && $products[$i]["onsaleenddateutc"] !== '' && $products[$i]["onsaleenddateutc"] < gmdate("Y-m-d H:i:s")) {
                    $products[$i]["isonsale"] = 0;
                }                    
            }
        }
        foreach ($products as $product) {
            foreach ($product as $key => $value) {
                $product[$key] = $value === null ? '' : deslash($value);
            }
        }
        //error_log("at 4465, products: " . json_encode($products));
        $result = [];
        $result["product"] = $products;
        $result["total"] = $total;
        $result["settings"] = $result3;
        $result["highestprice"] = $highestprice;        
        return $result;                    
    }
    return [];
}

add_action('wp_ajax_dragonecommercereservezyx987_getChart1Data', 'dragonecommercereservezyx987_getChart1Data');
function dragonecommercereservezyx987_getChart1Data() {
    check_ajax_referer('dragonecommercereservezyx987_getChart1Data', 'dragonecommercereservezyx987_hidden_security_getchart1data');
    if((!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getChart1Data';        
        $frequency = empty($_POST['frequency']) ? '' : sanitize_text_field($_POST['frequency']);
        $frequency = strip_tags($frequency);
        $frequency = $frequency === '' ? '-1' : $frequency;            
        if($frequency !== '14days' && $frequency !== '16weeks' && $frequency !== '12months' && $frequency !== '10years') {
            echo "Error. Please choose a value from the dropdown list.";exit();
        }            
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $query = "CALL " . $storedprocedure_name . "(?);";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 's';
            $parameterArray[] = &$frequency;                    
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $orders = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();            
            
            $result = array();
            foreach ($orders as $order) {
                foreach ($order as $key => $value) {
                    $temp = array();                    
                    $temp["name"] = $key;
                    $temp["value"] = $value === null ? 0 : floatval($value);
                    $result[] = $temp;
                }                
            }                        
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_getChart2Data', 'dragonecommercereservezyx987_getChart2Data');
function dragonecommercereservezyx987_getChart2Data() {
    check_ajax_referer('dragonecommercereservezyx987_getChart2Data', 'dragonecommercereservezyx987_hidden_security_getchart2data');
    if((!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getChart2Data';        
        $frequency = empty($_POST['frequency']) ? '' : sanitize_text_field($_POST['frequency']);
        $frequency = strip_tags($frequency);
        $frequency = $frequency === '' ? '-1' : $frequency;            
        if($frequency !== '14days' && $frequency !== '16weeks' && $frequency !== '12months' && $frequency !== '10years') {
            echo "Error. Please choose a value from the dropdown list.";exit();
        }            
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $query = "CALL " . $storedprocedure_name . "(?);";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 's';
            $parameterArray[] = &$frequency;                    
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $orders = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();            
            $result = array();
            foreach ($orders as $order) {
                foreach ($order as $key => $value) {
                    $temp = array();                    
                    $temp["name"] = $key;
                    $temp["value"] = $value === null ? 0 : intval($value);
                    $result[] = $temp;
                }                
            }                        
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_getChart3Data', 'dragonecommercereservezyx987_getChart3Data');
function dragonecommercereservezyx987_getChart3Data() {
    check_ajax_referer('dragonecommercereservezyx987_getChart3Data', 'dragonecommercereservezyx987_hidden_security_getchart3data');
    if((!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getChart3Data';        
        $frequency = empty($_POST['frequency']) ? '' : sanitize_text_field($_POST['frequency']);
        $frequency = strip_tags($frequency);
        $frequency = $frequency === '' ? '-1' : $frequency;            
        if($frequency !== '14days' && $frequency !== '16weeks' && $frequency !== '12months' && $frequency !== '10years') {
            echo "Error. Please choose a value from the dropdown list.";exit();
        }            
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $query = "CALL " . $storedprocedure_name . "(?);";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 's';
            $parameterArray[] = &$frequency;                    
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $orders = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();            
            //error_log("at 4611, orders: " .json_encode($orders));            
            $result = array();
            foreach ($orders as $order) {
                $temp = array();
                foreach ($order as $key => $value) {
                    if($key ==='name') {                    
                        $temp["name"] = $value;
                    } elseif($key ==='value') {
                        $temp["value"] = $value === null ? 0 : floatval($value);
                    }                    
                }
                $result[] = $temp;                
            }
            //error_log("at 4624, result: " .json_encode($result));            
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_getChart4Data', 'dragonecommercereservezyx987_getChart4Data');
function dragonecommercereservezyx987_getChart4Data() {
    check_ajax_referer('dragonecommercereservezyx987_getChart4Data', 'dragonecommercereservezyx987_hidden_security_getchart4data');
    if((!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getChart4Data';        
        $frequency = empty($_POST['frequency']) ? '' : sanitize_text_field($_POST['frequency']);
        $frequency = strip_tags($frequency);
        $frequency = $frequency === '' ? '-1' : $frequency;            
        if($frequency !== '14days' && $frequency !== '16weeks' && $frequency !== '12months' && $frequency !== '10years') {
            echo "Error. Please choose a value from the dropdown list.";exit();
        }            
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $query = "CALL " . $storedprocedure_name . "(?);";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 's';
            $parameterArray[] = &$frequency;                    
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $orders = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();            
            //error_log("at 4667, orders: " .json_encode($orders));            
            $result = array();
            foreach ($orders as $order) {
                $temp = array();
                foreach ($order as $key => $value) {
                    if($key ==='name') {                    
                        $temp["name"] = $value;
                    } elseif($key ==='value') {
                        $temp["value"] = $value === null ? 0 : intval($value);
                    }                    
                }
                $result[] = $temp;                
            }
            //error_log("at 4680, result: " .json_encode($result));            
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_getChart5Data', 'dragonecommercereservezyx987_getChart5Data');
function dragonecommercereservezyx987_getChart5Data() {
    check_ajax_referer('dragonecommercereservezyx987_getChart5Data', 'dragonecommercereservezyx987_hidden_security_getchart5data');
    if((!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getChart5Data';        
        $frequency = empty($_POST['frequency']) ? '' : sanitize_text_field($_POST['frequency']);
        $frequency = strip_tags($frequency);
        $frequency = $frequency === '' ? '-1' : $frequency;            
        if($frequency !== '14days' && $frequency !== '16weeks' && $frequency !== '12months' && $frequency !== '10years') {
            echo "Error. Please choose a value from the dropdown list.";exit();
        }            
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $query = "CALL " . $storedprocedure_name . "(?, ?);";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

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

            $types .= 's';
            $parameterArray[] = &$frequency;
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $orders = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();            
            //error_log("at 4727, orders: " .json_encode($orders));            
            $result = array();
            foreach ($orders as $order) {
                $temp = array();
                foreach ($order as $key => $value) {
                    if($key ==='name') {                    
                        $temp["name"] = $value;
                    } elseif($key ==='value') {
                        $temp["value"] = $value === null ? 0 : floatval($value);
                    }                    
                }
                $result[] = $temp;                
            }
            //error_log("at 4740, result: " .json_encode($result));            
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_getOrders', 'dragonecommercereservezyx987_getOrders');
function dragonecommercereservezyx987_getOrders() {
    check_ajax_referer('dragonecommercereservezyx987_getOrders', 'dragonecommercereservezyx987_hidden_security_getorders');
    if((!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $startDate = empty($_POST['start']) ? '' : sanitize_text_field($_POST['start']);
        $startDate = strip_tags($startDate);
        $startDate = sanitize_text_field(str_ireplace("T"," ",$startDate));
        $startDate = sanitize_text_field(str_ireplace("Z","",$startDate));        
        $endDate = empty($_POST['end']) ? '' : sanitize_text_field($_POST['end']);
        $endDate = strip_tags($endDate);        
        $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_dragonecommercereservezyx987_product';
        $table_name2 = 'wp_dragonecommercereservezyx987_department';
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getOrderList';
        $mystatus = empty($_POST['mystatus']) ? '-1' : sanitize_text_field($_POST['mystatus']);
        $mystatus = strip_tags($mystatus);
        $mystatus = intval($mystatus);
        $amountperpage = empty($_POST['amountperpage']) ? '10' : sanitize_text_field($_POST['amountperpage']);
        $amountperpage = strip_tags($amountperpage);
        $amountperpage = intval($amountperpage);    
        if($amountperpage === -1) {$amountperpage = 10;};                    
        $pagenumber = empty($_POST['pagenumber']) ? '1' : sanitize_text_field($_POST['pagenumber']);;
        $pagenumber = strip_tags($pagenumber);
        $pagenumber = intval($pagenumber);            
        $myoffset = ($pagenumber - 1) * $amountperpage;        
        $mysortby = empty($_POST['sortby']) ? '' : sanitize_text_field($_POST['sortby']);
        $mysortby = strip_tags($mysortby);
        $mysortby = $mysortby === '' ? 'id' : $mysortby;        
        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : sanitize_text_field($_POST['order']);
        $myorder = strip_tags($myorder);
        $myorder = $myorder === '' ? 'desc' : $myorder;        
        $searchwords = empty($_POST['searchwords']) ? '' : sanitize_text_field($_POST['searchwords']);
        $searchwords = strip_tags($searchwords);
        $searchusername = empty($_POST['searchusername']) ? '' : sanitize_text_field($_POST['searchusername']);
        $searchusername = strip_tags($searchusername);                
        $minprice = empty($_POST['minprice']) ? '0.00' : sanitize_text_field($_POST['minprice']);
        $minprice = strip_tags($minprice);
        $minprice = floatval($minprice);            
        $maxprice = empty($_POST['maxprice']) ? '9999999999999.00' : sanitize_text_field($_POST['maxprice']);
        $maxprice = strip_tags($maxprice);
        $maxprice = floatval($maxprice);                    
        $fromdate = empty($_POST['fromdate']) ? '1000-01-01 00:00:00' : sanitize_text_field($_POST['fromdate']);
        $fromdate = strip_tags($fromdate);            
        $todate = empty($_POST['todate']) ? '9999-12-31 23:59:59' : sanitize_text_field($_POST['todate']);
        $todate = strip_tags($todate);    
        if(dragonecommercereservezyx987_validateDate($fromdate) && dragonecommercereservezyx987_validateDate($todate)) {
            if($fromdate > $todate) {
                echo "Error. From date is later than to date.";exit();                        
            }
        }else{
            echo "Error. Please enter a valid date.";exit();    
        }            
        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 .= 's';
            $tablenameprefix = $wpdb->prefix;
            $parameterArray[] = &$tablenameprefix;
            
            $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[] = &$searchusername;
            
            $types .= 'd';
            $minprice2 = floatval($minprice);
            $parameterArray[] = &$minprice2;    

            $types .= 'd';
            $maxprice2 = floatval($maxprice);
            $parameterArray[] = &$maxprice2;

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

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

            $types .= 'i';
            $parameterArray[] = &$mystatus;        
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $orders = $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 ($orders as $order) {
                foreach ($order as $key => $value) {                
                    $order[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["order"] = $orders;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_saveOrder', 'dragonecommercereservezyx987_saveOrder');
function dragonecommercereservezyx987_saveOrder() {
    check_ajax_referer('dragonecommercereservezyx987_saveOrder', 'dragonecommercereservezyx987_hidden_security_saveorder');
    $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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $orderid_temp = empty($_POST['id']) ? '0' : sanitize_text_field($_POST['id']);
        $orderid_temp = strip_tags($orderid_temp);
        $orderid = intval($orderid_temp);
        
        if($orderid <= 0 || $_POST['status'] === null || $_POST['status'] === '') {echo "Invalid id.";exit();}            

        $emailsent_temp = $_POST['emailsent'] === null ? '' : sanitize_text_field($_POST['emailsent']);
        $emailsent_temp = strip_tags($emailsent_temp);
        $emailsent = $emailsent_temp === '' ? -1 : intval($emailsent_temp);
        
        $ordercancelemailsent_temp = $_POST['ordercancelemailsent'] === null ? '' : sanitize_text_field($_POST['ordercancelemailsent']);
        $ordercancelemailsent_temp = strip_tags($ordercancelemailsent_temp);
        $ordercancelemailsent = $ordercancelemailsent_temp === '' ? -1 : intval($ordercancelemailsent_temp);
        
        $ordercancelrefunded_temp = $_POST['ordercancelrefunded'] === null ? '' : sanitize_text_field($_POST['ordercancelrefunded']);
        $ordercancelrefunded_temp = strip_tags($ordercancelrefunded_temp);
        $ordercancelrefunded = $ordercancelrefunded_temp === '' ? -1 : intval($ordercancelrefunded_temp);

        $ordercanceltimeutc_temp = $_POST['ordercanceltimeutc'] === null ? '' : sanitize_text_field($_POST['ordercanceltimeutc']);
        $ordercanceltimeutc = strip_tags($ordercanceltimeutc_temp);
        $ordercanceltimeutc = trim($ordercanceltimeutc);
        
        $ordercancelrefundtimeutc_temp = $_POST['ordercancelrefundtimeutc'] === null ? '' : sanitize_text_field($_POST['ordercancelrefundtimeutc']);
        $ordercancelrefundtimeutc = strip_tags($ordercancelrefundtimeutc_temp);
        $ordercancelrefundtimeutc = trim($ordercancelrefundtimeutc);
        
        $orderstatus_temp = $_POST['status'] === null ? '' : sanitize_text_field($_POST['status']);
        $orderstatus_temp = strip_tags($orderstatus_temp);
        $orderstatus = $orderstatus_temp === '' ? -1 : intval($orderstatus_temp);

        $description_temp = $_POST['description'] === null ? '' : sanitize_text_field($_POST['description']);
        $description = strip_tags($description_temp);
        $description = trim($description);        
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        if($orderstatus === -1 && $emailsent === -1 && $ordercancelemailsent === -1 && $ordercancelrefunded === -1
           && $ordercanceltimeutc === '' && $ordercancelrefundtimeutc === '' && $description === '') { 
                echo "Please enter a value.";exit();
        }
        if($orderstatus <= 0) { 
                echo "Please choose a reservation status.";exit();
        }        
        if(($ordercanceltimeutc === "" || dragonecommercereservezyx987_validateDate($ordercanceltimeutc)) && 
           ($ordercancelrefundtimeutc === "" || dragonecommercereservezyx987_validateDate($ordercancelrefundtimeutc))) {
            if($ordercanceltimeutc > $ordercancelrefundtimeutc) {
                echo "Error. Reservation refund date is earlier than reservation cancel date.";exit();                        
            }
        }else{
            echo "Error. Please enter a valid date.";exit();    
        }        
        $table_name = 'wp_dragonecommercereservezyx987_order';
        $table_name2 = 'wp_dragonecommercereservezyx987_processstatus';
        $table_name3 = 'wp_dragonecommercereservezyx987_product_order';
        $table_name4 = 'wp_dragonecommercereservezyx987_product';
        $table_name5 = 'wp_dragonecommercereservezyx987_product_propertyvalue';        
        $table_name6 = 'wp_dragonecommercereservezyx987_setting';        
        $finalresult = '';        
        $oldorderstatus = $wpdb->get_var("SELECT status FROM " . $table_name . " WHERE id = " . $orderid );
        if(intval($oldorderstatus) <= 0) {        
            $message = "Old reservation status is negative integer. Reservation id : " . $orderid. ". User id: " . $current_user->data->ID;
            dragonecommercereservezyx987_saveToLogTable($message, 'Admin update reservation', 'info');    
            echo sanitize_text_field($message);
            exit();            
        }
        //validate - when admin enter not 'cancelled', but the cancel date or cancel refund date is not empty, 
        //check these values ordercancelemailsent, ordercancelrefunded, ordercanceltimeutc, ordercancelrefundtimeutc            
        $result = $wpdb->get_results("SELECT id, name from $table_name2 WHERE id= " . $orderstatus . " OR id = " . $oldorderstatus);
        $old_statusname = '';
        $new_statusname = '';                 
        if(count($result) === 2) {
            for($i=0; $i < count($result); $i++) {
                if(intval($result[$i]->id) === $orderstatus) {
                    $new_statusname = $result[$i]->name;
                } elseif(intval($result[$i]->id) === intval($oldorderstatus)) {    
                    $old_statusname = $result[$i]->name;
                }
            }
        }
        if(strtolower($new_statusname) !== 'cancelled' && ($ordercanceltimeutc !== '' || $ordercancelrefundtimeutc !== '' || $ordercancelemailsent === 1 || $ordercancelrefunded === 1)) {
            $message = "New reservation status is not 'cancelled', but there is 'reservation cancel email is sent', 'reservation cancel is refunded', cancel date or cancel refund date. Reservation id : " . $orderid. ". User id: " . $current_user->data->ID;
            dragonecommercereservezyx987_saveToLogTable($message, 'Admin update reservation', 'info');    
            $message2 = "New reservation status is not 'cancelled', but there is 'reservation cancel email is sent', 'reservation cancel is refunded', cancel date or cancel refund date. You chose new status: " . $new_statusname . ". If this reservation has a complicated hisotry, please write the details into column description.";            
            echo esc_html($message2);
            exit();                
        }            
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $stmt=null;
            $sqlColumnsArray = array();
            if($orderstatus > 0) {        
                $sqlColumnsArray['status|i'] = $orderstatus;            
            }
            if($emailsent === 0 || $emailsent === 1) {        
                $sqlColumnsArray['emailsent|i'] = $emailsent;            
            }
            if($ordercancelemailsent === 0 || $ordercancelemailsent === 1) {        
                $sqlColumnsArray['ordercancelemailsent|i'] = $ordercancelemailsent;            
            }
            if($ordercancelrefunded === 0 || $ordercancelrefunded === 1) {        
                $sqlColumnsArray['ordercancelrefunded|i'] = $ordercancelrefunded;            
            }
            $sqlColumnsArray['ordercanceltimeutc|s'] = $ordercanceltimeutc;                    
            $sqlColumnsArray['ordercancelrefundtimeutc|s'] = $ordercancelrefundtimeutc;                    
            $sqlColumnsArray['description|s'] = $description;

            if(count($sqlColumnsArray) > 0) {
                $query = "UPDATE $table_name SET ";
                $types = '';
                $parameterArray = array('');                
                foreach($sqlColumnsArray as $key => $value) {
                    $temp = explode('|', $key, 2);
                    if($temp[0] === 'ordercanceltimeutc' && $ordercanceltimeutc === '') {
                        $query .= ' ' . $temp[0] . ' = null, ';                    
                    } elseif($temp[0] === 'ordercancelrefundtimeutc' && $ordercancelrefundtimeutc === '') {
                        $query .= ' ' . $temp[0] . ' = null, ';                    
                    } elseif($temp[0] === 'description' && $description === '') {
                        $query .= ' ' . $temp[0] . ' = null, ';                    
                    } else {
                        $types .= $temp[1];
                        $query .= ' ' . $temp[0] . ' = ?, ';
                    }                    
                    if($temp[0] === 'status') {
                        $parameterArray[] = &$orderstatus;
                    } elseif($temp[0] === 'ordercanceltimeutc') {
                        if($ordercanceltimeutc !== '') {
                            $parameterArray[] = &$ordercanceltimeutc;
                        }
                    } elseif($temp[0] === 'ordercancelrefundtimeutc') {
                        if($ordercancelrefundtimeutc !== '') {
                            $parameterArray[] = &$ordercancelrefundtimeutc;
                        }
                    } elseif($temp[0] === 'description') {
                        if($description !== '') {
                            $parameterArray[] = &$description;
                        }
                    } elseif($temp[0] === 'emailsent') {
                        $parameterArray[] = &$emailsent;
                    } elseif($temp[0] === 'ordercancelemailsent') {
                        $parameterArray[] = &$ordercancelemailsent;
                    } elseif($temp[0] === 'ordercancelrefunded') {
                        $parameterArray[] = &$ordercancelrefunded;
                    }                    
                }
                $query .= " updatetimeutc = UTC_TIMESTAMP() WHERE id = ? ";                
                $types .= 'i';
                $parameterArray[] = &$orderid;                
                $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 reservation failed. ';
                }
                $stmt->close();                                
            } else {
                $finalresult .= 'Nothing is updated. ';
            }
            //update _product, _product_propertyvalue quantity if reservation status is changed from reserved to cancelled
            $ENABLE_PRODUCT_QUANTITY_AUTO_DEDUCT = $wpdb->get_var("SELECT value FROM $table_name6 WHERE name = 'ENABLE_PRODUCT_QUANTITY_AUTO_DEDUCT'");
            if($ENABLE_PRODUCT_QUANTITY_AUTO_DEDUCT === '1' && strtolower($old_statusname) === 'reserved' && strtolower($new_statusname) === 'cancelled') {
                $productpropertyvaluequantityArr = array();
                $productquantityArr = array();
                $result = $wpdb->get_results("SELECT productid, productpropertyvalueids, quantity from $table_name3 WHERE status = 1 AND orderid= "  . $orderid);
                for($i=0; $i<count($result); $i++) {
                    $temp = strval($result[$i]->productid) . '_' . ($result[$i]->productpropertyvalueids === null ? '' : $result[$i]->productpropertyvalueids);
                    if(isset($productpropertyvaluequantityArr[$temp])) {
                        $productpropertyvaluequantityArr[$temp] += intval($result[$i]->quantity);
                    } else {
                        $productpropertyvaluequantityArr[$temp] = intval($result[$i]->quantity);
                    }    
                    $temp2 = strval($result[$i]->productid);
                    if(isset($productquantityArr[$temp2])) {
                        $productquantityArr[$temp2] += intval($result[$i]->quantity);
                    } else {
                        $productquantityArr[$temp2] = intval($result[$i]->quantity);
                    }                    
                }    
                //error_log("at 5083, productpropertyvaluequantityArr: " . json_encode($productpropertyvaluequantityArr) . ", productquantityArr: " . json_encode($productquantityArr));        
                if(count($productpropertyvaluequantityArr) > 0) {
                    foreach($productpropertyvaluequantityArr as $key => $value) {
                        $quantity = intval($value);
                        $temp = explode("_", $key);
                        $productid = intval($temp[0]);
                        $propertyvalueids = $temp[1];
                        if($propertyvalueids !== '') {
                            //update _product_propertyvalue table
                            $query = "UPDATE $table_name5 SET quantity = quantity + ?, updatetimeutc = UTC_TIMESTAMP() WHERE quantity is not null and productid = ? and propertyvalueids = ?";
                            $stmt = $wpdb->dbh->prepare($query);
                            $types = '';
                            $parameterArray = array('');
                            
                            $types .= 'i';
                            $parameterArray[] = &$quantity;                                

                            $types .= 'i';
                            $parameterArray[] = &$productid;
                            
                            $types .= 's';
                            $parameterArray[] = &$propertyvalueids;
                            
                            $parameterArray[0] = $types;
                            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                            $stmt->execute();
                            if($wpdb->dbh->errno > 0 || $stmt->errno > 0) {
                                $finalresult .= 'Update table ' . $table_name5 . ' failed. ';
                            }                
                            $stmt->close();
                        }                    
                    }                            
                }
                if(count($productquantityArr) > 0) {
                    foreach($productquantityArr as $key => $value) {
                        $quantity = intval($value);
                        $productid = intval($key);
                        //update _product table
                        $query = "UPDATE $table_name4 SET quantity = quantity + ?, updatetimeutc = UTC_TIMESTAMP() WHERE quantity is not null and id = ?";
                        $stmt = $wpdb->dbh->prepare($query);
                        $types = '';
                        $parameterArray = array('');
                        
                        $types .= 'i';
                        $parameterArray[] = &$quantity;                                

                        $types .= 'i';
                        $parameterArray[] = &$productid;                            
                        
                        $parameterArray[0] = $types;
                        call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                        $stmt->execute();
                        if($wpdb->dbh->errno > 0 || $stmt->errno > 0) {
                            $finalresult .= 'Update table ' . $table_name4 . ' failed. ';
                        }                
                        $stmt->close();                    
                    }                            
                }                                
            }            
            if($finalresult === '' ) {$finalresult = 'Success';} 
            echo esc_html($finalresult);                                
            exit();    
        }        
    }
    echo 'Invalid data.';
    exit();    
}

add_action('wp_ajax_dragonecommercereservezyx987_getOrderdetails', 'dragonecommercereservezyx987_getOrderdetails');
function dragonecommercereservezyx987_getOrderdetails() {
    check_ajax_referer('dragonecommercereservezyx987_getOrderdetails', 'dragonecommercereservezyx987_hidden_security_getorderdetails');
    if((!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $startDate = empty($_POST['start']) ? '' : sanitize_text_field($_POST['start']);
        $startDate = strip_tags($startDate);
        $startDate = sanitize_text_field(str_ireplace("T"," ",$startDate));
        $startDate = sanitize_text_field(str_ireplace("Z","",$startDate));        
        $endDate = empty($_POST['end']) ? '' : sanitize_text_field($_POST['end']);
        $endDate = strip_tags($endDate);        
        $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_dragonecommercereservezyx987_product';
        $table_name2 = 'wp_dragonecommercereservezyx987_department';
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getOrderdetailsList';

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

        $amountperpage = empty($_POST['amountperpage']) ? '10' : sanitize_text_field($_POST['amountperpage']);
        $amountperpage = strip_tags($amountperpage);
        $amountperpage = intval($amountperpage);    
        if($amountperpage === -1) {$amountperpage = 10;};            
                    
        $pagenumber = empty($_POST['pagenumber']) ? '1' : sanitize_text_field($_POST['pagenumber']);;
        $pagenumber = strip_tags($pagenumber);
        $pagenumber = intval($pagenumber);            
        $myoffset = ($pagenumber - 1) * $amountperpage;
        
        $mysortby = empty($_POST['sortby']) ? '' : sanitize_text_field($_POST['sortby']);
        $mysortby = strip_tags($mysortby);
        $mysortby = $mysortby === '' ? 'id' : $mysortby;
        
        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : sanitize_text_field($_POST['order']);
        $myorder = strip_tags($myorder);
        $myorder = $myorder === '' ? 'desc' : $myorder;
        
        $searchwords = empty($_POST['searchwords']) ? '' : sanitize_text_field($_POST['searchwords']);
        $searchwords = strip_tags($searchwords);
        
        $searchpropertyvalueid_temp = empty($_POST['propertyvalueid']) ? '1' : sanitize_text_field($_POST['propertyvalueid']);
        $searchpropertyvalueid_temp = strip_tags($searchpropertyvalueid_temp);
        $searchpropertyvalueid = intval($searchpropertyvalueid_temp);
        
        $searchusername = empty($_POST['searchusername']) ? '' : sanitize_text_field($_POST['searchusername']);
        $searchusername = strip_tags($searchusername);                

        $minprice = empty($_POST['minprice']) ? '0.00' : sanitize_text_field($_POST['minprice']);
        $minprice = strip_tags($minprice);
        $minprice = floatval($minprice);            

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

        if(dragonecommercereservezyx987_validateDate($fromdate) && dragonecommercereservezyx987_validateDate($todate)) {
            if($fromdate > $todate) {
                echo "Error. From date is later than to date.";exit();                        
            }
        }else{
            echo "Error. Please enter a valid date.";exit();    
        }            
        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 .= 's';
            $tablenameprefix = $wpdb->prefix;
            $parameterArray[] = &$tablenameprefix;
            
            $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[] = &$searchpropertyvalueid;    
            
            $types .= 's';
            $parameterArray[] = &$searchusername;
            
            $types .= 'd';
            $minprice2 = floatval($minprice);
            $parameterArray[] = &$minprice2;    

            $types .= 'd';
            $maxprice2 = floatval($maxprice);
            $parameterArray[] = &$maxprice2;

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

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

            $types .= 'i';
            $parameterArray[] = &$mystatus;        
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $orders = $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 ($orders as $order) {
                foreach ($order as $key => $value) {                
                    $order[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["orderdetails"] = $orders;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_saveOrderdetails', 'dragonecommercereservezyx987_saveOrderdetails');
function dragonecommercereservezyx987_saveOrderdetails() {
    check_ajax_referer('dragonecommercereservezyx987_saveOrderdetails', 'dragonecommercereservezyx987_hidden_security_saveorderdetails');
    $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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $orderid_temp = empty($_POST['id']) ? '0' : sanitize_text_field($_POST['id']);
        $orderid_temp = strip_tags($orderid_temp);
        $orderid = intval($orderid_temp);
        
        if($orderid <= 0 || $_POST['status'] === null || $_POST['status'] === '') {echo "Invalid id.";exit();}            

        $emailsent_temp = $_POST['emailsent'] === null ? '' : sanitize_text_field($_POST['emailsent']);
        $emailsent_temp = strip_tags($emailsent_temp);
        $emailsent = $emailsent_temp === '' ? -1 : intval($emailsent_temp);
        
        $ordercancelemailsent_temp = $_POST['ordercancelemailsent'] === null ? '' : sanitize_text_field($_POST['ordercancelemailsent']);
        $ordercancelemailsent_temp = strip_tags($ordercancelemailsent_temp);
        $ordercancelemailsent = $ordercancelemailsent_temp === '' ? -1 : intval($ordercancelemailsent_temp);
        
        $ordercancelrefunded_temp = $_POST['ordercancelrefunded'] === null ? '' : sanitize_text_field($_POST['ordercancelrefunded']);
        $ordercancelrefunded_temp = strip_tags($ordercancelrefunded_temp);
        $ordercancelrefunded = $ordercancelrefunded_temp === '' ? -1 : intval($ordercancelrefunded_temp);

        $ordercanceltimeutc_temp = $_POST['ordercanceltimeutc'] === null ? '' : sanitize_text_field($_POST['ordercanceltimeutc']);
        $ordercanceltimeutc = strip_tags($ordercanceltimeutc_temp);
        $ordercanceltimeutc = trim($ordercanceltimeutc);
        
        $ordercancelrefundtimeutc_temp = $_POST['ordercancelrefundtimeutc'] === null ? '' : sanitize_text_field($_POST['ordercancelrefundtimeutc']);
        $ordercancelrefundtimeutc = strip_tags($ordercancelrefundtimeutc_temp);
        $ordercancelrefundtimeutc = trim($ordercancelrefundtimeutc);
        
        $orderstatus_temp = $_POST['status'] === null ? '' : sanitize_text_field($_POST['status']);
        $orderstatus_temp = strip_tags($orderstatus_temp);
        $orderstatus = $orderstatus_temp === '' ? -1 : intval($orderstatus_temp);

        $description_temp = $_POST['description'] === null ? '' : sanitize_text_field($_POST['description']);
        $description = strip_tags($description_temp);
        $description = trim($description);
        
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        if($orderstatus === -1 && $emailsent === -1 && $ordercancelemailsent === -1 && $ordercancelrefunded === -1
           && $ordercanceltimeutc === '' && $ordercancelrefundtimeutc === '' && $description === '') { 
                echo "Please enter a value.";exit();
        }
        if($orderstatus <= 0) { 
                echo "Please choose a reservation status.";exit();
        }        
        if(($ordercanceltimeutc === "" || dragonecommercereservezyx987_validateDate($ordercanceltimeutc)) && 
           ($ordercancelrefundtimeutc === "" || dragonecommercereservezyx987_validateDate($ordercancelrefundtimeutc))) {
            if($ordercanceltimeutc > $ordercancelrefundtimeutc) {
                echo "Error. Reservation refund date is earlier than reservation cancel date.";exit();                        
            }
        }else{
            echo "Error. Please enter a valid date.";exit();    
        }
        
        $table_name = 'wp_dragonecommercereservezyx987_order';
        $table_name2 = 'wp_dragonecommercereservezyx987_processstatus';
        $finalresult = 'Success';
            
        $result = $wpdb->get_results("SELECT name from $table_name2 WHERE id= " . $orderstatus);
        $new_statusname = '';                 
        if(count($result) === 1) {
            for($i=0; $i<count($result); $i++) {
                $new_statusname = $result[$i]->name;                           
            }
        }
        //validate - when admin enter not 'cancelled', but the cancel date or cancel refund date is not empty
        //check these values ordercancelemailsent, ordercancelrefunded, ordercanceltimeutc, ordercancelrefundtimeutc, show error
        if(strtolower($new_statusname) !== 'cancelled' && ($ordercanceltimeutc !== '' || $ordercancelrefundtimeutc !== '' || $ordercancelemailsent === 1 || $ordercancelrefunded === 1)) {
            $message = "New reservation status is not 'cancelled', but there is 'reservation cancel email is sent', 'reservation cancel is refunded', cancel date or cancel refund date. Reservation id : " . $orderid. ". User id: " . $current_user->data->ID;
            dragonecommercereservezyx987_saveToLogTable($message, 'Admin update reservation', 'info');    
            $message2 = "New reservation status is not 'cancelled', but there is 'reservation cancel email is sent', 'reservation cancel is refunded', cancel date or cancel refund date. You chose new status: " . $new_statusname . ". If this reservation has a complicated hisotry, please write the details into column description.";            
            echo esc_html($message2);
            exit();                
        }            
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $stmt=null;
            $sqlColumnsArray = array();
            if($orderstatus > 0) {        
                $sqlColumnsArray['status|i'] = $orderstatus;            
            }
            if($emailsent === 0 || $emailsent === 1) {        
                $sqlColumnsArray['emailsent|i'] = $emailsent;            
            }
            if($ordercancelemailsent === 0 || $ordercancelemailsent === 1) {        
                $sqlColumnsArray['ordercancelemailsent|i'] = $ordercancelemailsent;            
            }
            if($ordercancelrefunded === 0 || $ordercancelrefunded === 1) {        
                $sqlColumnsArray['ordercancelrefunded|i'] = $ordercancelrefunded;            
            }
            $sqlColumnsArray['ordercanceltimeutc|s'] = $ordercanceltimeutc;                    
            $sqlColumnsArray['ordercancelrefundtimeutc|s'] = $ordercancelrefundtimeutc;                                            
            $sqlColumnsArray['description|s'] = $description;
            if(count($sqlColumnsArray) > 0) {
                $query = "UPDATE $table_name SET ";
                $types = '';
                $parameterArray = array('');                
                foreach($sqlColumnsArray as $key => $value) {
                    $temp = explode('|', $key, 2);
                    if($temp[0] === 'ordercanceltimeutc' && $ordercanceltimeutc === '') {
                        $query .= ' ' . $temp[0] . ' = null, ';                    
                    } elseif($temp[0] === 'ordercancelrefundtimeutc' && $ordercancelrefundtimeutc === '') {
                        $query .= ' ' . $temp[0] . ' = null, ';                    
                    } elseif($temp[0] === 'description' && $description === '') {
                        $query .= ' ' . $temp[0] . ' = null, ';                    
                    } else {
                        $types .= $temp[1];
                        $query .= ' ' . $temp[0] . ' = ?, ';
                    }                    
                    if($temp[0] === 'status') {
                        $parameterArray[] = &$orderstatus;
                    } elseif($temp[0] === 'ordercanceltimeutc') {
                        if($ordercanceltimeutc !== '') {
                            $parameterArray[] = &$ordercanceltimeutc;
                        }
                    } elseif($temp[0] === 'ordercancelrefundtimeutc') {
                        if($ordercancelrefundtimeutc !== '') {
                            $parameterArray[] = &$ordercancelrefundtimeutc;
                        }
                    } elseif($temp[0] === 'description') {
                        if($description !== '') {
                            $parameterArray[] = &$description;
                        }
                    } elseif($temp[0] === 'emailsent') {
                        $parameterArray[] = &$emailsent;
                    } elseif($temp[0] === 'ordercancelemailsent') {
                        $parameterArray[] = &$ordercancelemailsent;
                    } elseif($temp[0] === 'ordercancelrefunded') {
                        $parameterArray[] = &$ordercancelrefunded;
                    }                    
                }
                $query .= " updatetimeutc = UTC_TIMESTAMP() WHERE id = ? ";                
                $types .= 'i';
                $parameterArray[] = &$orderid;                
                $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 reservation failed';
                }
                $stmt->close();                                
            } else {
                $finalresult = 'Nothing is updated';
            }                                    
            echo esc_html($finalresult);                                
            exit();    
        }        
    }
    echo 'Invalid data.';
    exit();    
}

add_action('wp_ajax_dragonecommercereservezyx987_saveProcessstatus', 'dragonecommercereservezyx987_saveProcessstatus');
function dragonecommercereservezyx987_saveProcessstatus() {
    check_ajax_referer('dragonecommercereservezyx987_saveProcessstatus', 'dragonecommercereservezyx987_hidden_security_saveprocessstatus');
    $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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $processstatusid_temp = empty($_POST['id']) ? 0 : sanitize_text_field($_POST['id']);
        $processstatusid_temp = strip_tags($processstatusid_temp);
        $processstatusid = intval($processstatusid_temp);
        
        if($processstatusid <= 0 || $_POST['status'] === null || $_POST['status'] === '') {echo "Invalid id.";exit();}    

        $processstatusname_temp = $_POST['name'] === null ? '' : sanitize_text_field($_POST['name']);
        $processstatusname = strip_tags($processstatusname_temp);
        $processstatusname = stripslashes($processstatusname);
        
        $processstatusdescription_temp = $_POST['description'] === null ? '' : sanitize_text_field($_POST['description']);
        $processstatusdescription = strip_tags($processstatusdescription_temp);
        $processstatusdescription = stripslashes($processstatusdescription);
        
        $processstatusstatus_temp = $_POST['status'] === null ? '' : sanitize_text_field($_POST['status']);
        $processstatusstatus_temp = strip_tags($processstatusstatus_temp);
        $processstatusstatus = $processstatusstatus_temp === '' ? 0 : intval($processstatusstatus_temp);        

        if($processstatusname === '' && $processstatusdescription === '' && $processstatusstatus === -1) {
            echo "Please enter a value.";exit();
        }
        if($processstatusname === '' || $processstatusstatus === -1) {
            echo "Name and status are required.";exit();
        }
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_processstatus';
        $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", $processstatusname, $processstatusid);
            $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 process status: process status name \"" . $processstatusname . "\" already exists in the process status table. Not saved. ";exit();}
            } else {
                echo "Edit a process status: process status name \"" . $processstatusname . "\" query has error. Not saved. ";exit();
            }
        
            $stmt=null;
            $sqlColumnsArray = array();            
            if($processstatusname !== '') {
                $sqlColumnsArray['name|s'] = $processstatusname;
            }
            $sqlColumnsArray['description|s'] = $processstatusdescription;
            if($processstatusstatus === 0 || $processstatusstatus === 1) {
                $sqlColumnsArray['status|i'] = $processstatusstatus;
            }
            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[] = &$processstatusname;
                    } elseif($temp[0] === 'description') {
                        $parameterArray[] = &$processstatusdescription;
                    } elseif($temp[0] === 'status') {
                        $parameterArray[] = &$processstatusstatus;
                    }
                }
                $query .= " updatetimeutc = UTC_TIMESTAMP() WHERE id = ? ";                
                $types .= 'i';
                $parameterArray[] = &$processstatusid;                
                $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 process status failed';
                }
                $stmt->close();                                
            } else {
                $finalresult = 'Nothing is updated';
            }                                    
            echo esc_html($finalresult);                                
            exit();                
        }
    }
    echo "Invalid data.";
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_saveCountry', 'dragonecommercereservezyx987_saveCountry');
function dragonecommercereservezyx987_saveCountry() {
    check_ajax_referer('dragonecommercereservezyx987_saveCountry', 'dragonecommercereservezyx987_hidden_security_savecountry');
    $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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y'){
        $countryid_temp = empty($_POST['id']) ? 0 : sanitize_text_field($_POST['id']);
        $countryid_temp = strip_tags($countryid_temp);
        $countryid = intval($countryid_temp);        
        if($countryid <= 0 || $_POST['status'] === null || $_POST['status'] === '') {echo "Invalid id.";exit();}    
        $countryname_temp = $_POST['name'] === null ? '' : sanitize_text_field($_POST['name']);
        $countryname = strip_tags($countryname_temp);
        $countryname = stripslashes($countryname);
    
        $countryabbreviation_temp = $_POST['abbreviation'] === null ? '' : sanitize_text_field($_POST['abbreviation']);
        $countryabbreviation = strip_tags($countryabbreviation_temp);
        $countryabbreviation = stripslashes($countryabbreviation);        
        $countrydescription_temp = $_POST['description'] === null ? '' : sanitize_text_field($_POST['description']);
        $countrydescription = strip_tags($countrydescription_temp);
        $countrydescription = stripslashes($countrydescription);
        
        $countrystatus_temp = $_POST['status'] === null ? '' : sanitize_text_field($_POST['status']);
        $countrystatus_temp = strip_tags($countrystatus_temp);
        $countrystatus = $countrystatus_temp === '' ? 0 : intval($countrystatus_temp);        

        if($countryabbreviation === '' && $countryname === '' && $countrydescription === '' && $countrystatus === -1) {
            echo "Please enter a value."; exit();
        }
        if($countryabbreviation === '' || $countryname === '' || $countrystatus === -1) {
            echo "Name, abbreviation and status are required."; exit();
        }
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_country';
        $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 = ? or abbreviation = ?) AND id != ?");
            $stmt->bind_param("ssi", $countryname, $countryabbreviation, $countryid);
            $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 country: country name: \"" . $countryname . "\" and/or abbreviation: \"" . $countryabbreviation . "\" already exist(s) in the country table. Not saved. ";echo esc_html($finalresult);exit();}
            } else {
                $finalresult = "Edit a country: country name \"" . $countryname . "\" query has error. Not saved. ";echo esc_html($finalresult);exit();
            }            
    
            $stmt=null;
            $sqlColumnsArray = array();            
            if($countryname !== '') {
                $sqlColumnsArray['name|s'] = $countryname;
            }
            $sqlColumnsArray['description|s'] = $countrydescription;
            if($countryabbreviation !== '') {
                $sqlColumnsArray['abbreviation|s'] = $countryabbreviation;
            }
            if($countrystatus === 0 || $countrystatus === 1) {
                $sqlColumnsArray['status|i'] = $countrystatus;
            }                
            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[] = &$countryname;
                    } elseif($temp[0] === 'description') {
                        $parameterArray[] = &$countrydescription;
                    } elseif($temp[0] === 'abbreviation') {
                        $parameterArray[] = &$countryabbreviation;
                    } elseif($temp[0] === 'status') {
                        $parameterArray[] = &$countrystatus;
                    }
                }
                $query .= " updatetimeutc = UTC_TIMESTAMP() WHERE id = ? ";                
                $types .= 'i';
                $parameterArray[] = &$countryid;                
                $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 country failed';
                }
                $stmt->close();                                
            } else {
                $finalresult = 'Nothing is updated';
            }                                    
            echo esc_html($finalresult);                                
            exit();                
        }
    }
    echo "Invalid data.";
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_saveProvince', 'dragonecommercereservezyx987_saveProvince');
function dragonecommercereservezyx987_saveProvince() {
    check_ajax_referer('dragonecommercereservezyx987_saveProvince', 'dragonecommercereservezyx987_hidden_security_saveprovince');
    $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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $provinceid_temp = empty($_POST['id']) ? 0 : sanitize_text_field($_POST['id']);
        $provinceid_temp = strip_tags($provinceid_temp);
        $provinceid = intval($provinceid_temp);
        
        if($provinceid <= 0 || $_POST['status'] === null || $_POST['status'] === '') {echo "Invalid id.";exit();}    

        $provincename_temp = $_POST['name'] === null ? '' : sanitize_text_field($_POST['name']);
        $provincename = strip_tags($provincename_temp);
        $provincename = stripslashes($provincename);
    
        $countryid_temp = $_POST['countryid'] === null ? '' : sanitize_text_field($_POST['countryid']);
        $countryid_temp = strip_tags($countryid_temp);
        $countryid = $countryid_temp === '' ? 0 : intval($countryid_temp);        
        
        $provincedescription_temp = $_POST['description'] === null ? '' : sanitize_text_field($_POST['description']);
        $provincedescription = strip_tags($provincedescription_temp);
        $provincedescription = stripslashes($provincedescription);
        
        $provincestatus_temp = $_POST['status'] === null ? '' : sanitize_text_field($_POST['status']);
        $provincestatus_temp = strip_tags($provincestatus_temp);
        $provincestatus = $provincestatus_temp === '' ? 0 : intval($provincestatus_temp);        

        if($countryid <= 0 && $provincename === '' && $provincedescription === '' && $provincestatus === -1) {
            echo "Please enter a value."; exit;
        }
        if($countryid <= 0 || $provincename === '' || $provincestatus === -1) {
            echo "Name, country and status are required."; exit;
        }
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_province';
        $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 countryid = ? and id != ?");
            $stmt->bind_param("sii", $provincename, $countryid, $provinceid);
            $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 province: province name \"" . $provincename . "\" already exists for that country in the province table. Not saved. ";exit();}
            } else {
                echo "Create a new province: province name \"" . $provincename . "\" query has error. Not saved. ";exit();
            }
        
            $stmt=null;                
            $sqlColumnsArray = array();            
            if($provincename !== '') {
                $sqlColumnsArray['name|s'] = $provincename;
            }
            $sqlColumnsArray['description|s'] = $provincedescription;
            if($countryid > 0) {
                $sqlColumnsArray['countryid|i'] = $countryid;
            }
            if($provincestatus === 0 || $provincestatus === 1) {
                $sqlColumnsArray['status|i'] = $provincestatus;
            }                
            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[] = &$provincename;
                    } elseif($temp[0] === 'description') {
                        $parameterArray[] = &$provincedescription;
                    } elseif($temp[0] === 'countryid') {
                        $parameterArray[] = &$countryid;
                    } elseif($temp[0] === 'status') {
                        $parameterArray[] = &$provincestatus;
                    }
                }
                $query .= " updatetimeutc = UTC_TIMESTAMP() WHERE id = ? ";                
                $types .= 'i';
                $parameterArray[] = &$provinceid;                
                $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 province failed';
                }
                $stmt->close();                                
            } else {
                $finalresult = 'Nothing is updated';
            }                                    
            echo esc_html($finalresult);                                
            exit();                                
        }
    }
    echo "Invalid data.";
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_saveCity', 'dragonecommercereservezyx987_saveCity');
function dragonecommercereservezyx987_saveCity() {
    check_ajax_referer('dragonecommercereservezyx987_saveCity', 'dragonecommercereservezyx987_hidden_security_savecity');
    $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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $cityid_temp = empty($_POST['id']) ? 0 : sanitize_text_field($_POST['id']);
        $cityid_temp = strip_tags($cityid_temp);
        $cityid = intval($cityid_temp);
        
        if($cityid <= 0 || $_POST['status'] === null || $_POST['status'] === '') {echo "Invalid id.";exit();}    

        $cityname_temp = $_POST['name'] === null ? '' : sanitize_text_field($_POST['name']);
        $cityname = strip_tags($cityname_temp);
        $cityname = stripslashes($cityname);
    
        $provinceid_temp = $_POST['provinceid'] === null ? '' : sanitize_text_field($_POST['provinceid']);
        $provinceid_temp = strip_tags($provinceid_temp);
        $provinceid = $provinceid_temp === '' ? 0 : intval($provinceid_temp);
        
        $countryid_temp = $_POST['countryid'] === null ? '' : sanitize_text_field($_POST['countryid']);
        $countryid_temp = strip_tags($countryid_temp);
        $countryid = $countryid_temp === '' ? 0 : intval($countryid_temp);        
        
        $citydescription_temp = $_POST['description'] === null ? '' : sanitize_text_field($_POST['description']);
        $citydescription = strip_tags($citydescription_temp);
        $citydescription = stripslashes($citydescription);
        
        $citystatus_temp = $_POST['status'] === null ? '' : sanitize_text_field($_POST['status']);
        $citystatus_temp = strip_tags($citystatus_temp);
        $citystatus = $citystatus_temp === '' ? 0 : intval($citystatus_temp);        

        if($countryid <= 0 && $provinceid <= 0 && $cityname === '' && $citydescription === '' && $citystatus === -1) {
            echo "Please enter a value.";exit();
        }
        if($countryid <= 0 || $provinceid <= 0 || $cityname === '' || $citystatus === -1) {
            echo "Name, country, province, and status are required.";exit();
        }
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_city';
        $finalresult = 'Success';        
        $table_name2 = 'wp_dragonecommercereservezyx987_province';            
        if($provinceid > 0 && $countryid > 0) {        
            $dbcount = $wpdb->get_var("SELECT COUNT(*) FROM $table_name2 WHERE countryid = " . $countryid . " AND id = " . $provinceid);
            if($dbcount === '0') {echo "Save a city: province id " .  $provinceid . " in country id " . $countryid . " does not exist in province table. Not saved. ";exit();}                
        }                    
        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 provinceid = ? and id != ?");
            $stmt->bind_param("sii", $cityname, $provinceid, $cityid);
            $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 city: city name \"" . $cityname . "\" already exists for the province in the city table. Not saved. ";exit();}
            } else {
                echo "Edit a city: city name \"" . $cityname . "\" query has error. Not saved. ";exit();
            }
        
            $stmt=null;
            $sqlColumnsArray = array();            
            if($cityname !== '') {
                $sqlColumnsArray['name|s'] = $cityname;
            }
            $sqlColumnsArray['description|s'] = $citydescription;        
            if($provinceid > 0) {
                $sqlColumnsArray['provinceid|i'] = $provinceid;
            }
            if($citystatus === 0 || $citystatus === 1) {
                $sqlColumnsArray['status|i'] = $citystatus;
            }
            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[] = &$cityname;
                    } elseif($temp[0] === 'description') {
                        $parameterArray[] = &$citydescription;
                    } elseif($temp[0] === 'provinceid') {
                        $parameterArray[] = &$provinceid;
                    } elseif($temp[0] === 'status') {
                        $parameterArray[] = &$citystatus;
                    }                
                }
                $query .= " updatetimeutc = UTC_TIMESTAMP() WHERE id = ? ";                
                $types .= 'i';
                $parameterArray[] = &$cityid;                
                $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 city failed';
                }
                $stmt->close();                                
            } else {
                $finalresult = 'Nothing is updated';
            }                                    
            echo esc_html($finalresult);                                
            exit();                    
        }
    }
    echo "Invalid data.";
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_saveCurrency', 'dragonecommercereservezyx987_saveCurrency');
function dragonecommercereservezyx987_saveCurrency() {
    check_ajax_referer('dragonecommercereservezyx987_saveCurrency', 'dragonecommercereservezyx987_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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $currencyid_temp = empty($_POST['id']) ? 0 : sanitize_text_field($_POST['id']);
        $currencyid_temp = strip_tags($currencyid_temp);
        $currencyid = intval($currencyid_temp);
        
        if($currencyid <= 0 || $_POST['status'] === null || $_POST['status'] === '') {echo "Invalid id.";exit();}    

        $currencyname_temp = $_POST['name'] === null ? '' : sanitize_text_field($_POST['name']);
        $currencyname = strip_tags($currencyname_temp);
        $currencyname = stripslashes($currencyname);
    
        $currencysign_temp = $_POST['sign'] === null ? '' : sanitize_text_field($_POST['sign']);
        $currencysign = strip_tags($currencysign_temp);
        $currencysign = stripslashes($currencysign);
        
        $isocurrencycode_temp = $_POST['isocurrencycode'] === null ? '' : sanitize_text_field($_POST['isocurrencycode']);
        $isocurrencycode = strip_tags($isocurrencycode_temp);        
        $isocurrencycode = stripslashes($isocurrencycode);
        
        $currencydescription_temp = $_POST['description'] === null ? '' : sanitize_text_field($_POST['description']);
        $currencydescription = strip_tags($currencydescription_temp);
        $currencydescription = stripslashes($currencydescription);
        
        $currencystatus_temp = $_POST['status'] === null ? '' : sanitize_text_field($_POST['status']);
        $currencystatus_temp = strip_tags($currencystatus_temp);
        $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_dragonecommercereservezyx987_currency';
        $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 = ? or sign = ? or isocurrencycode = ?) AND id != ?");
            $stmt->bind_param("sssi", $currencyname, $currencysign, $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: \"" . $currencyname . "\" and/or sign: \"" . $currencysign . "\"  and/or isocurrencycode: \"" . $isocurrencycode . "\" already exist(s) in the currency table. Not saved. ";echo esc_html($finalresult);exit();}
            } else {
                $finalresult = "Edit a currency: currency name \"" . $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_dragonecommercereservezyx987_saveDepartment', 'dragonecommercereservezyx987_saveDepartment');
function dragonecommercereservezyx987_saveDepartment() {
    check_ajax_referer('dragonecommercereservezyx987_saveDepartment', 'dragonecommercereservezyx987_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((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $departmentid_temp = empty($_POST['id']) ? 0 : sanitize_text_field($_POST['id']);
        $departmentid_temp = strip_tags($departmentid_temp);
        $departmentid = intval($departmentid_temp);
        
        if($departmentid <= 0 || $_POST['status'] === null || $_POST['status'] === '') {echo "Invalid id.";exit();}    

        $departmentname_temp = $_POST['name'] === null ? '' : sanitize_text_field($_POST['name']);
        $departmentname = strip_tags($departmentname_temp);
        $departmentname = stripslashes($departmentname);
    
        $departmentdescription_temp = $_POST['description'] === null ? '' : sanitize_text_field($_POST['description']);
        $departmentdescription = strip_tags($departmentdescription_temp);
        $departmentdescription = stripslashes($departmentdescription);
        
        $departmentstatus_temp = $_POST['status'] === null ? '' : sanitize_text_field($_POST['status']);
        $departmentstatus_temp = strip_tags($departmentstatus_temp);
        $departmentstatus = $departmentstatus_temp === '' ? 0 : intval($departmentstatus_temp);        

        if($departmentname === '' && $departmentdescription === '' && $departmentstatus === -1) {
            echo "Please enter a value.";exit();
        }
        if($departmentname === '' || $departmentstatus === -1) {
            echo "Name and status are required.";exit();
        }
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_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 \"" . $departmentname . "\" already exists in the department table. Not saved.";exit();}
            } else {
                echo "Edit a department: department name \"" . $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_dragonecommercereservezyx987_saveGroupcategory', 'dragonecommercereservezyx987_saveGroupcategory');
function dragonecommercereservezyx987_saveGroupcategory() {
    check_ajax_referer('dragonecommercereservezyx987_saveGroupcategory', 'dragonecommercereservezyx987_hidden_security_savegroupcategory');
    $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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $groupcategoryid_temp = empty($_POST['id']) ? 0 : sanitize_text_field($_POST['id']);
        $groupcategoryid_temp = strip_tags($groupcategoryid_temp);
        $groupcategoryid = intval($groupcategoryid_temp);
        
        if($groupcategoryid <= 0 || $_POST['status'] === null || $_POST['status'] === '') {echo "Invalid id.";exit();}    

        $groupcategoryname_temp = $_POST['name'] === null ? '' : sanitize_text_field($_POST['name']);
        $groupcategoryname = strip_tags($groupcategoryname_temp);        
        $groupcategoryname = stripslashes($groupcategoryname);
    
        $groupcategorydescription_temp = $_POST['description'] === null ? '' : sanitize_text_field($_POST['description']);
        $groupcategorydescription = strip_tags($groupcategorydescription_temp);
        $groupcategorydescription = stripslashes($groupcategorydescription);
        
        $groupcategorypriority_temp = $_POST['priority'] === null ? '' : sanitize_text_field($_POST['priority']);
        $groupcategorypriority_temp = strip_tags($groupcategorypriority_temp);
        $groupcategorypriority = $groupcategorypriority_temp === '' ? 0 : intval($groupcategorypriority_temp);
        $groupcategorypriority_isnull = $groupcategorypriority_temp === 'null' ? true : false;
        
        $groupcategorymandatory_temp = $_POST['mandatory'] === null ? '' : sanitize_text_field($_POST['mandatory']);
        $groupcategorymandatory_temp = strip_tags($groupcategorymandatory_temp);
        $groupcategorymandatory = $groupcategorymandatory_temp === '' ? 0 : intval($groupcategorymandatory_temp);    
        
        $groupcategorystatus_temp = $_POST['status'] === null ? '' : sanitize_text_field($_POST['status']);
        $groupcategorystatus_temp = strip_tags($groupcategorystatus_temp);
        $groupcategorystatus = $groupcategorystatus_temp === '' ? 0 : intval($groupcategorystatus_temp);        

        if($groupcategorypriority_temp === 'null' && $groupcategorymandatory === -1 && $groupcategoryname === '' 
            && $groupcategorydescription === '' && $groupcategorystatus === -1) {
            echo "Please enter a value.";exit();
        }
        if($groupcategorymandatory === -1 || $groupcategoryname === '' || $groupcategorystatus === -1) {
            echo "Name, mandatory and status are required.";exit();
        }
        if($groupcategorypriority_temp === 'invalid') {
            echo "Priority should be an integer.";exit();
        }        
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_groupcategory';
        $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", $groupcategoryname, $groupcategoryid);
            $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 group category: group category name \"" . $groupcategoryname . "\" already exists in the group category table. Not saved. ";exit();}
            } else {
                echo "Edit a group category: group category name \"" . $groupcategoryname . "\" query has error. Not saved. ";exit();
            }            
            $stmt=null;
            $sqlColumnsArray = array();            
            if($groupcategoryname !== '') {
                $sqlColumnsArray['name|s'] = $groupcategoryname;
            }
            $sqlColumnsArray['description|s'] = $groupcategorydescription;
            $sqlColumnsArray['priority|i'] = $groupcategorypriority;
            if($groupcategorymandatory === 0 || $groupcategorymandatory === 1) {
                $sqlColumnsArray['mandatory|i'] = $groupcategorymandatory;
            }
            if($groupcategorystatus === 0 || $groupcategorystatus === 1) {
                $sqlColumnsArray['status|i'] = $groupcategorystatus;
            }
            if(count($sqlColumnsArray) > 0) {
                $query = "UPDATE $table_name SET ";
                $types = '';
                $parameterArray = array('');                
                foreach($sqlColumnsArray as $key => $value) {
                    $temp = explode('|', $key, 2);    
                    if($temp[0] === 'priority' && $groupcategorypriority_isnull === true) {
                        $query .= ' ' . $temp[0] . ' = null, ';
                    } else {
                        $types .= $temp[1];
                        $query .= ' ' . $temp[0] . ' = ?, ';
                    }
                    if($temp[0] === 'name') {
                        $parameterArray[] = &$groupcategoryname;
                    } elseif($temp[0] === 'description') {
                        $parameterArray[] = &$groupcategorydescription;
                    } elseif($temp[0] === 'priority') {
                        if($groupcategorypriority_isnull !== true) {
                            $parameterArray[] = &$groupcategorypriority;
                        }
                    } elseif($temp[0] === 'mandatory') {
                        $parameterArray[] = &$groupcategorymandatory;
                    } elseif($temp[0] === 'status') {
                        $parameterArray[] = &$groupcategorystatus;
                    }                    
                }
                $query .= " updatetimeutc = UTC_TIMESTAMP() WHERE id = ? ";                
                $types .= 'i';
                $parameterArray[] = &$groupcategoryid;                
                $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 group category failed';
                }
                $stmt->close();                                
            } else {
                $finalresult = 'Nothing is updated';
            }                                    
            echo esc_html($finalresult);                                
            exit();                    
        }
    }
    echo "Invalid data.";
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_saveGroup', 'dragonecommercereservezyx987_saveGroup');
function dragonecommercereservezyx987_saveGroup() {
    check_ajax_referer('dragonecommercereservezyx987_saveGroup', 'dragonecommercereservezyx987_hidden_security_savegroup');
    $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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $groupid_temp = empty($_POST['id']) ? 0 : sanitize_text_field($_POST['id']);
        $groupid_temp = strip_tags($groupid_temp);
        $groupid = intval($groupid_temp);
        
        if($groupid <= 0 || $_POST['status'] === null || $_POST['status'] === '') {echo "Invalid id.";exit();}    

        $groupname_temp = $_POST['name'] === null ? '' : sanitize_text_field($_POST['name']);
        $groupname = strip_tags($groupname_temp);    
        $groupname = stripslashes($groupname);
    
        $groupdescription_temp = $_POST['description'] === null ? '' : sanitize_text_field($_POST['description']);
        $groupdescription = strip_tags($groupdescription_temp);
        $groupdescription = stripslashes($groupdescription);
        
        $groupgroupcategoryid_temp = $_POST['groupcategoryid'] === null ? '' : sanitize_text_field($_POST['groupcategoryid']);
        $groupgroupcategoryid_temp = strip_tags($groupgroupcategoryid_temp);
        $groupgroupcategoryid = $groupgroupcategoryid_temp === '' ? -1 : intval($groupgroupcategoryid_temp);
        
        $grouppriority_temp = $_POST['priority'] === null ? '' : sanitize_text_field($_POST['priority']);
        $grouppriority_temp = strip_tags($grouppriority_temp);
        $grouppriority = $grouppriority_temp === '' ? 0 : intval($grouppriority_temp);
        $grouppriority_isnull = $grouppriority_temp === 'null' ? true : false;
                
        $groupsearchable_temp = $_POST['searchable'] === null ? '' : sanitize_text_field($_POST['searchable']);
        $groupsearchable_temp = strip_tags($groupsearchable_temp);
        $groupsearchable = $groupsearchable_temp === '' ? 0 : intval($groupsearchable_temp);    

        $groupforallproduct_temp = $_POST['forallproduct'] === null ? '' : sanitize_text_field($_POST['forallproduct']);
        $groupforallproduct_temp = strip_tags($groupforallproduct_temp);
        $groupforallproduct = $groupforallproduct_temp === '' ? 0 : intval($groupforallproduct_temp);
        
        $groupstatus_temp = $_POST['status'] === null ? '' : sanitize_text_field($_POST['status']);
        $groupstatus_temp = strip_tags($groupstatus_temp);
        $groupstatus = $groupstatus_temp === '' ? 0 : intval($groupstatus_temp);        

        if($grouppriority_temp === 'null' && $groupgroupcategoryid <= 0 && $groupforallproduct === -1
            && $groupsearchable === -1 && $groupname === '' && $groupdescription === '' && $groupstatus === -1) {
            echo "Please enter a value.";exit();
        }
        if($groupgroupcategoryid <= 0 && $groupforallproduct === -1
            && $groupsearchable === -1 && $groupname === '' && $groupstatus === -1) {
            echo "Name, group category, searchable, for all product, and status are required.";exit();
        }
        if($grouppriority_temp === 'invalid') {
            echo "Priority should be an integer.";exit();
        }
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_group';
        $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", $groupname, $groupid);
            $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 group: group name: \"" . $groupname . "\" already exists in the group table. Not saved. ";exit();}
            } else {
                echo "Edit a group: group name: \"" . $groupname . "\" query has error. Not saved. ";exit();
            }            
            $stmt=null;
            $sqlColumnsArray = array();            
            if($groupname !== '') {
                $sqlColumnsArray['name|s'] = $groupname;
            }
            $sqlColumnsArray['description|s'] = $groupdescription;            
            if($groupgroupcategoryid > 0) {
                $sqlColumnsArray['groupcategoryid|i'] = $groupgroupcategoryid;
            }
            $sqlColumnsArray['priority|i'] = $grouppriority;            
            if($groupforallproduct === 0 || $groupforallproduct === 1) {
                $sqlColumnsArray['forallproduct|i'] = $groupforallproduct;
            }            
            if($groupsearchable === 0 || $groupsearchable === 1) {
                $sqlColumnsArray['searchable|i'] = $groupsearchable;
            }
            if($groupstatus === 0 || $groupstatus === 1) {
                $sqlColumnsArray['status|i'] = $groupstatus;
            }
            if(count($sqlColumnsArray) > 0) {
                $query = "UPDATE $table_name SET ";
                $types = '';
                $parameterArray = array('');                
                foreach($sqlColumnsArray as $key => $value) {
                    $temp = explode('|', $key, 2);                    
                    if($temp[0] === 'priority' && $grouppriority_isnull === true) {
                        $query .= ' ' . $temp[0] . ' = null, ';
                    } else {
                        $types .= $temp[1];
                        $query .= ' ' . $temp[0] . ' = ?, ';
                    }
                    if($temp[0] === 'name') {
                        $parameterArray[] = &$groupname;
                    } elseif($temp[0] === 'description') {
                        $parameterArray[] = &$groupdescription;
                    } elseif($temp[0] === 'groupcategoryid') {
                        $parameterArray[] = &$groupgroupcategoryid;
                    } elseif($temp[0] === 'priority') {
                        if($grouppriority_isnull !== true) {
                            $parameterArray[] = &$grouppriority;
                        }
                    } elseif($temp[0] === 'forallproduct') {
                        $parameterArray[] = &$groupforallproduct;
                    } elseif($temp[0] === 'searchable') {
                        $parameterArray[] = &$groupsearchable;
                    } elseif($temp[0] === 'status') {
                        $parameterArray[] = &$groupstatus;
                    }            
                }
                $query .= " updatetimeutc = UTC_TIMESTAMP() WHERE id = ? ";                
                $types .= 'i';
                $parameterArray[] = &$groupid;                
                $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 group failed';
                }
                $stmt->close();                                
            } else {
                $finalresult = 'Nothing is updated';
            }                                    
            echo esc_html($finalresult);                                
            exit();                
        }
    }
    echo "Invalid data.";
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_saveChargetype', 'dragonecommercereservezyx987_saveChargetype');
function dragonecommercereservezyx987_saveChargetype() {
    check_ajax_referer('dragonecommercereservezyx987_saveChargetype', 'dragonecommercereservezyx987_hidden_security_savechargetype');
    $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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $chargetypeid_temp = empty($_POST['id']) ? 0 : sanitize_text_field($_POST['id']);
        $chargetypeid_temp = strip_tags($chargetypeid_temp);
        $chargetypeid = intval($chargetypeid_temp);
        
        if($chargetypeid <= 0 || $_POST['status'] === null || $_POST['status'] === '') {echo "Invalid id.";exit();}    

        $chargetypename_temp = $_POST['name'] === null ? '' : sanitize_text_field($_POST['name']);
        $chargetypename = strip_tags($chargetypename_temp);    
        $chargetypename = stripslashes($chargetypename);
    
        $chargetypedescription_temp = $_POST['description'] === null ? '' : sanitize_text_field($_POST['description']);
        $chargetypedescription = strip_tags($chargetypedescription_temp);
        $chargetypedescription = stripslashes($chargetypedescription);
        
        $chargetypepriority_temp = $_POST['priority'] === null ? '' : sanitize_text_field($_POST['priority']);
        $chargetypepriority_temp = strip_tags($chargetypepriority_temp);
        $chargetypepriority = $chargetypepriority_temp === '' ? 0 : intval($chargetypepriority_temp);
        $chargetypepriority_isnull = $chargetypepriority_temp === 'null' ? true : false;
        
        $chargetypestatus_temp = $_POST['status'] === null ? '' : sanitize_text_field($_POST['status']);
        $chargetypestatus_temp = strip_tags($chargetypestatus_temp);
        $chargetypestatus = $chargetypestatus_temp === '' ? 0 : intval($chargetypestatus_temp);        

        if($chargetypepriority_temp === 'null' && $chargetypename === '' && $chargetypedescription === '' && $chargetypestatus === -1) {
            echo "Please enter a value.";exit();
        }
        if($chargetypename === '' || $chargetypestatus === -1) {
            echo "Name and status are required.";exit();
        }
        if($chargetypepriority_temp === 'invalid') {
            echo "Priority should be an integer.";exit();
        }        
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_chargetype';
        $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", $chargetypename, $chargetypeid);
            $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 charge type: charge type name \"" . $chargetypename . "\" already exists in the charge type table. Not saved.";exit();}
            } else {
                echo "Edit a charge type: charge type name \"" . $chargetypename . "\" query has error. Not saved.";exit();
            }
        
            $stmt=null;
            $sqlColumnsArray = array();            
            if($chargetypename !== '') {
                $sqlColumnsArray['name|s'] = $chargetypename;
            }
            $sqlColumnsArray['description|s'] = $chargetypedescription;
            $sqlColumnsArray['priority|i'] = $chargetypepriority;
            if($chargetypestatus === 0 || $chargetypestatus === 1) {
                $sqlColumnsArray['status|i'] = $chargetypestatus;
            }
            if(count($sqlColumnsArray) > 0) {
                $query = "UPDATE $table_name SET ";
                $types = '';
                $parameterArray = array('');                
                foreach($sqlColumnsArray as $key => $value) {
                    $temp = explode('|', $key, 2);
                    if($temp[0] === 'priority' && $chargetypepriority_isnull === true) {
                        $query .= ' ' . $temp[0] . ' = null, ';
                    } else {
                        $types .= $temp[1];
                        $query .= ' ' . $temp[0] . ' = ?, ';
                    }    
                    if($temp[0] === 'name') {
                        $parameterArray[] = &$chargetypename;
                    } elseif($temp[0] === 'description') {
                        $parameterArray[] = &$chargetypedescription;
                    } elseif($temp[0] === 'priority') {
                        if($chargetypepriority_isnull !== true) {
                            $parameterArray[] = &$chargetypepriority;
                        }
                    } elseif($temp[0] === 'status') {
                        $parameterArray[] = &$chargetypestatus;
                    }                
                }
                $query .= " updatetimeutc = UTC_TIMESTAMP() WHERE id = ? ";                
                $types .= 'i';
                $parameterArray[] = &$chargetypeid;                
                $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 charge type failed';
                }
                $stmt->close();                                
            } else {
                $finalresult = 'Nothing is updated';
            }                                    
            echo esc_html($finalresult);                                
            exit();                
        }
    }
    echo "Invalid data.";
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_saveProperty', 'dragonecommercereservezyx987_saveProperty');
function dragonecommercereservezyx987_saveProperty() {
    check_ajax_referer('dragonecommercereservezyx987_saveProperty', 'dragonecommercereservezyx987_hidden_security_saveproperty');
    $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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $propertyid_temp = empty($_POST['id']) ? 0 : sanitize_text_field($_POST['id']);
        $propertyid_temp = strip_tags($propertyid_temp);
        $propertyid = intval($propertyid_temp);
        
        if($propertyid <= 0 || $_POST['status'] === null || $_POST['status'] === '') {echo "Invalid id.";exit();}    

        $propertyname_temp = $_POST['name'] === null ? '' : sanitize_text_field($_POST['name']);
        $propertyname = strip_tags($propertyname_temp);    
        $propertyname = stripslashes($propertyname);

        $propertyshownname_temp = $_POST['shownname'] === null ? '' : sanitize_text_field($_POST['shownname']);
        $propertyshownname = strip_tags($propertyshownname_temp);
        $propertyshownname = stripslashes($propertyshownname);
        
        $propertydescription_temp = $_POST['description'] === null ? '' : sanitize_text_field($_POST['description']);
        $propertydescription = strip_tags($propertydescription_temp);
        $propertydescription = stripslashes($propertydescription);
        
        $propertychargetypeid_temp = $_POST['chargetypeid'] === null ? '' : sanitize_text_field($_POST['chargetypeid']);
        $propertychargetypeid_temp = strip_tags($propertychargetypeid_temp);
        $propertychargetypeid = $propertychargetypeid_temp === '' ? -1 : intval($propertychargetypeid_temp);
                
        $propertypriority_temp = $_POST['priority'] === null ? '' : sanitize_text_field($_POST['priority']);
        $propertypriority_temp = strip_tags($propertypriority_temp);
        $propertypriority = $propertypriority_temp === '' ? 0 : intval($propertypriority_temp);
        $propertypriority_isnull = $propertypriority_temp === 'null' ? true : false;
        
        $propertyforallproduct_temp = $_POST['forallproduct'] === null ? '' : sanitize_text_field($_POST['forallproduct']);
        $propertyforallproduct_temp = strip_tags($propertyforallproduct_temp);
        $propertyforallproduct = $propertyforallproduct_temp === '' ? -1 : intval($propertyforallproduct_temp);
    
        $propertymandatory_temp = $_POST['mandatory'] === null ? '' : sanitize_text_field($_POST['mandatory']);
        $propertymandatory_temp = strip_tags($propertymandatory_temp);
        $propertymandatory = $propertymandatory_temp === '' ? -1 : intval($propertymandatory_temp);
        
        $propertystatus_temp = $_POST['status'] === null ? '' : sanitize_text_field($_POST['status']);
        $propertystatus_temp = strip_tags($propertystatus_temp);
        $propertystatus = $propertystatus_temp === '' ? -1 : intval($propertystatus_temp);        

        if($propertypriority_temp === 'null' && $propertychargetypeid <= 0 && $propertyforallproduct === -1
            && $propertymandatory === -1 && $propertyname === '' && $propertyshownname === '' && $propertydescription === '' && $propertystatus === -1) {
            echo "Please enter a value.";exit();
        }
        if($propertyforallproduct === -1 && $propertymandatory === -1 && $propertyname === '' && $propertyshownname === '' && $propertystatus === -1) {
            echo "Name, for all product, mandatory, and status are required.";exit();
        }
        if($propertypriority_temp === 'invalid') {
            echo "Priority should be an integer.";exit();
        }        
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_property';
        $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", $propertyname, $propertyid);
            $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 property: property name " . $propertyname . " already exists in the property table. Not saved.";exit();}
            } else {
                echo "Edit a property: property name " . $propertyname . " query has error. Not saved.";exit();
            }
        
            $stmt=null;
            $sqlColumnsArray = array();            
            if($propertyname !== '') {
                $sqlColumnsArray['name|s'] = $propertyname;
            }
            if($propertyshownname !== '') {
                $sqlColumnsArray['shownname|s'] = $propertyshownname;
            }
            $sqlColumnsArray['description|s'] = $propertydescription;
            $sqlColumnsArray['chargetypeid|i'] = $propertychargetypeid;
            if($propertyforallproduct === 0 || $propertyforallproduct === 1) {
                $sqlColumnsArray['forallproduct|i'] = $propertyforallproduct;
            }
            if($propertymandatory === 0 || $propertymandatory === 1) {
                $sqlColumnsArray['mandatory|i'] = $propertymandatory;
            }        
            $sqlColumnsArray['priority|i'] = $propertypriority;
            if($propertystatus === 0 || $propertystatus === 1) {
                $sqlColumnsArray['status|i'] = $propertystatus;
            }
            if(count($sqlColumnsArray) > 0) {
                $query = "UPDATE $table_name SET ";
                $types = '';
                $parameterArray = array('');                
                foreach($sqlColumnsArray as $key => $value) {
                    $temp = explode('|', $key, 2);
                    if($temp[0] === 'priority' && $propertypriority_isnull === true) {
                        $query .= ' ' . $temp[0] . ' = null, ';
                    } elseif($temp[0] === 'chargetypeid' && $propertychargetypeid <= 0) {
                        $query .= ' ' . $temp[0] . ' = null, ';
                    } else {
                        $types .= $temp[1];
                        $query .= ' ' . $temp[0] . ' = ?, ';
                    }
                    if($temp[0] === 'name') {
                        $parameterArray[] = &$propertyname;
                    } elseif($temp[0] === 'shownname') {
                        $parameterArray[] = &$propertyshownname;
                    } elseif($temp[0] === 'description') {
                        $parameterArray[] = &$propertydescription;
                    } elseif($temp[0] === 'chargetypeid') {
                        if($propertychargetypeid > 0) {
                            $parameterArray[] = &$propertychargetypeid;
                        }
                    } elseif($temp[0] === 'forallproduct') {
                        $parameterArray[] = &$propertyforallproduct;
                    } elseif($temp[0] === 'mandatory') {
                        $parameterArray[] = &$propertymandatory;
                    } elseif($temp[0] === 'priority') {
                        if($propertypriority_isnull !== true) {
                            $parameterArray[] = &$propertypriority;
                        }
                    } elseif($temp[0] === 'status') {
                        $parameterArray[] = &$propertystatus;
                    }                    
                }
                $query .= " updatetimeutc = UTC_TIMESTAMP() WHERE id = ? ";                
                $types .= 'i';
                $parameterArray[] = &$propertyid;                
                $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 property failed';
                }
                $stmt->close();                                
            } else {
                $finalresult = 'Nothing is updated';
            }                                    
            echo esc_html($finalresult);                                
            exit();
        }
    }
    echo "Invalid data.";
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_saveSlideshow', 'dragonecommercereservezyx987_saveSlideshow');
function dragonecommercereservezyx987_saveSlideshow() {
    check_ajax_referer('dragonecommercereservezyx987_saveSlideshow', 'dragonecommercereservezyx987_hidden_security_saveslideshow');
    $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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $slideshowid_temp = empty($_POST['id']) ? 0 : sanitize_text_field($_POST['id']);
        $slideshowid_temp = strip_tags($slideshowid_temp);
        $slideshowid = intval($slideshowid_temp);
        
        if($slideshowid <= 0 || $_POST['status'] === null || $_POST['status'] === '') {echo "Invalid id.";exit();}    

        $slideshowname_temp = $_POST['name'] === null ? '' : sanitize_text_field($_POST['name']);
        $slideshowname = strip_tags($slideshowname_temp);    
        $slideshowname = stripslashes($slideshowname);
    
        $slideshowdescription_temp = $_POST['description'] === null ? '' : sanitize_text_field($_POST['description']);
        $slideshowdescription = strip_tags($slideshowdescription_temp);
        $slideshowdescription = stripslashes($slideshowdescription);
        
        $slideshowsequencenumber_temp = $_POST['sequencenumber'] === null ? '' : sanitize_text_field($_POST['sequencenumber']);
        $slideshowsequencenumber_temp = strip_tags($slideshowsequencenumber_temp);
        $slideshowsequencenumber = $slideshowsequencenumber_temp === '' ? 0 : intval($slideshowsequencenumber_temp);
        $slideshowsequencenumber_isnull = $slideshowsequencenumber_temp === 'null' ? true : false;
        
        $showname_temp = $_POST['showname'] === null ? '' : sanitize_text_field($_POST['showname']);
        $showname_temp = strip_tags($showname_temp);
        $showname = $showname_temp === '' ? 0 : intval($showname_temp);        

        $showdescription_temp = $_POST['showdescription'] === null ? '' : sanitize_text_field($_POST['showdescription']);
        $showdescription_temp = strip_tags($showdescription_temp);
        $showdescription = $showdescription_temp === '' ? 0 : intval($showdescription_temp);
        
        $slideshowstatus_temp = $_POST['status'] === null ? '' : sanitize_text_field($_POST['status']);
        $slideshowstatus_temp = strip_tags($slideshowstatus_temp);
        $slideshowstatus = $slideshowstatus_temp === '' ? 0 : intval($slideshowstatus_temp);
        
        if($slideshowsequencenumber_temp === 'null' && $slideshowname === '' && $slideshowdescription === '' && $slideshowstatus === -1 && $showname === -1 && $showdescription === -1) {
            echo "Please enter a value.";exit();
        }
        if($slideshowname === '' || $slideshowstatus === -1 || $showname === -1 || $showdescription === -1) {
            echo "Name, showname, showdescription and status are required.";exit();
        }
        if($slideshowsequencenumber_temp === 'invalid') {
            echo "Sequence number should be an integer.";exit();
        }
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_slideshow';
        $finalresult = 'Success';                        
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }                
            $stmt=null;        
            $sqlColumnsArray = array();            
            if($slideshowname !== '') {
                $sqlColumnsArray['name|s'] = $slideshowname;
            }
            $sqlColumnsArray['description|s'] = $slideshowdescription;
            $sqlColumnsArray['sequencenumber|i'] = $slideshowsequencenumber;
            if($showname === 0 || $showname === 1) {
                $sqlColumnsArray['showname|i'] = $showname;
            }
            if($showdescription === 0 || $showdescription === 1) {
                $sqlColumnsArray['showdescription|i'] = $showdescription;
            }
            if($slideshowstatus === 0 || $slideshowstatus === 1) {
                $sqlColumnsArray['status|i'] = $slideshowstatus;
            }
            if(count($sqlColumnsArray) > 0) {
                $query = "UPDATE $table_name SET ";
                $types = '';
                $parameterArray = array('');                
                foreach($sqlColumnsArray as $key => $value) {
                    $temp = explode('|', $key, 2);
                    if($temp[0] === 'sequencenumber' && $slideshowsequencenumber_isnull === true) {
                        $query .= ' ' . $temp[0] . ' = null, ';
                    } else {
                        $types .= $temp[1];
                        $query .= ' ' . $temp[0] . ' = ?, ';
                    }
                    if($temp[0] === 'name') {
                        $parameterArray[] = &$slideshowname;
                    } elseif($temp[0] === 'description') {
                        $parameterArray[] = &$slideshowdescription;
                    } elseif($temp[0] === 'sequencenumber') {
                        if($slideshowsequencenumber_isnull !== true) {
                            $parameterArray[] = &$slideshowsequencenumber;
                        }
                    } elseif($temp[0] === 'showname') {
                        $parameterArray[] = &$showname;
                    } elseif($temp[0] === 'showdescription') {
                        $parameterArray[] = &$showdescription;
                    } elseif($temp[0] === 'status') {
                        $parameterArray[] = &$slideshowstatus;
                    }        
                }
                $query .= " updatetimeutc = UTC_TIMESTAMP() WHERE id = ? ";                
                $types .= 'i';
                $parameterArray[] = &$slideshowid;                
                $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 slideshow failed';
                }
                $stmt->close();                                
            } else {
                $finalresult = 'Nothing is updated';
            }                                    
            echo esc_html($finalresult);                                
            exit();                
        }
    }
    echo "Invalid data.";
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_deleteSlideshow', 'dragonecommercereservezyx987_deleteSlideshowByAjax');
function dragonecommercereservezyx987_deleteSlideshowByAjax() {
    check_ajax_referer('dragonecommercereservezyx987_deleteSlideshow', 'dragonecommercereservezyx987_hidden_security_deleteslideshow');
    $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();
    }
    $myerrormessage = '';
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $slideshowid_temp = empty($_POST['id']) ? 0 : sanitize_text_field($_POST['id']);
        $slideshowid_temp = strip_tags($slideshowid_temp);
        $slideshowid = intval($slideshowid_temp);        
        if($slideshowid > 0) {
            global $wpdb;
            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
            $table_name = 'wp_dragonecommercereservezyx987_slideshow';            
            $filename = $wpdb->get_var("SELECT filename FROM " . $table_name . " WHERE id = " . $slideshowid);
            if($filename !== null && $filename !== '') {        
                $target_dir = dragonecommercereservezyx987_upload_folder() . "/images/slideshow/";
                //$target_dir = ABSPATH . "wp-content/plugins/dragonecommercereserve/images/slideshow/";
                if(!file_exists($target_dir)) {
                    mkdir($target_dir, 0755, true);
                } else {        
                    chmod($target_dir, 0777);
                }        
                $target_file = $target_dir . $filename;        
                if(file_exists($target_file)) {
                    $result = unlink($target_file);
                    if($result === false) {echo 'Failed deleting file ' . sanitize_text_field($filename);exit();}
                }            
                chmod($target_dir, 0755);
            }                
            $result = $wpdb->query($wpdb->prepare("Delete FROM $table_name WHERE id = %d", $slideshowid));
            if($result === FALSE) {
                $dragon_ecommerce_dbResult .= 'Error deleting a record from table ' . $table_name . ", id: " . $slideshowid . ". ";
                echo 'Error deleting a record from table ' . $table_name . ", id: " . $slideshowid . ".";
                exit();
            } else {                
                echo "success";exit();
            }
        } else {
            $dragon_ecommerce_dbResult .= 'Error deleting a record from table ' . $table_name . ", wrong id: " . $slideshowid . ". ";
            echo 'Error deleting a record from table ' . $table_name . ", wrong id: " . $slideshowid . ".";
            exit();
        }
    } else {
        $myerrormessage = 'You do not have administrator role or it is not a POST request.';
    }
    echo esc_html($myerrormessage);
    exit();    
}

add_action('wp_ajax_dragonecommercereservezyx987_saveHandling', 'dragonecommercereservezyx987_saveHandling');
function dragonecommercereservezyx987_saveHandling() {
    check_ajax_referer('dragonecommercereservezyx987_saveHandling', 'dragonecommercereservezyx987_hidden_security_savehandling');
    dragonecommercereservezyx987_savePropertyvalue_template();
}

add_action('wp_ajax_dragonecommercereservezyx987_saveShipping', 'dragonecommercereservezyx987_saveShipping');
function dragonecommercereservezyx987_saveShipping() {
    check_ajax_referer('dragonecommercereservezyx987_saveShipping', 'dragonecommercereservezyx987_hidden_security_saveshipping');
    dragonecommercereservezyx987_savePropertyvalue_template();
}

add_action('wp_ajax_dragonecommercereservezyx987_saveTax', 'dragonecommercereservezyx987_saveTax');
function dragonecommercereservezyx987_saveTax() {
    check_ajax_referer('dragonecommercereservezyx987_saveTax', 'dragonecommercereservezyx987_hidden_security_savetax');
    dragonecommercereservezyx987_savePropertyvalue_template();
}

add_action('wp_ajax_dragonecommercereservezyx987_saveDiscount', 'dragonecommercereservezyx987_saveDiscount');
function dragonecommercereservezyx987_saveDiscount() {
    check_ajax_referer('dragonecommercereservezyx987_saveDiscount', 'dragonecommercereservezyx987_hidden_security_savediscount');
    dragonecommercereservezyx987_savePropertyvalue_template();
}

add_action('wp_ajax_dragonecommercereservezyx987_saveCoupon', 'dragonecommercereservezyx987_saveCoupon');
function dragonecommercereservezyx987_saveCoupon() {
    check_ajax_referer('dragonecommercereservezyx987_saveCoupon', 'dragonecommercereservezyx987_hidden_security_savecoupon');
    dragonecommercereservezyx987_savePropertyvalue_template();
}

add_action('wp_ajax_dragonecommercereservezyx987_savePropertyvalue', 'dragonecommercereservezyx987_savePropertyvalue');
function dragonecommercereservezyx987_savePropertyvalue() {
    check_ajax_referer('dragonecommercereservezyx987_savePropertyvalue', 'dragonecommercereservezyx987_hidden_security_savepropertyvalue');
    dragonecommercereservezyx987_savePropertyvalue_template();
}

function dragonecommercereservezyx987_savePropertyvalue_template() {
    $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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $propertyvalueid_temp = empty($_POST['id']) ? '0' : sanitize_text_field($_POST['id']);
        $propertyvalueid_temp = strip_tags($propertyvalueid_temp);
        $propertyvalueid = intval($propertyvalueid_temp);
        
        if($propertyvalueid <= 0 || $_POST['status'] === null || $_POST['status'] === '') {echo "Invalid id.";exit();}    

        $propertyid_temp = empty($_POST['propertyid']) ? '0' : sanitize_text_field($_POST['propertyid']);
        $propertyid_temp = strip_tags($propertyid_temp);
        $propertyid = intval($propertyid_temp);        
        
        $propertyvaluename_temp = $_POST['name'] === null ? '' : sanitize_text_field($_POST['name']);
        $propertyvaluename = strip_tags($propertyvaluename_temp);    
        $propertyvaluename = stripslashes($propertyvaluename);
    
        $propertyvalueshownname_temp = $_POST['shownname'] === null ? '' : sanitize_text_field($_POST['shownname']);
        $propertyvalueshownname = strip_tags($propertyvalueshownname_temp);    
        $propertyvalueshownname = stripslashes($propertyvalueshownname);
        
        $propertyvaluedescription_temp = $_POST['description'] === null ? '' : sanitize_text_field($_POST['description']);
        $propertyvaluedescription = strip_tags($propertyvaluedescription_temp);
        $propertyvaluedescription = stripslashes($propertyvaluedescription);
        
        $propertyvaluecode_temp = $_POST['code'] === null ? '' : sanitize_text_field($_POST['code']);
        $propertyvaluecode = strip_tags($propertyvaluecode_temp);
        
        $propertyvalueuserate_temp = $_POST['userate'] === null ? '' : sanitize_text_field($_POST['userate']);
        $propertyvalueuserate_temp = strip_tags($propertyvalueuserate_temp);
        $propertyvalueuserate = $propertyvalueuserate_temp === '' ? -1 : intval($propertyvalueuserate_temp);
    
        $propertyvaluerate_temp = $_POST['rate'] === null ? '' : sanitize_text_field($_POST['rate']);
        $propertyvaluerate_temp = strip_tags($propertyvaluerate_temp);
        $propertyvaluerate = $propertyvaluerate_temp === '' ? -1 : floatval($propertyvaluerate_temp);
                
        $propertyvalueusefee_temp = $_POST['usefee'] === null ? '' : sanitize_text_field($_POST['usefee']);
        $propertyvalueusefee_temp = strip_tags($propertyvalueusefee_temp);
        $propertyvalueusefee = $propertyvalueusefee_temp === '' ? -1 : intval($propertyvalueusefee_temp);

        $propertyvaluefee_temp = $_POST['fee'] === null ? '' : sanitize_text_field($_POST['fee']);
        $propertyvaluefee_temp = strip_tags($propertyvaluefee_temp);
        $propertyvaluefee = $propertyvaluefee_temp === '' ? -1 : floatval($propertyvaluefee_temp);

        $propertyvaluestart_temp = $_POST['start'] === null ? '' : sanitize_text_field($_POST['start']);
        $propertyvaluestart = strip_tags($propertyvaluestart_temp);
        
        $propertyvalueend_temp = $_POST['end'] === null ? '' : sanitize_text_field($_POST['end']);
        $propertyvalueend = strip_tags($propertyvalueend_temp);        

        $propertyvaluefromcountryid_temp = $_POST['fromcountryid'] === null ? '' : sanitize_text_field($_POST['fromcountryid']);
        $propertyvaluefromcountryid_temp = strip_tags($propertyvaluefromcountryid_temp);
        $propertyvaluefromcountryid = $propertyvaluefromcountryid_temp === '' ? -1 : intval($propertyvaluefromcountryid_temp);

        $propertyvaluefromstateprovinceid_temp = $_POST['fromstateprovinceid'] === null ? '' : sanitize_text_field($_POST['fromstateprovinceid']);
        $propertyvaluefromstateprovinceid_temp = strip_tags($propertyvaluefromstateprovinceid_temp);
        $propertyvaluefromstateprovinceid = $propertyvaluefromstateprovinceid_temp === '' ? -1 : intval($propertyvaluefromstateprovinceid_temp);

        $propertyvaluetocountryid_temp = $_POST['tocountryid'] === null ? '' : sanitize_text_field($_POST['tocountryid']);
        $propertyvaluetocountryid_temp = strip_tags($propertyvaluetocountryid_temp);
        $propertyvaluetocountryid = $propertyvaluetocountryid_temp === '' ? -1 : intval($propertyvaluetocountryid_temp);
                
        $propertyvaluetostateprovinceid_temp = $_POST['tostateprovinceid'] === null ? '' : sanitize_text_field($_POST['tostateprovinceid']);
        $propertyvaluetostateprovinceid_temp = strip_tags($propertyvaluetostateprovinceid_temp);
        $propertyvaluetostateprovinceid = $propertyvaluetostateprovinceid_temp === '' ? -1 : intval($propertyvaluetostateprovinceid_temp);
    
        $propertyvaluepriority_temp = $_POST['priority'] === null ? '' : sanitize_text_field($_POST['priority']);
        $propertyvaluepriority_temp = strip_tags($propertyvaluepriority_temp);
        $propertyvaluepriority = $propertyvaluepriority_temp === '' ? 0 : intval($propertyvaluepriority_temp);
        $propertyvaluepriority_isnull = $propertyvaluepriority_temp === 'null' ? true : false;
            
        $propertyvalueminordersubtotal_temp = $_POST['minordersubtotal'] === null ? '' : sanitize_text_field($_POST['minordersubtotal']);
        $propertyvalueminordersubtotal_temp = strip_tags($propertyvalueminordersubtotal_temp);
        $propertyvalueminordersubtotal = $propertyvalueminordersubtotal_temp === '' ? -1 : floatval($propertyvalueminordersubtotal_temp);
        
        $propertyvaluetaxincludeshipping_temp = $_POST['taxincludeshipping'] === null ? '' : sanitize_text_field($_POST['taxincludeshipping']);
        $propertyvaluetaxincludeshipping_temp = strip_tags($propertyvaluetaxincludeshipping_temp);
        $propertyvaluetaxincludeshipping = $propertyvaluetaxincludeshipping_temp === '' ? -1 : intval($propertyvaluetaxincludeshipping_temp);        

        $propertyvaluetaxincludehandling_temp = $_POST['taxincludehandling'] === null ? '' : sanitize_text_field($_POST['taxincludehandling']);
        $propertyvaluetaxincludehandling_temp = strip_tags($propertyvaluetaxincludehandling_temp);
        $propertyvaluetaxincludehandling = $propertyvaluetaxincludehandling_temp === '' ? -1 : intval($propertyvaluetaxincludehandling_temp);
        
        $propertyvaluestatus_temp = $_POST['status'] === null ? '' : sanitize_text_field($_POST['status']);
        $propertyvaluestatus_temp = strip_tags($propertyvaluestatus_temp);
        $propertyvaluestatus = $propertyvaluestatus_temp === '' ? -1 : intval($propertyvaluestatus_temp);
                
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name2 = 'wp_dragonecommercereservezyx987_province';            
        if($propertyvaluefromstateprovinceid !== -1 && $propertyvaluefromstateprovinceid !== 0 && $propertyvaluefromcountryid !== -1 && $propertyvaluefromcountryid !== 0) {            
            $dbcount = $wpdb->get_var("SELECT COUNT(*) FROM $table_name2 WHERE countryid = " . $propertyvaluefromcountryid . " AND id = " . $propertyvaluefromstateprovinceid);
            if($dbcount === '0') {echo "Save a propertyvalue: province id " .  $propertyvaluefromstateprovinceid . " in country id " . $propertyvaluefromcountryid . " does not exist in province table. Not saved. ";exit();}                
        }                    
        if($propertyvaluetostateprovinceid !== -1 && $propertyvaluetostateprovinceid !== 0 && $propertyvaluetocountryid !== -1 && $propertyvaluetocountryid !== 0) {            
            $dbcount = $wpdb->get_var("SELECT COUNT(*) FROM $table_name2 WHERE countryid = " . $propertyvaluetocountryid . " AND id = " . $propertyvaluetostateprovinceid);
            if($dbcount === '0') {echo "Save a propertyvalue: province id " .  $propertyvaluetostateprovinceid . " in country id " . $propertyvaluetocountryid . " does not exist in province table. Not saved. ";exit();}                
        }
        if($propertyvaluecode === '' && $propertyid <= 0 && $propertyvaluetocountryid <= 0 && $propertyvaluetostateprovinceid <= 0 
            && $propertyvaluefromcountryid <= 0 && $propertyvaluefromstateprovinceid <= 0 && $propertyvalueuserate < 0    
            && $propertyvalueusefee < 0 && ($propertyvaluepriority_temp === 'null') && $propertyvalueminordersubtotal <= 0
            && $propertyvaluename === '' && $propertyvaluedescription === '' && $propertyvaluestatus === -1
            && $propertyvaluestart === '' && $propertyvalueend === '' && $propertyvaluetaxincludeshipping === -1 && $propertyvaluetaxincludehandling === -1) { 
                echo "Please enter a value.";exit();
        }        
        if(($propertyvaluestart === "" || dragonecommercereservezyx987_validateDate($propertyvaluestart)) && 
           ($propertyvalueend === "" || dragonecommercereservezyx987_validateDate($propertyvalueend))) {
            if($propertyvaluestart > $propertyvalueend) {
                echo "Error. Start date is later than end date.";exit();                        
            }
        }else{
            echo "Error. Please enter a valid date.";exit();    
        }
        if($propertyvaluepriority_temp === 'invalid') {
            echo "Priority should be an integer.";exit();
        }        
        $table_name = 'wp_dragonecommercereservezyx987_propertyvalue';
        $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 propertyid = ? AND id != ?");
            $stmt->bind_param("sii", $propertyvaluename, $propertyid, $propertyvalueid);                
            $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 property value: property value name \"" . $propertyvaluename . "\" for the same property already exists in the propertyvalue table. Not saved. ";exit();}
            } else {
                echo "Edit a property value: property value name \"" . $propertyvaluename . "\" query has error. Not saved. ";exit();
            }            
            $stmt=null;
            $sqlColumnsArray = array();            
            if($propertyvaluecode !== '') {
                $sqlColumnsArray['code|s'] = $propertyvaluecode;
            }            
            if($propertyid > 0) {
                $sqlColumnsArray['propertyid|i'] = $propertyid;
            }            
            $sqlColumnsArray['fromcountryid|i'] = $propertyvaluefromcountryid;
            $sqlColumnsArray['fromstateprovinceid|i'] = $propertyvaluefromstateprovinceid;
            $sqlColumnsArray['tocountryid|i'] = $propertyvaluetocountryid;                
            $sqlColumnsArray['tostateprovinceid|i'] = $propertyvaluetostateprovinceid;        
            if($propertyvalueuserate === 1) {
                $sqlColumnsArray['userate|i'] = $propertyvalueuserate;                
                if($propertyvaluerate >= 0) {
                    $sqlColumnsArray['rate|d'] = $propertyvaluerate;                        
                }
            } elseif($propertyvalueuserate === 0) {
                $sqlColumnsArray['userate|i'] = $propertyvalueuserate;
                $sqlColumnsArray['rate|d'] = $propertyvaluerate;                                        
            }
            if($propertyvalueusefee === 1) {
                $sqlColumnsArray['usefee|i'] = $propertyvalueusefee;                
                if($propertyvaluefee >= 0) {
                    $sqlColumnsArray['fee|d'] = $propertyvaluefee;                    
                }
            } elseif($propertyvalueusefee === 0) {
                $sqlColumnsArray['usefee|i'] = $propertyvalueusefee;
                $sqlColumnsArray['fee|d'] = $propertyvaluefee;                
            }            
            $sqlColumnsArray['priority|i'] = $propertyvaluepriority;
            $sqlColumnsArray['minordersubtotal|d'] = $propertyvalueminordersubtotal;
            if($propertyvaluename !== '') {
                $sqlColumnsArray['name|s'] = $propertyvaluename;    
            }
            if($propertyvalueshownname !== '') {
                $sqlColumnsArray['shownname|s'] = $propertyvalueshownname;                    
            }
            $sqlColumnsArray['description|s'] = $propertyvaluedescription;
            if($propertyvaluetaxincludeshipping === 0 || $propertyvaluetaxincludeshipping === 1) {        
                $sqlColumnsArray['taxincludeshipping|i'] = $propertyvaluetaxincludeshipping;            
            }
            if($propertyvaluetaxincludehandling === 0 || $propertyvaluetaxincludehandling === 1) {        
                $sqlColumnsArray['taxincludehandling|i'] = $propertyvaluetaxincludehandling;            
            }
            if($propertyvaluestatus === 0 || $propertyvaluestatus === 1) {        
                $sqlColumnsArray['status|i'] = $propertyvaluestatus;            
            }            
            if($propertyvaluestart !== '') {
                $sqlColumnsArray['start|s'] = $propertyvaluestart;                    
            }
            if($propertyvalueend !== '') {
                $sqlColumnsArray['end|s'] = $propertyvalueend;                
            }
            if(count($sqlColumnsArray) > 0) {
                $query = "UPDATE $table_name SET ";
                $types = '';
                $parameterArray = array('');                
                foreach($sqlColumnsArray as $key => $value) {
                    $temp = explode('|', $key, 2);
                    if($temp[0] === 'priority' && $propertyvaluepriority_isnull === true) {
                        $query .= ' ' . $temp[0] . ' = null, ';
                    } elseif($temp[0] === 'fromcountryid' && $propertyvaluefromcountryid <= 0) {
                        $query .= ' ' . $temp[0] . ' = null, ';                    
                    } elseif($temp[0] === 'fromstateprovinceid' && $propertyvaluefromstateprovinceid <= 0) {
                        $query .= ' ' . $temp[0] . ' = null, ';                    
                    } elseif($temp[0] === 'tocountryid' && $propertyvaluetocountryid <= 0) {
                        $query .= ' ' . $temp[0] . ' = null, ';                    
                    } elseif($temp[0] === 'tostateprovinceid' && $propertyvaluetostateprovinceid <= 0) {
                        $query .= ' ' . $temp[0] . ' = null, ';                    
                    } elseif($temp[0] === 'description' && $propertyvaluedescription === '') {
                        $query .= ' ' . $temp[0] . ' = null, ';                    
                    } elseif($temp[0] === 'minordersubtotal' && $propertyvalueminordersubtotal <= 0) {
                        $query .= ' ' . $temp[0] . ' = null, ';                    
                    } elseif($temp[0] === 'rate' && $propertyvalueuserate === 0) {
                        $query .= ' ' . $temp[0] . ' = null, ';                    
                    } elseif($temp[0] === 'fee' && $propertyvalueusefee === 0) {
                        $query .= ' ' . $temp[0] . ' = null, ';                    
                    } else {
                        $types .= $temp[1];
                        $query .= ' ' . $temp[0] . ' = ?, ';
                    }                    
                    if($temp[0] === 'code') {
                        $parameterArray[] = &$propertyvaluecode;
                    } elseif($temp[0] === 'propertyid') {
                        $parameterArray[] = &$propertyid;
                    } elseif($temp[0] === 'fromcountryid') {
                        if($propertyvaluefromcountryid > 0) {
                            $parameterArray[] = &$propertyvaluefromcountryid;
                        }
                    } elseif($temp[0] === 'fromstateprovinceid') {
                        if($propertyvaluefromstateprovinceid > 0) {
                            $parameterArray[] = &$propertyvaluefromstateprovinceid;
                        }
                    } elseif($temp[0] === 'tocountryid') {
                        if($propertyvaluetocountryid > 0 ) {
                            $parameterArray[] = &$propertyvaluetocountryid;
                        }
                    } elseif($temp[0] === 'tostateprovinceid') {
                        if($propertyvaluetostateprovinceid > 0) {
                            $parameterArray[] = &$propertyvaluetostateprovinceid;
                        }
                    } elseif($temp[0] === 'userate') {
                        $parameterArray[] = &$propertyvalueuserate;
                    } elseif($temp[0] === 'rate') {
                        if($propertyvalueuserate === 1) {
                            $parameterArray[] = &$propertyvaluerate;
                        }
                    } elseif($temp[0] === 'usefee') {
                        $parameterArray[] = &$propertyvalueusefee;
                    } elseif($temp[0] === 'fee') {
                        if($propertyvalueusefee === 1) {
                            $parameterArray[] = &$propertyvaluefee;
                        }
                    } elseif($temp[0] === 'priority') {
                        if($propertyvaluepriority_isnull !== true) {
                            $parameterArray[] = &$propertyvaluepriority;
                        }
                    } elseif($temp[0] === 'minordersubtotal') {
                        if($propertyvalueminordersubtotal > 0) {
                            $parameterArray[] = &$propertyvalueminordersubtotal;
                        }
                    } elseif($temp[0] === 'name') {
                        $parameterArray[] = &$propertyvaluename;
                    } elseif($temp[0] === 'shownname') {
                        $parameterArray[] = &$propertyvalueshownname;
                    } elseif($temp[0] === 'description') {
                        if($propertyvaluedescription !== '') {
                            $parameterArray[] = &$propertyvaluedescription;
                        }
                    } elseif($temp[0] === 'status') {
                        $parameterArray[] = &$propertyvaluestatus;
                    } elseif($temp[0] === 'start') {
                        $parameterArray[] = &$propertyvaluestart;
                    } elseif($temp[0] === 'end') {
                        $parameterArray[] = &$propertyvalueend;
                    } elseif($temp[0] === 'taxincludeshipping') {
                        $parameterArray[] = &$propertyvaluetaxincludeshipping;
                    } elseif($temp[0] === 'taxincludehandling') {
                        $parameterArray[] = &$propertyvaluetaxincludehandling;
                    }                    
                }
                $query .= " updatetimeutc = UTC_TIMESTAMP() WHERE id = ? ";                
                $types .= 'i';
                $parameterArray[] = &$propertyvalueid;                
                $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 property value failed';
                }
                $stmt->close();                                
            } else {
                $finalresult = 'Nothing is updated';
            }                                    
            echo esc_html($finalresult);                                
            exit();    
        }        
    }
    echo 'Invalid data.';
    exit();
}

//This function is only for admin role in admin page, not for customers shopping page
add_action('wp_ajax_dragonecommercereservezyx987_getProducts', 'dragonecommercereservezyx987_getProducts'); 
function dragonecommercereservezyx987_getProducts() {
    check_ajax_referer('dragonecommercereservezyx987_getProducts', 'dragonecommercereservezyx987_hidden_security_getproducts');
    $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 json_encode("{}");    
        exit();
    }    
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_product';
        $table_name2 = 'wp_dragonecommercereservezyx987_department';
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getProductList';

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

        $amountperpage = empty($_POST['amountperpage']) ? '10' : sanitize_text_field($_POST['amountperpage']);
        $amountperpage = strip_tags($amountperpage);
        $amountperpage = intval($amountperpage);    
        if($amountperpage === -1) {$amountperpage = 10;}
                    
        $pagenumber = empty($_POST['pagenumber']) ? '1' : sanitize_text_field($_POST['pagenumber']);;
        $pagenumber = strip_tags($pagenumber);
        $pagenumber = intval($pagenumber);    
        
        $myoffset = ($pagenumber - 1) * $amountperpage;
        
        $mysortby = empty($_POST['sortby']) ? '' : sanitize_text_field($_POST['sortby']);
        $mysortby = strip_tags($mysortby);
        $mysortby = $mysortby === '' ? 'id' : $mysortby;
        
        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : sanitize_text_field($_POST['order']);
        $myorder = strip_tags($myorder);
        $myorder = $myorder === '' ? 'asc' : $myorder;
        
        $searchwords = empty($_POST['searchwords']) ? '' : sanitize_text_field($_POST['searchwords']);
        $searchwords = strip_tags($searchwords);
        $barcode = empty($_POST['barcode']) ? '' : sanitize_text_field($_POST['barcode']);
        $barcode = strip_tags($barcode);

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

        $minprice = empty($_POST['minprice']) ? '0.00' : sanitize_text_field($_POST['minprice']);
        $minprice = strip_tags($minprice);
        $minprice = floatval($minprice);            

        $maxprice = empty($_POST['maxprice']) ? '9999999999999.00' : sanitize_text_field($_POST['maxprice']);
        $maxprice = strip_tags($maxprice);
        $maxprice = floatval($maxprice);            
        
        $fromdate = empty($_POST['fromdate']) ? '1000-01-01 00:00:00' : sanitize_text_field($_POST['fromdate']);
        $fromdate = strip_tags($fromdate);            
        $todate = empty($_POST['todate']) ? '9999-12-31 23:59:59' : sanitize_text_field($_POST['todate']);
        $todate = strip_tags($todate);
        
        $isonsale_temp = (!isset($_POST['isonsale'])) ? '0' : sanitize_text_field($_POST['isonsale']);
        $isonsale_temp = strip_tags($isonsale_temp);
        $isonsale = intval($isonsale_temp);

        $istaxfree_temp = (!isset($_POST['istaxfree'])) ? '0' : sanitize_text_field($_POST['istaxfree']);
        $istaxfree_temp = strip_tags($istaxfree_temp);
        $istaxfree = intval($istaxfree_temp);        
                
        if(dragonecommercereservezyx987_validateDate($fromdate) && dragonecommercereservezyx987_validateDate($todate)) {
            if($fromdate > $todate) {
                echo "Error. From date is later than to date.";exit();                        
            }
        }else{
            echo "Error. Please enter a valid date.";exit();    
        }
        if($isonsale === 0 || $isonsale === -1 || $isonsale === 1) {
        } else {
            echo esc_html("Error. Incorrect is on sale value: " . $isonsale);exit();            
        }
        if($istaxfree === 0 || $istaxfree === -1 || $istaxfree === 1) {
        } else {
            echo esc_html("Error. Incorrect is tax free value: " . $istaxfree);exit();            
        }        
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $query = "CALL " . $storedprocedure_name . "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, @outvalue, @outvalue2);";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

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

            $types .= 'i';
            $parameterArray[] = &$istaxfree;
            
            $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[] = &$barcode;
            
            $types .= 'i';
            $parameterArray[] = &$departmentid;        

            $types .= 'd';
            $minprice2 = floatval($minprice);
            $parameterArray[] = &$minprice2;    

            $types .= 'd';
            $maxprice2 = floatval($maxprice);
            $parameterArray[] = &$maxprice2;

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

            $types .= 's';
            $parameterArray[] = &$todate;                
            
            $types .= 'i'; //0: inactive, 1: active, -1: both
            $parameterArray[] = &$productstatus;                            
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $products = $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 ($products as $product) {
                foreach ($product as $key => $value) {                
                    $product[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["product"] = $products;
            $result["total"] = $total;                            
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_getProductdetails', 'dragonecommercereservezyx987_getProductdetails'); 
function dragonecommercereservezyx987_getProductdetails() {
    check_ajax_referer('dragonecommercereservezyx987_getProductdetails', 'dragonecommercereservezyx987_hidden_security_getproductdetails');
    if((!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_product';
        $table_name2 = 'wp_dragonecommercereservezyx987_department';
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getProductdetailsList';

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

        $amountperpage = empty($_POST['amountperpage']) ? '10' : sanitize_text_field($_POST['amountperpage']);
        $amountperpage = strip_tags($amountperpage);
        $amountperpage = intval($amountperpage);    
        if($amountperpage === -1) {$amountperpage = 10;}
                    
        $pagenumber = empty($_POST['pagenumber']) ? '1' : sanitize_text_field($_POST['pagenumber']);;
        $pagenumber = strip_tags($pagenumber);
        $pagenumber = intval($pagenumber);    
        
        $myoffset = ($pagenumber - 1) * $amountperpage;
        
        $mysortby = empty($_POST['sortby']) ? '' : sanitize_text_field($_POST['sortby']);
        $mysortby = strip_tags($mysortby);
        $mysortby = $mysortby === '' ? 'id' : $mysortby;
        
        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : sanitize_text_field($_POST['order']);
        $myorder = strip_tags($myorder);
        $myorder = $myorder === '' ? 'asc' : $myorder;
        
        $searchwords = empty($_POST['searchwords']) ? '' : sanitize_text_field($_POST['searchwords']);
        $searchwords = strip_tags($searchwords);
        $barcode = empty($_POST['barcode']) ? '' : sanitize_text_field($_POST['barcode']);
        $barcode = strip_tags($barcode);

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

        $minprice = empty($_POST['minprice']) ? '0.00' : sanitize_text_field($_POST['minprice']);
        $minprice = strip_tags($minprice);
        $minprice = floatval($minprice);            

        $maxprice = empty($_POST['maxprice']) ? '-1.00' : sanitize_text_field($_POST['maxprice']);
        $maxprice = strip_tags($maxprice);
        $maxprice = floatval($maxprice);            
        
        $fromdate = empty($_POST['fromdate']) ? '1000-01-01 00:00:00' : sanitize_text_field($_POST['fromdate']);
        $fromdate = strip_tags($fromdate);            
        $todate = empty($_POST['todate']) ? '9999-12-31 23:59:59' : sanitize_text_field($_POST['todate']);
        $todate = strip_tags($todate);
        
        $isonsale_temp = (!isset($_POST['isonsale'])) ? '0' : sanitize_text_field($_POST['isonsale']);
        $isonsale_temp = strip_tags($isonsale_temp);
        $isonsale = intval($isonsale_temp);

        $istaxfree_temp = (!isset($_POST['istaxfree'])) ? '0' : sanitize_text_field($_POST['istaxfree']);
        $istaxfree_temp = strip_tags($istaxfree_temp);
        $istaxfree = intval($istaxfree_temp);        
                
        if(dragonecommercereservezyx987_validateDate($fromdate) && dragonecommercereservezyx987_validateDate($todate)) {
            if($fromdate > $todate) {
                echo "Error. From date is later than to date.";exit();                        
            }
        }else{
            echo "Error. Please enter a valid date.";exit();    
        }
        if($isonsale === 0 || $isonsale === -1 || $isonsale === 1) {
        } else {
            echo esc_html("Error. Incorrect is on sale value: " . $isonsale);exit();            
        }
        if($istaxfree === 0 || $istaxfree === -1 || $istaxfree === 1) {
        } else {
            echo esc_html("Error. Incorrect is tax free value: " . $istaxfree);exit();            
        }        
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $query = "CALL " . $storedprocedure_name . "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, @outvalue, @outvalue2);";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

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

            $types .= 'i';
            $parameterArray[] = &$istaxfree;
            
            $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[] = &$barcode;
            
            $types .= 'i';
            $parameterArray[] = &$departmentid;        

            $types .= 'd';
            $minprice2 = floatval($minprice);
            $parameterArray[] = &$minprice2;    

            $types .= 'd';
            $maxprice2 = floatval($maxprice);
            $parameterArray[] = &$maxprice2;

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

            $types .= 's';
            $parameterArray[] = &$todate;                
            
            $types .= 'i'; //0: inactive, 1: active, -1: both
            $parameterArray[] = &$productstatus;                            
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $products = $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 ($products as $product) {
                foreach ($product as $key => $value) {                
                    $product[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["productdetails"] = $products;
            $result["total"] = $total;                            
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_saveProductdetails', 'dragonecommercereservezyx987_saveProductdetails');
function dragonecommercereservezyx987_saveProductdetails() {
    check_ajax_referer('dragonecommercereservezyx987_saveProductdetails', 'dragonecommercereservezyx987_hidden_security_saveproductdetails');
    $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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $productid_temp = empty($_POST['id']) ? 0 : sanitize_text_field($_POST['id']);
        $productid_temp = strip_tags($productid_temp);
        $productid = intval($productid_temp);
        
        if($productid <= 0) {echo "Invalid id.";exit();}

        $productdetailsquantity_temp = $_POST['quantity'] === null ? '' : sanitize_text_field($_POST['quantity']);
        $productdetailsquantity_temp = strip_tags($productdetailsquantity_temp);
        $productdetailsquantity = $productdetailsquantity_temp === '' ? 0 : intval($productdetailsquantity_temp);
        $productdetailsquantity_isnull = $productdetailsquantity_temp === 'null' ? true : false;        

        $productdetailsoriginalquantity_temp = $_POST['originalquantity'] === null ? '' : sanitize_text_field($_POST['originalquantity']);
        $productdetailsoriginalquantity_temp = strip_tags($productdetailsoriginalquantity_temp);
        $productdetailsoriginalquantity = $productdetailsoriginalquantity_temp === '' ? 0 : intval($productdetailsoriginalquantity_temp);
        $productdetailsoriginalquantity_isnull = $productdetailsoriginalquantity_temp === 'null' ? true : false;
        
        if($productdetailsquantity_temp === 'invalid') {
            echo "Quantity should be an integer.";exit();
        }
        if($productdetailsoriginalquantity_temp === 'invalid') {
            echo "Original quantity should be an integer.";exit();
        }
        $propertyvalueids_temp = $_POST['propertyvalueids'] === null ? '' : sanitize_text_field($_POST['propertyvalueids']);
        $propertyvalueids = strip_tags($propertyvalueids_temp);
        if($propertyvalueids === '') {
            echo "This product has no property value ids in the table. Not saved.";exit();
        }        
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_product_propertyvalue';
        $finalresult = 'Success';                    
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }            
            $stmt=null;
            $sqlColumnsArray = array();        
            if($productdetailsquantity >= 0) {
                $sqlColumnsArray['quantity|i'] = $productdetailsquantity;
            }
            if($productdetailsoriginalquantity >= 0) {
                $sqlColumnsArray['originalquantity|i'] = $productdetailsoriginalquantity;
            }
            if(count($sqlColumnsArray) > 0) {
                $query = "UPDATE $table_name SET ";
                $types = '';
                $parameterArray = array('');                
                foreach($sqlColumnsArray as $key => $value) {
                    $temp = explode('|', $key, 2);
                    if($temp[0] === 'quantity' && $productdetailsquantity_isnull === true) {
                        $query .= ' ' . $temp[0] . ' = null, ';
                    } elseif($temp[0] === 'originalquantity' && $productdetailsoriginalquantity_isnull === true) {
                        $query .= ' ' . $temp[0] . ' = null, ';
                    } else {
                        $types .= $temp[1];
                        $query .= ' ' . $temp[0] . ' = ?, ';
                    }
                    if($temp[0] === 'quantity') {
                        if($productdetailsquantity_isnull !== true) {
                            $parameterArray[] = &$productdetailsquantity;
                        }
                    } elseif($temp[0] === 'originalquantity') {
                        if($productdetailsoriginalquantity_isnull !== true) {
                            $parameterArray[] = &$productdetailsoriginalquantity;
                        }
                    }                    
                }
                $query .= " updatetimeutc = UTC_TIMESTAMP() WHERE productid = ? AND propertyvalueids = ?";                
                $types .= 'i';
                $parameterArray[] = &$productid;
                $types .= 's';
                $parameterArray[] = &$propertyvalueids;
                
                $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 product details failed';
                }
                $stmt->close();                                
            } else {
                $finalresult = 'Nothing is updated';
            }                                    
            echo esc_html($finalresult);                                
            exit();                    
        }
    }
    echo "Invalid data.";
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_getUsers', 'dragonecommercereservezyx987_getUsers');
function dragonecommercereservezyx987_getUsers() {
    check_ajax_referer('dragonecommercereservezyx987_getUsers', 'dragonecommercereservezyx987_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 json_encode("{}");    
        exit();
    }    
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = $wpdb->prefix . 'users';
        $table_name2 = 'wp_dragonecommercereservezyx987_user_status';
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getUserList';

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

        $amountperpage = empty($_POST['amountperpage']) ? '10' : sanitize_text_field($_POST['amountperpage']);
        $amountperpage = strip_tags($amountperpage);
        $amountperpage = intval($amountperpage);    
        if($amountperpage === -1) {$amountperpage = 10;}
                    
        $pagenumber = empty($_POST['pagenumber']) ? '1' : sanitize_text_field($_POST['pagenumber']);;
        $pagenumber = strip_tags($pagenumber);
        $pagenumber = intval($pagenumber);    
    
        $myoffset = ($pagenumber - 1) * $amountperpage;
        
        $mysortby = empty($_POST['sortby']) ? '' : sanitize_text_field($_POST['sortby']);
        $mysortby = strip_tags($mysortby);
        $mysortby = $mysortby === '' ? 'id' : $mysortby;
        
        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : sanitize_text_field($_POST['order']);
        $myorder = strip_tags($myorder);
        $myorder = $myorder === '' ? 'asc' : $myorder;
        
        $searchwords = empty($_POST['searchwords']) ? '' : sanitize_text_field($_POST['searchwords']);
        $searchwords = strip_tags($searchwords);
        $email = empty($_POST['searchemail']) ? '' : sanitize_text_field($_POST['searchemail']);
        $email = strip_tags($email);            
        
        $fromdate = empty($_POST['fromdate']) ? '1000-01-01 00:00:00' : sanitize_text_field($_POST['fromdate']);
        $fromdate = strip_tags($fromdate);            
        $todate = empty($_POST['todate']) ? '9999-12-31 23:59:59' : sanitize_text_field($_POST['todate']);
        $todate = strip_tags($todate);

        if(dragonecommercereservezyx987_validateDate($fromdate) && dragonecommercereservezyx987_validateDate($todate)) {
            if($fromdate > $todate) {
                echo "Error. From date is later than to date.";exit();                        
            }
        }else{
            echo "Error. Please enter a valid date.";exit();    
        }            
        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 .= 's';
            $tablenameprefix = $wpdb->prefix;
            $parameterArray[] = &$tablenameprefix;
            
            $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[] = &$email;                

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

            $types .= 's';
            $parameterArray[] = &$todate;                
            
            $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 json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_getCountries', 'dragonecommercereservezyx987_getCountriesByAjax');
function dragonecommercereservezyx987_getCountriesByAjax() {
    check_ajax_referer('dragonecommercereservezyx987_getCountries', 'dragonecommercereservezyx987_hidden_security_getcountries');
    $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 json_encode("{}");    
        exit();
    }    
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_country';
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getCountryList';

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

        $amountperpage = empty($_POST['amountperpage']) ? '10' : sanitize_text_field($_POST['amountperpage']);
        $amountperpage = strip_tags($amountperpage);
        $amountperpage = intval($amountperpage);    
        if($amountperpage === -1) {$amountperpage = 10;}
                    
        $pagenumber = empty($_POST['pagenumber']) ? '1' : sanitize_text_field($_POST['pagenumber']);;
        $pagenumber = strip_tags($pagenumber);
        $pagenumber = intval($pagenumber);    
    
        $myoffset = ($pagenumber - 1) * $amountperpage;
        
        $mysortby = empty($_POST['sortby']) ? '' : sanitize_text_field($_POST['sortby']);
        $mysortby = strip_tags($mysortby);
        $mysortby = $mysortby === '' ? 'id' : $mysortby;
        
        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : sanitize_text_field($_POST['order']);
        $myorder = strip_tags($myorder);
        $myorder = $myorder === '' ? 'asc' : $myorder;
        
        $searchwords = empty($_POST['searchwords']) ? '' : sanitize_text_field($_POST['searchwords']);
        $searchwords = strip_tags($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[] = &$countrystatus;                            
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $countries = $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 ($countries as $country) {
                foreach ($country as $key => $value) {                
                    $country[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["country"] = $countries;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_getProvinces', 'dragonecommercereservezyx987_getProvincesByAjax');
function dragonecommercereservezyx987_getProvincesByAjax() {
    check_ajax_referer('dragonecommercereservezyx987_getProvinces', 'dragonecommercereservezyx987_hidden_security_getprovinces');
    $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 json_encode("{}");
        exit();
    }    
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_province';
        $table_name2 = 'wp_dragonecommercereservezyx987_country';
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getProvinceList';

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

        $amountperpage = empty($_POST['amountperpage']) ? '10' : sanitize_text_field($_POST['amountperpage']);
        $amountperpage = strip_tags($amountperpage);
        $amountperpage = intval($amountperpage);    
        if($amountperpage === -1) {$amountperpage = 10;}
                    
        $pagenumber = empty($_POST['pagenumber']) ? '1' : sanitize_text_field($_POST['pagenumber']);;
        $pagenumber = strip_tags($pagenumber);
        $pagenumber = intval($pagenumber);    
    
        $myoffset = ($pagenumber - 1) * $amountperpage;
        
        $mysortby = empty($_POST['sortby']) ? '' : sanitize_text_field($_POST['sortby']);
        $mysortby = strip_tags($mysortby);
        $mysortby = $mysortby === '' ? 'id' : $mysortby;
        
        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : sanitize_text_field($_POST['order']);
        $myorder = strip_tags($myorder);
        $myorder = $myorder === '' ? 'asc' : $myorder;
        
        $searchwords = empty($_POST['searchwords']) ? '' : sanitize_text_field($_POST['searchwords']);
        $searchwords = strip_tags($searchwords);
        $countryid = empty($_POST['countryid']) ? '0' : sanitize_text_field($_POST['countryid']);
        $countryid = strip_tags($countryid);
        $countryid = intval($countryid);    
        if($countryid === -1) {$countryid = 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 .= 'i';
            $parameterArray[] = &$countryid;            
            
            $types .= 'i'; //0: inactive, 1: active, -1: both
            $parameterArray[] = &$provincestatus;                            
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $countries = $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 ($countries as $country) {
                foreach ($country as $key => $value) {                
                    $country[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["province"] = $countries;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_getCities', 'dragonecommercereservezyx987_getCitiesByAjax');
function dragonecommercereservezyx987_getCitiesByAjax() {
    check_ajax_referer('dragonecommercereservezyx987_getCities', 'dragonecommercereservezyx987_hidden_security_getcities');
    $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 json_encode("{}");    
        exit();
    }    
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getCityList';

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

        $amountperpage = empty($_POST['amountperpage']) ? '10' : sanitize_text_field($_POST['amountperpage']);
        $amountperpage = strip_tags($amountperpage);
        $amountperpage = intval($amountperpage);    
        if($amountperpage === -1) {$amountperpage = 10;}
                    
        $pagenumber = empty($_POST['pagenumber']) ? '1' : sanitize_text_field($_POST['pagenumber']);;
        $pagenumber = strip_tags($pagenumber);
        $pagenumber = intval($pagenumber);    
    
        $myoffset = ($pagenumber - 1) * $amountperpage;
        
        $mysortby = empty($_POST['sortby']) ? '' : sanitize_text_field($_POST['sortby']);
        $mysortby = strip_tags($mysortby);
        $mysortby = $mysortby === '' ? 'id' : $mysortby;
        
        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : sanitize_text_field($_POST['order']);
        $myorder = strip_tags($myorder);
        $myorder = $myorder === '' ? 'asc' : $myorder;
        
        $searchwords = empty($_POST['searchwords']) ? '' : sanitize_text_field($_POST['searchwords']);
        $searchwords = strip_tags($searchwords);
        $countryid = empty($_POST['countryid']) ? '0' : sanitize_text_field($_POST['countryid']);
        $countryid = strip_tags($countryid);
        $countryid = intval($countryid);
        if($countryid === -1) {$countryid = 0;}
        
        $provinceid = empty($_POST['provinceid']) ? '0' : sanitize_text_field($_POST['provinceid']);
        $provinceid = strip_tags($provinceid);
        $provinceid = intval($provinceid);
        if($provinceid === -1) {$provinceid = 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 .= 'i';
            $parameterArray[] = &$countryid;                

            $types .= 'i';
            $parameterArray[] = &$provinceid;            
            
            $types .= 'i'; //0: inactive, 1: active, -1: both
            $parameterArray[] = &$citystatus;                            
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $cities = $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 ($cities as $city) {
                foreach ($city as $key => $value) {                
                    $city[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["city"] = $cities;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_getCurrencies', 'dragonecommercereservezyx987_getCurrenciesByAjax');
function dragonecommercereservezyx987_getCurrenciesByAjax() {
    check_ajax_referer('dragonecommercereservezyx987_getCurrencies', 'dragonecommercereservezyx987_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 json_encode("{}");
        exit();
    }    
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getCurrencyList';

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

        $amountperpage = empty($_POST['amountperpage']) ? '10' : sanitize_text_field($_POST['amountperpage']);
        $amountperpage = strip_tags($amountperpage);
        $amountperpage = intval($amountperpage);    
        if($amountperpage === -1) {$amountperpage = 10;}
                    
        $pagenumber = empty($_POST['pagenumber']) ? '1' : sanitize_text_field($_POST['pagenumber']);;
        $pagenumber = strip_tags($pagenumber);
        $pagenumber = intval($pagenumber);    
    
        $myoffset = ($pagenumber - 1) * $amountperpage;
        
        $mysortby = empty($_POST['sortby']) ? '' : sanitize_text_field($_POST['sortby']);
        $mysortby = strip_tags($mysortby);
        $mysortby = $mysortby === '' ? 'id' : $mysortby;
        
        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : sanitize_text_field($_POST['order']);
        $myorder = strip_tags($myorder);
        $myorder = $myorder === '' ? 'asc' : $myorder;
        
        $searchwords = empty($_POST['searchwords']) ? '' : sanitize_text_field($_POST['searchwords']);
        $searchwords = strip_tags($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 json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_getDepartments', 'dragonecommercereservezyx987_getDepartmentsByAjax');
function dragonecommercereservezyx987_getDepartmentsByAjax() {
    check_ajax_referer('dragonecommercereservezyx987_getDepartments', 'dragonecommercereservezyx987_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 json_encode("{}");    
        exit();
    }    
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_department';
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getDepartmentList';

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

        $amountperpage = empty($_POST['amountperpage']) ? '10' : sanitize_text_field($_POST['amountperpage']);
        $amountperpage = strip_tags($amountperpage);
        $amountperpage = intval($amountperpage);    
        if($amountperpage === -1) {$amountperpage = 10;}
                    
        $pagenumber = empty($_POST['pagenumber']) ? '1' : sanitize_text_field($_POST['pagenumber']);;
        $pagenumber = strip_tags($pagenumber);
        $pagenumber = intval($pagenumber);    
    
        $myoffset = ($pagenumber - 1) * $amountperpage;
        
        $mysortby = empty($_POST['sortby']) ? '' : sanitize_text_field($_POST['sortby']);
        $mysortby = strip_tags($mysortby);
        $mysortby = $mysortby === '' ? 'id' : $mysortby;
        
        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : sanitize_text_field($_POST['order']);
        $myorder = strip_tags($myorder);
        $myorder = $myorder === '' ? 'asc' : $myorder;
        
        $searchwords = empty($_POST['searchwords']) ? '' : sanitize_text_field($_POST['searchwords']);
        $searchwords = strip_tags($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();
            $countries = $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 ($countries as $country) {
                foreach ($country as $key => $value) {                
                    $country[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["department"] = $countries;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_getGroupcategories', 'dragonecommercereservezyx987_getGroupcategoriesByAjax');
function dragonecommercereservezyx987_getGroupcategoriesByAjax() {
    check_ajax_referer('dragonecommercereservezyx987_getGroupcategories', 'dragonecommercereservezyx987_hidden_security_getgroupcategories');
    $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 json_encode("{}");    
        exit();
    }    
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_groupcategory';
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getGroupcategoryList';

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

        $amountperpage = empty($_POST['amountperpage']) ? '10' : sanitize_text_field($_POST['amountperpage']);
        $amountperpage = strip_tags($amountperpage);
        $amountperpage = intval($amountperpage);    
        if($amountperpage === -1) {$amountperpage = 10;}
                    
        $pagenumber = empty($_POST['pagenumber']) ? '1' : sanitize_text_field($_POST['pagenumber']);;
        $pagenumber = strip_tags($pagenumber);
        $pagenumber = intval($pagenumber);    
    
        $myoffset = ($pagenumber - 1) * $amountperpage;
        
        $mysortby = empty($_POST['sortby']) ? '' : sanitize_text_field($_POST['sortby']);
        $mysortby = strip_tags($mysortby);
        $mysortby = $mysortby === '' ? 'id' : $mysortby;
        
        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : sanitize_text_field($_POST['order']);
        $myorder = strip_tags($myorder);
        $myorder = $myorder === '' ? 'asc' : $myorder;
        
        $searchwords = empty($_POST['searchwords']) ? '' : sanitize_text_field($_POST['searchwords']);
        $searchwords = strip_tags($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[] = &$groupcategorystatus;                            
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $countries = $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 ($countries as $country) {
                foreach ($country as $key => $value) {                
                    $country[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["groupcategory"] = $countries;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_getProcessstatuses', 'dragonecommercereservezyx987_getProcessstatusesByAjax');
function dragonecommercereservezyx987_getProcessstatusesByAjax() {
    check_ajax_referer('dragonecommercereservezyx987_getProcessstatuses', 'dragonecommercereservezyx987_hidden_security_getprocessstatuses');
    $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 json_encode("{}");    
        exit();
    }
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_processstatus';
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getProcessstatusList';

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

        $amountperpage = empty($_POST['amountperpage']) ? '10' : sanitize_text_field($_POST['amountperpage']);
        $amountperpage = strip_tags($amountperpage);
        $amountperpage = intval($amountperpage);    
        if($amountperpage === -1) {$amountperpage = 10;}
                    
        $pagenumber = empty($_POST['pagenumber']) ? '1' : sanitize_text_field($_POST['pagenumber']);;
        $pagenumber = strip_tags($pagenumber);
        $pagenumber = intval($pagenumber);    
    
        $myoffset = ($pagenumber - 1) * $amountperpage;
        
        $mysortby = empty($_POST['sortby']) ? '' : sanitize_text_field($_POST['sortby']);
        $mysortby = strip_tags($mysortby);
        $mysortby = $mysortby === '' ? 'id' : $mysortby;
        
        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : sanitize_text_field($_POST['order']);
        $myorder = strip_tags($myorder);
        $myorder = $myorder === '' ? 'asc' : $myorder;
        
        $searchwords = empty($_POST['searchwords']) ? '' : sanitize_text_field($_POST['searchwords']);
        $searchwords = strip_tags($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[] = &$processstatusstatus;                            
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $processstatuses = $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 ($processstatuses as $processstatus) {
                foreach ($processstatus as $key => $value) {                
                    $processstatus[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["processstatus"] = $processstatuses;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_getGroups', 'dragonecommercereservezyx987_getGroupsByAjax');
function dragonecommercereservezyx987_getGroupsByAjax() {
    check_ajax_referer('dragonecommercereservezyx987_getGroups', 'dragonecommercereservezyx987_hidden_security_getgroups');
    $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 json_encode("{}");
        exit();
    }    
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $temp = '';            
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_group';
        $table_name2 = 'wp_dragonecommercereservezyx987_groupcategory';
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getGroupList';

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

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

        $myoffset = ($pagenumber - 1) * $amountperpage;
        
        $mysortby = empty($_POST['sortby']) ? '' : sanitize_text_field($_POST['sortby']);
        $mysortby = strip_tags($mysortby);
        $mysortby = $mysortby === '' ? 'id' : $mysortby;
        
        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : sanitize_text_field($_POST['order']);
        $myorder = strip_tags($myorder);
        $myorder = $myorder === '' ? 'asc' : $myorder;
        
        $searchwords = empty($_POST['searchwords']) ? '' : sanitize_text_field($_POST['searchwords']);
        $searchwords = strip_tags($searchwords);
        $groupcategoryname = empty($_POST['groupcategoryname']) ? '' : sanitize_text_field($_POST['groupcategoryname']);
        $groupcategoryname = strip_tags($groupcategoryname);
            
        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[] = &$groupcategoryname;        
            
            $types .= 'i'; //0: inactive, 1: active, -1: both
            $parameterArray[] = &$groupstatus;                            
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $groups = $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 ($groups as $group) {
                foreach ($group as $key => $value) {                
                    $group[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["group"] = $groups;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_getChargetypes', 'dragonecommercereservezyx987_getChargetypesByAjax');
function dragonecommercereservezyx987_getChargetypesByAjax() {
    check_ajax_referer('dragonecommercereservezyx987_getChargetypes', 'dragonecommercereservezyx987_hidden_security_getchargetypes');
    $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 json_encode("{}");
        exit();
    }    
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_chargetype';
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getChargetypeList';

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

        $amountperpage = empty($_POST['amountperpage']) ? '10' : sanitize_text_field($_POST['amountperpage']);
        $amountperpage = strip_tags($amountperpage);
        $amountperpage = intval($amountperpage);    
        if($amountperpage === -1) {$amountperpage = 10;}
                    
        $pagenumber = empty($_POST['pagenumber']) ? '1' : sanitize_text_field($_POST['pagenumber']);;
        $pagenumber = strip_tags($pagenumber);
        $pagenumber = intval($pagenumber);    
    
        $myoffset = ($pagenumber - 1) * $amountperpage;
        
        $mysortby = empty($_POST['sortby']) ? '' : sanitize_text_field($_POST['sortby']);
        $mysortby = strip_tags($mysortby);
        $mysortby = $mysortby === '' ? 'id' : $mysortby;
        
        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : sanitize_text_field($_POST['order']);
        $myorder = strip_tags($myorder);
        $myorder = $myorder === '' ? 'asc' : $myorder;
        
        $searchwords = empty($_POST['searchwords']) ? '' : sanitize_text_field($_POST['searchwords']);
        $searchwords = strip_tags($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[] = &$chargetypestatus;                            
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $processstatuses = $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 ($processstatuses as $processstatus) {
                foreach ($processstatus as $key => $value) {                
                    $processstatus[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["chargetype"] = $processstatuses;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_getDistances', 'dragonecommercereservezyx987_getDistancesByAjax');
function dragonecommercereservezyx987_getDistancesByAjax() {
    check_ajax_referer('dragonecommercereservezyx987_getDistances', 'dragonecommercereservezyx987_hidden_security_getdistances');
    $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 json_encode("{}");
        exit();
    }    
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_distance';
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getDistanceList';

        $amountperpage = empty($_POST['amountperpage']) ? '10' : sanitize_text_field($_POST['amountperpage']);
        $amountperpage = strip_tags($amountperpage);
        $amountperpage = intval($amountperpage);    
        if($amountperpage === -1) {$amountperpage = 10;}
                    
        $pagenumber = empty($_POST['pagenumber']) ? '1' : sanitize_text_field($_POST['pagenumber']);;
        $pagenumber = strip_tags($pagenumber);
        $pagenumber = intval($pagenumber);    
    
        $myoffset = ($pagenumber - 1) * $amountperpage;
        
        $mysortby = empty($_POST['sortby']) ? '' : sanitize_text_field($_POST['sortby']);
        $mysortby = strip_tags($mysortby);
        $mysortby = $mysortby === '' ? 'id' : $mysortby;
        
        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : sanitize_text_field($_POST['order']);
        $myorder = strip_tags($myorder);
        $myorder = $myorder === '' ? 'asc' : $myorder;
        
        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;                        
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $distances = $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 ($distances as $distance) {
                foreach ($distance as $key => $value) {                
                    $distance[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["distance"] = $distances;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_getWeights', 'dragonecommercereservezyx987_getWeightsByAjax');
function dragonecommercereservezyx987_getWeightsByAjax() {
    check_ajax_referer('dragonecommercereservezyx987_getWeights', 'dragonecommercereservezyx987_hidden_security_getweights');
    $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 json_encode("{}");
        exit();
    }    
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

        $table_name = 'wp_dragonecommercereservezyx987_weight';
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getWeightList';

        $amountperpage = empty($_POST['amountperpage']) ? '10' : sanitize_text_field($_POST['amountperpage']);
        $amountperpage = strip_tags($amountperpage);
        $amountperpage = intval($amountperpage);    
        if($amountperpage === -1) {$amountperpage = 10;}
                    
        $pagenumber = empty($_POST['pagenumber']) ? '1' : sanitize_text_field($_POST['pagenumber']);;
        $pagenumber = strip_tags($pagenumber);
        $pagenumber = intval($pagenumber);    
    
        $myoffset = ($pagenumber - 1) * $amountperpage;
        
        $mysortby = empty($_POST['sortby']) ? '' : sanitize_text_field($_POST['sortby']);
        $mysortby = strip_tags($mysortby);
        $mysortby = $mysortby === '' ? 'id' : $mysortby;
        
        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : sanitize_text_field($_POST['order']);
        $myorder = strip_tags($myorder);
        $myorder = $myorder === '' ? 'asc' : $myorder;
        
        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;                        
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $weights = $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 ($weights as $weight) {
                foreach ($weight as $key => $value) {                
                    $weight[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["weight"] = $weights;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_getEmailmethods', 'dragonecommercereservezyx987_getEmailmethodsByAjax');
function dragonecommercereservezyx987_getEmailmethodsByAjax() {
    check_ajax_referer('dragonecommercereservezyx987_getEmailmethods', 'dragonecommercereservezyx987_hidden_security_getemailmethods');
    $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 json_encode("{}");
        exit();
    }    
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_emailmethod';
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getEmailmethodList';

        $amountperpage = empty($_POST['amountperpage']) ? '10' : sanitize_text_field($_POST['amountperpage']);
        $amountperpage = strip_tags($amountperpage);
        $amountperpage = intval($amountperpage);    
        if($amountperpage === -1) {$amountperpage = 10;}
                    
        $pagenumber = empty($_POST['pagenumber']) ? '1' : sanitize_text_field($_POST['pagenumber']);;
        $pagenumber = strip_tags($pagenumber);
        $pagenumber = intval($pagenumber);    
    
        $myoffset = ($pagenumber - 1) * $amountperpage;
        
        $mysortby = empty($_POST['sortby']) ? '' : sanitize_text_field($_POST['sortby']);
        $mysortby = strip_tags($mysortby);
        $mysortby = $mysortby === '' ? 'id' : $mysortby;
        
        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : sanitize_text_field($_POST['order']);
        $myorder = strip_tags($myorder);
        $myorder = $myorder === '' ? 'asc' : $myorder;
        
        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;                        
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $emailmethods = $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 ($emailmethods as $emailmethod) {
                foreach ($emailmethod as $key => $value) {                
                    $emailmethod[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["emailmethod"] = $emailmethods;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_getLogs', 'dragonecommercereservezyx987_getLogsByAjax');
function dragonecommercereservezyx987_getLogsByAjax() {
    check_ajax_referer('dragonecommercereservezyx987_getLogs', 'dragonecommercereservezyx987_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 json_encode("{}");
        exit();
    }    
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

        $table_name = 'wp_dragonecommercereservezyx987_log';
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getLogList';

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

        $amountperpage = empty($_POST['amountperpage']) ? '10' : sanitize_text_field($_POST['amountperpage']);
        $amountperpage = strip_tags($amountperpage);
        $amountperpage = intval($amountperpage);    
        if($amountperpage === -1) {$amountperpage = 10;}
                    
        $pagenumber = empty($_POST['pagenumber']) ? '1' : sanitize_text_field($_POST['pagenumber']);;
        $pagenumber = strip_tags($pagenumber);
        $pagenumber = intval($pagenumber);    
    
        $myoffset = ($pagenumber - 1) * $amountperpage;
        
        $mysortby = empty($_POST['sortby']) ? '' : sanitize_text_field($_POST['sortby']);
        $mysortby = strip_tags($mysortby);
        $mysortby = $mysortby === '' ? 'id' : $mysortby;
        
        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : sanitize_text_field($_POST['order']);
        $myorder = strip_tags($myorder);
        $myorder = $myorder === '' ? 'desc' : $myorder;
        
        $searchwords = empty($_POST['searchwords']) ? '' : sanitize_text_field($_POST['searchwords']);
        $searchwords = strip_tags($searchwords);

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

        $processname_temp = (!isset($_POST['processname'])) ? '' : sanitize_text_field($_POST['processname']);
        $processname = strip_tags($processname_temp);
        if($processname === '-1') {$processname = "";}
        
        $userid_temp = (!isset($_POST['userid'])) ? '0' : sanitize_text_field($_POST['userid']);
        $userid_temp = strip_tags($userid_temp);
        $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 json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_getSlideshows', 'dragonecommercereservezyx987_getSlideshowsByAjax');
function dragonecommercereservezyx987_getSlideshowsByAjax() {
    check_ajax_referer('dragonecommercereservezyx987_getSlideshows', 'dragonecommercereservezyx987_hidden_security_getslideshows');
    $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 json_encode("{}");
        exit();
    }    
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_slideshow';
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getSlideshowList';

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

        $amountperpage = empty($_POST['amountperpage']) ? '10' : sanitize_text_field($_POST['amountperpage']);
        $amountperpage = strip_tags($amountperpage);
        $amountperpage = intval($amountperpage);    
        if($amountperpage === -1) {$amountperpage = 10;}
                    
        $pagenumber = empty($_POST['pagenumber']) ? '1' : sanitize_text_field($_POST['pagenumber']);;
        $pagenumber = strip_tags($pagenumber);
        $pagenumber = intval($pagenumber);    
    
        $myoffset = ($pagenumber - 1) * $amountperpage;
        
        $mysortby = empty($_POST['sortby']) ? '' : sanitize_text_field($_POST['sortby']);
        $mysortby = strip_tags($mysortby);
        $mysortby = $mysortby === '' ? 'id' : $mysortby;
        
        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : sanitize_text_field($_POST['order']);
        $myorder = strip_tags($myorder);
        $myorder = $myorder === '' ? 'asc' : $myorder;
        
        $searchwords = empty($_POST['searchwords']) ? '' : sanitize_text_field($_POST['searchwords']);
        $searchwords = strip_tags($searchwords);
        $searchdescription = empty($_POST['searchdescription']) ? '' : sanitize_text_field($_POST['searchdescription']);
        $searchdescription = strip_tags($searchdescription);
            
        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[] = &$searchdescription;        
            
            $types .= 'i'; //0: inactive, 1: active, -1: both
            $parameterArray[] = &$slideshowstatus;                            
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $slideshows = $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 ($slideshows as $slideshow) {
                foreach ($slideshow as $key => $value) {                
                    $slideshow[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["slideshow"] = $slideshows;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_getDiscounts', 'dragonecommercereservezyx987_getDiscountsByAjax');
function dragonecommercereservezyx987_getDiscountsByAjax() {
    check_ajax_referer('dragonecommercereservezyx987_getDiscounts', 'dragonecommercereservezyx987_hidden_security_getdiscounts');
    $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 json_encode("{}");
        exit();
    }    
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_propertyvalue';
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getDiscountList';

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

        $amountperpage = empty($_POST['amountperpage']) ? '10' : sanitize_text_field($_POST['amountperpage']);
        $amountperpage = strip_tags($amountperpage);
        $amountperpage = intval($amountperpage);    
        if($amountperpage === -1) {$amountperpage = 10;}
                    
        $pagenumber = empty($_POST['pagenumber']) ? '1' : sanitize_text_field($_POST['pagenumber']);;
        $pagenumber = strip_tags($pagenumber);
        $pagenumber = intval($pagenumber);    
    
        $myoffset = ($pagenumber - 1) * $amountperpage;
        
        $mysortby = empty($_POST['sortby']) ? '' : sanitize_text_field($_POST['sortby']);
        $mysortby = strip_tags($mysortby);
        $mysortby = $mysortby === '' ? 'id' : $mysortby;
        
        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : sanitize_text_field($_POST['order']);
        $myorder = strip_tags($myorder);
        $myorder = $myorder === '' ? 'asc' : $myorder;
        
        $searchwords = empty($_POST['searchwords']) ? '' : sanitize_text_field($_POST['searchwords']);
        $searchwords = strip_tags($searchwords);
        $searchshownname = empty($_POST['searchshownname']) ? '' : sanitize_text_field($_POST['searchshownname']);
        $searchshownname = strip_tags($searchshownname);            
        $searchdescription = empty($_POST['searchdescription']) ? '' : sanitize_text_field($_POST['searchdescription']);
        $searchdescription = strip_tags($searchdescription);        
        
        $fromdate = empty($_POST['fromdate']) ? '1000-01-01 00:00:00' : sanitize_text_field($_POST['fromdate']);
        $fromdate = strip_tags($fromdate);            
        $todate = empty($_POST['todate']) ? '9999-12-31 23:59:59' : sanitize_text_field($_POST['todate']);
        $todate = strip_tags($todate);

        if(dragonecommercereservezyx987_validateDate($fromdate) && dragonecommercereservezyx987_validateDate($todate)) {
            if($fromdate > $todate) {
                echo "Error. From date is later than to date.";exit();                        
            }
        }else{
            echo "Error. Please enter a valid date.";exit();    
        }
        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[] = &$searchshownname;
            
            $types .= 's';
            $parameterArray[] = &$searchdescription;                

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

            $types .= 's';
            $parameterArray[] = &$todate;                
            
            $types .= 'i'; //0: inactive, 1: active, -1: both
            $parameterArray[] = &$discountstatus;                            
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $discounts = $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 ($discounts as $discount) {
                foreach ($discount as $key => $value) {
                    $discount[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["discount"] = $discounts;
            $result["total"] = $total;
            
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_getCoupons', 'dragonecommercereservezyx987_getCouponsByAjax');
function dragonecommercereservezyx987_getCouponsByAjax() {
    check_ajax_referer('dragonecommercereservezyx987_getCoupons', 'dragonecommercereservezyx987_hidden_security_getcoupons');
    $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 json_encode("{}");
        exit();
    }    
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_propertyvalue';
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getCouponList';

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

        $amountperpage = empty($_POST['amountperpage']) ? '10' : sanitize_text_field($_POST['amountperpage']);
        $amountperpage = strip_tags($amountperpage);
        $amountperpage = intval($amountperpage);    
        if($amountperpage === -1) {$amountperpage = 10;}
                    
        $pagenumber = empty($_POST['pagenumber']) ? '1' : sanitize_text_field($_POST['pagenumber']);;
        $pagenumber = strip_tags($pagenumber);
        $pagenumber = intval($pagenumber);    
        
        $myoffset = ($pagenumber - 1) * $amountperpage;
        
        $mysortby = empty($_POST['sortby']) ? '' : sanitize_text_field($_POST['sortby']);
        $mysortby = strip_tags($mysortby);
        $mysortby = $mysortby === '' ? 'id' : $mysortby;
        
        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : sanitize_text_field($_POST['order']);
        $myorder = strip_tags($myorder);
        $myorder = $myorder === '' ? 'asc' : $myorder;
        
        $searchwords = empty($_POST['searchwords']) ? '' : sanitize_text_field($_POST['searchwords']);
        $searchwords = strip_tags($searchwords);
        $searchshownname = empty($_POST['searchshownname']) ? '' : sanitize_text_field($_POST['searchshownname']);
        $searchshownname = strip_tags($searchshownname);            
        $searchdescription = empty($_POST['searchdescription']) ? '' : sanitize_text_field($_POST['searchdescription']);
        $searchdescription = strip_tags($searchdescription);    
        
        $fromdate = empty($_POST['fromdate']) ? '1000-01-01 00:00:00' : sanitize_text_field($_POST['fromdate']);
        $fromdate = strip_tags($fromdate);            
        $todate = empty($_POST['todate']) ? '9999-12-31 23:59:59' : sanitize_text_field($_POST['todate']);
        $todate = strip_tags($todate);

        if(dragonecommercereservezyx987_validateDate($fromdate) && dragonecommercereservezyx987_validateDate($todate)) {
            if($fromdate > $todate) {
                echo "Error. From date is later than to date.";exit();                        
            }
        }else{
            echo "Error. Please enter a valid date.";exit();    
        }            
        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[] = &$searchshownname;
            
            $types .= 's';
            $parameterArray[] = &$searchdescription;                

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

            $types .= 's';
            $parameterArray[] = &$todate;                
            
            $types .= 'i'; //0: inactive, 1: active, -1: both
            $parameterArray[] = &$couponstatus;                            
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $coupons = $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 ($coupons as $coupon) {
                foreach ($coupon as $key => $value) {                
                    $coupon[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["coupon"] = $coupons;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_getPropertyvalues', 'dragonecommercereservezyx987_getPropertyvaluesByAjax');
function dragonecommercereservezyx987_getPropertyvaluesByAjax() {
    check_ajax_referer('dragonecommercereservezyx987_getPropertyvalues', 'dragonecommercereservezyx987_hidden_security_getpropertyvalues');
    $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 json_encode("{}");
        exit();
    }    
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_propertyvalue';
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getPropertyvalueList';

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

        $propertyvaluepropertyid_temp = (!isset($_POST['propertyvaluepropertyid'])) ? '1' : sanitize_text_field($_POST['propertyvaluepropertyid']);
        $propertyvaluepropertyid_temp = strip_tags($propertyvaluepropertyid_temp);
        $propertyvaluepropertyid = intval($propertyvaluepropertyid_temp);
        
        $amountperpage_temp = empty($_POST['amountperpage']) ? '10' : sanitize_text_field($_POST['amountperpage']);
        $amountperpage_temp = strip_tags($amountperpage_temp);
        $amountperpage = intval($amountperpage_temp);    
        if($amountperpage === -1) {$amountperpage = 10;}
                    
        $pagenumber_temp = empty($_POST['pagenumber']) ? '1' : sanitize_text_field($_POST['pagenumber']);;
        $pagenumber_temp = strip_tags($pagenumber_temp);
        $pagenumber = intval($pagenumber_temp);    
    
        $myoffset = ($pagenumber - 1) * $amountperpage;
        
        $mysortby = empty($_POST['sortby']) ? '' : sanitize_text_field($_POST['sortby']);
        $mysortby = strip_tags($mysortby);
        $mysortby = $mysortby === '' ? 'id' : $mysortby;
        
        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : sanitize_text_field($_POST['order']);
        $myorder = strip_tags($myorder);
        $myorder = $myorder === '' ? 'asc' : $myorder;
        
        $searchwords = empty($_POST['searchwords']) ? '' : sanitize_text_field($_POST['searchwords']);
        $searchwords = strip_tags($searchwords);
        $searchshownname = empty($_POST['searchshownname']) ? '' : sanitize_text_field($_POST['searchshownname']);
        $searchshownname = strip_tags($searchshownname);            
        $searchdescription = empty($_POST['searchdescription']) ? '' : sanitize_text_field($_POST['searchdescription']);
        $searchdescription = strip_tags($searchdescription);    
        
        $fromdate = empty($_POST['fromdate']) ? '1000-01-01 00:00:00' : sanitize_text_field($_POST['fromdate']);
        $fromdate = strip_tags($fromdate);            
        $todate = empty($_POST['todate']) ? '9999-12-31 23:59:59' : sanitize_text_field($_POST['todate']);
        $todate = strip_tags($todate);

        if(dragonecommercereservezyx987_validateDate($fromdate) && dragonecommercereservezyx987_validateDate($todate)) {
            if($fromdate > $todate) {
                echo "Error. From date is later than to date.";exit();                        
            }
        }else{
            echo "Error. Please enter a valid date.";exit();    
        }            
        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[] = &$searchshownname;
            
            $types .= 's';
            $parameterArray[] = &$searchdescription;                

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

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

            $types .= 'i'; 
            $parameterArray[] = &$propertyvaluepropertyid;
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $propertyvalues = $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 ($propertyvalues as $propertyvalue) {
                foreach ($propertyvalue as $key => $value) {                
                    $propertyvalue[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["propertyvalue"] = $propertyvalues;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_getHandlings', 'dragonecommercereservezyx987_getHandlingsByAjax');
function dragonecommercereservezyx987_getHandlingsByAjax() {
    check_ajax_referer('dragonecommercereservezyx987_getHandlings', 'dragonecommercereservezyx987_hidden_security_gethandlings');
    $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 json_encode("{}");
        exit();
    }    
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_propertyvalue';
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getHandlingList';

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

        $amountperpage = empty($_POST['amountperpage']) ? '10' : sanitize_text_field($_POST['amountperpage']);
        $amountperpage = strip_tags($amountperpage);
        $amountperpage = intval($amountperpage);    
        if($amountperpage === -1) {$amountperpage = 10;}
                    
        $pagenumber = empty($_POST['pagenumber']) ? '1' : sanitize_text_field($_POST['pagenumber']);;
        $pagenumber = strip_tags($pagenumber);
        $pagenumber = intval($pagenumber);    
    
        $myoffset = ($pagenumber - 1) * $amountperpage;
        
        $mysortby = empty($_POST['sortby']) ? '' : sanitize_text_field($_POST['sortby']);
        $mysortby = strip_tags($mysortby);
        $mysortby = $mysortby === '' ? 'id' : $mysortby;
        
        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : sanitize_text_field($_POST['order']);
        $myorder = strip_tags($myorder);
        $myorder = $myorder === '' ? 'asc' : $myorder;
        
        $searchwords = empty($_POST['searchwords']) ? '' : sanitize_text_field($_POST['searchwords']);
        $searchwords = strip_tags($searchwords);
        $searchshownname = empty($_POST['searchshownname']) ? '' : sanitize_text_field($_POST['searchshownname']);
        $searchshownname = strip_tags($searchshownname);            
        $searchdescription = empty($_POST['searchdescription']) ? '' : sanitize_text_field($_POST['searchdescription']);
        $searchdescription = strip_tags($searchdescription);    
        
        $fromdate = empty($_POST['fromdate']) ? '1000-01-01 00:00:00' : sanitize_text_field($_POST['fromdate']);
        $fromdate = strip_tags($fromdate);            
        $todate = empty($_POST['todate']) ? '9999-12-31 23:59:59' : sanitize_text_field($_POST['todate']);
        $todate = strip_tags($todate);
    
        if(dragonecommercereservezyx987_validateDate($fromdate) && dragonecommercereservezyx987_validateDate($todate)) {
            if($fromdate > $todate) {
                echo "Error. From date is later than to date.";exit();                        
            }
        }else{
            echo "Error. Please enter a valid date.";exit();    
        }            
        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[] = &$searchshownname;
            
            $types .= 's';
            $parameterArray[] = &$searchdescription;                

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

            $types .= 's';
            $parameterArray[] = &$todate;                
            
            $types .= 'i'; //0: inactive, 1: active, -1: both
            $parameterArray[] = &$handlingstatus;                            
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $handlings = $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 ($handlings as $handling) {
                foreach ($handling as $key => $value) {                
                    $handling[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["handling"] = $handlings;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_getShippings', 'dragonecommercereservezyx987_getShippingsByAjax');
function dragonecommercereservezyx987_getShippingsByAjax() {
    check_ajax_referer('dragonecommercereservezyx987_getShippings', 'dragonecommercereservezyx987_hidden_security_getshippings');
    $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 json_encode("{}");
        exit();
    }    
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_propertyvalue';
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getShippingList';

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

        $amountperpage = empty($_POST['amountperpage']) ? '10' : sanitize_text_field($_POST['amountperpage']);
        $amountperpage = strip_tags($amountperpage);
        $amountperpage = intval($amountperpage);    
        if($amountperpage === -1) {$amountperpage = 10;}
                    
        $pagenumber = empty($_POST['pagenumber']) ? '1' : sanitize_text_field($_POST['pagenumber']);;
        $pagenumber = strip_tags($pagenumber);
        $pagenumber = intval($pagenumber);    
    
        $myoffset = ($pagenumber - 1) * $amountperpage;
        
        $mysortby = empty($_POST['sortby']) ? '' : sanitize_text_field($_POST['sortby']);
        $mysortby = strip_tags($mysortby);
        $mysortby = $mysortby === '' ? 'id' : $mysortby;
        
        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : sanitize_text_field($_POST['order']);
        $myorder = strip_tags($myorder);
        $myorder = $myorder === '' ? 'asc' : $myorder;
        
        $searchwords = empty($_POST['searchwords']) ? '' : sanitize_text_field($_POST['searchwords']);
        $searchwords = strip_tags($searchwords);
        $searchshownname = empty($_POST['searchshownname']) ? '' : sanitize_text_field($_POST['searchshownname']);
        $searchshownname = strip_tags($searchshownname);            
        $searchdescription = empty($_POST['searchdescription']) ? '' : sanitize_text_field($_POST['searchdescription']);
        $searchdescription = strip_tags($searchdescription);

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

        if(dragonecommercereservezyx987_validateDate($fromdate) && dragonecommercereservezyx987_validateDate($todate)) {
            if($fromdate > $todate) {
                echo "Error. From date is later than to date.";exit();                        
            }
        }else{
            echo "Error. Please enter a valid date.";exit();    
        }
        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[] = &$searchshownname;
            
            $types .= 's';
            $parameterArray[] = &$searchdescription;                

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

            $types .= 's';
            $parameterArray[] = &$todate;                
            
            $types .= 'i'; //0: inactive, 1: active, -1: both
            $parameterArray[] = &$shippingstatus;                            
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $shippings = $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 ($shippings as $shipping) {
                foreach ($shipping as $key => $value) {                
                    $shipping[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["shipping"] = $shippings;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_getTaxes', 'dragonecommercereservezyx987_getTaxesByAjax');
function dragonecommercereservezyx987_getTaxesByAjax() {
    check_ajax_referer('dragonecommercereservezyx987_getTaxes', 'dragonecommercereservezyx987_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 json_encode("{}");
        exit();
    }
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_propertyvalue';
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getTaxList';

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

        $amountperpage = empty($_POST['amountperpage']) ? '10' : sanitize_text_field($_POST['amountperpage']);
        $amountperpage = strip_tags($amountperpage);
        $amountperpage = intval($amountperpage);    
        if($amountperpage === -1) {$amountperpage = 10;}
                    
        $pagenumber = empty($_POST['pagenumber']) ? '1' : sanitize_text_field($_POST['pagenumber']);;
        $pagenumber = strip_tags($pagenumber);
        $pagenumber = intval($pagenumber);    
    
        $myoffset = ($pagenumber - 1) * $amountperpage;
        
        $mysortby = empty($_POST['sortby']) ? '' : sanitize_text_field($_POST['sortby']);
        $mysortby = strip_tags($mysortby);
        $mysortby = $mysortby === '' ? 'id' : $mysortby;
        
        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : sanitize_text_field($_POST['order']);
        $myorder = strip_tags($myorder);
        $myorder = $myorder === '' ? 'asc' : $myorder;
        
        $searchwords = empty($_POST['searchwords']) ? '' : sanitize_text_field($_POST['searchwords']);
        $searchwords = strip_tags($searchwords);
        $searchshownname = empty($_POST['searchshownname']) ? '' : sanitize_text_field($_POST['searchshownname']);
        $searchshownname = strip_tags($searchshownname);            
        $searchdescription = empty($_POST['searchdescription']) ? '' : sanitize_text_field($_POST['searchdescription']);
        $searchdescription = strip_tags($searchdescription);        
        
        $fromdate = empty($_POST['fromdate']) ? '1000-01-01 00:00:00' : sanitize_text_field($_POST['fromdate']);
        $fromdate = strip_tags($fromdate);            
        $todate = empty($_POST['todate']) ? '9999-12-31 23:59:59' : sanitize_text_field($_POST['todate']);
        $todate = strip_tags($todate);

        if(dragonecommercereservezyx987_validateDate($fromdate) && dragonecommercereservezyx987_validateDate($todate)) {
            if($fromdate > $todate) {
                echo "Error. From date is later than to date.";exit();                        
            }
        }else{
            echo "Error. Please enter a valid date.";exit();    
        }
        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[] = &$searchshownname;
            
            $types .= 's';
            $parameterArray[] = &$searchdescription;                

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

            $types .= 's';
            $parameterArray[] = &$todate;                
            
            $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 json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_getProperties', 'dragonecommercereservezyx987_getPropertiesByAjax');
function dragonecommercereservezyx987_getPropertiesByAjax() {
    check_ajax_referer('dragonecommercereservezyx987_getProperties', 'dragonecommercereservezyx987_hidden_security_getproperties');
    $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 json_encode("{}");
        exit();
    }    
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_property';
        $table_name2 = 'wp_dragonecommercereservezyx987_chargetype';
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getPropertyList';

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

        $amountperpage = empty($_POST['amountperpage']) ? '10' : sanitize_text_field($_POST['amountperpage']);
        $amountperpage = strip_tags($amountperpage);
        $amountperpage = intval($amountperpage);    
        if($amountperpage === -1) {$amountperpage = 10;}
                    
        $pagenumber = empty($_POST['pagenumber']) ? '1' : sanitize_text_field($_POST['pagenumber']);;
        $pagenumber = strip_tags($pagenumber);
        $pagenumber = intval($pagenumber);    
    
        $myoffset = ($pagenumber - 1) * $amountperpage;
        
        $mysortby = empty($_POST['sortby']) ? '' : sanitize_text_field($_POST['sortby']);
        $mysortby = strip_tags($mysortby);
        $mysortby = $mysortby === '' ? 'id' : $mysortby;
        
        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : sanitize_text_field($_POST['order']);
        $myorder = strip_tags($myorder);
        $myorder = $myorder === '' ? 'asc' : $myorder;
        
        $searchwords = empty($_POST['searchwords']) ? '' : sanitize_text_field($_POST['searchwords']);
        $searchwords = strip_tags($searchwords);
        $chargetypeid = empty($_POST['chargetypeid']) ? '0' : sanitize_text_field($_POST['chargetypeid']);
        $chargetypeid = strip_tags($chargetypeid);
        $chargetypeid = intval($chargetypeid);
        if($chargetypeid === -1) {$chargetypeid = 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 .= 'i';
            $parameterArray[] = &$chargetypeid;            
            
            $types .= 'i'; //0: inactive, 1: active, -1: both
            $parameterArray[] = &$propertystatus;                            
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $properties = $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($properties as $property) {
                foreach($property as $key => $value) {                
                    $property[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["property"] = $properties;
            $result["total"] = $total;                
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_getGroupProperties', 'dragonecommercereservezyx987_getGroupPropertiesByAjax');
function dragonecommercereservezyx987_getGroupPropertiesByAjax() {
    check_ajax_referer('dragonecommercereservezyx987_getGroupProperties', 'dragonecommercereservezyx987_hidden_security_getgroupproperties');
    $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 json_encode("{}");
        exit();
    }    
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $temp = '';
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_grouop_property';
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getGroupPropertyList';

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

        $amountperpage = empty($_POST['amountperpage']) ? '10' : sanitize_text_field($_POST['amountperpage']);
        $amountperpage = strip_tags($amountperpage);
        $amountperpage = intval($amountperpage);    
        if($amountperpage === -1) {$amountperpage = 10;}
                    
        $pagenumber = empty($_POST['pagenumber']) ? '1' : sanitize_text_field($_POST['pagenumber']);;
        $pagenumber = strip_tags($pagenumber);
        $pagenumber = intval($pagenumber);    
    
        $myoffset = ($pagenumber - 1) * $amountperpage;
        
        $mysortby = empty($_POST['sortby']) ? '' : sanitize_text_field($_POST['sortby']);
        $mysortby = strip_tags($mysortby);
        $mysortby = $mysortby === '' ? 'id' : $mysortby;
        
        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : sanitize_text_field($_POST['order']);
        $myorder = strip_tags($myorder);
        $myorder = $myorder === '' ? 'asc' : $myorder;
        
        $groupid = empty($_POST['groupid']) ? '0' : sanitize_text_field($_POST['groupid']);
        $groupid = strip_tags($groupid);
        $groupid = intval($groupid);
        if($groupid === -1) {$groupid = 0;}
        
        $propertyid = empty($_POST['propertyid']) ? '0' : sanitize_text_field($_POST['propertyid']);
        $propertyid = strip_tags($propertyid);
        $propertyid = intval($propertyid);
        if($propertyid === -1) {$propertyid = 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 .= 'i';
            $parameterArray[] = &$groupid;

            $types .= 'i';
            $parameterArray[] = &$propertyid;            
            
            $types .= 'i'; //0: inactive, 1: active, -1: both
            $parameterArray[] = &$grouppropertystatus;                            
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $groupproperties = $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($groupproperties as $groupproperty) {
                foreach($groupproperty as $key => $value) {                
                    $groupproperty[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["groupproperty"] = $groupproperties;
            $result["total"] = $total;                
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_getSettings', 'dragonecommercereservezyx987_getSettings');
function dragonecommercereservezyx987_getSettings() {
    check_ajax_referer('dragonecommercereservezyx987_getSettings', 'dragonecommercereservezyx987_hidden_security_getsettings');
    $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 json_encode("{}");
        exit();
    }    
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $startDate = empty($_POST['start']) ? '' : sanitize_text_field($_POST['start']);
        $startDate = strip_tags($startDate);
        $startDate = sanitize_text_field(str_ireplace("T"," ",$startDate));
        $startDate = sanitize_text_field(str_ireplace("Z","",$startDate));
        
        $endDate = empty($_POST['end']) ? '' : sanitize_text_field($_POST['end']);
        $endDate = strip_tags($endDate);
        $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_dragonecommercereservezyx987_setting';
        $productstatus = 1;            
        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();
            $settings = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            $counter = 0;
            foreach ($settings as $setting) {
                $found = false;
                foreach ($setting as $key => $value) {                
                    $setting[$key] = $value === null ? '' : deslash($value);
                    if($key === 'name' && $value === 'DBBACKUP_DETAILS') {
                        $found = true;
                    }// elseif($key === 'name' && $value === 'COMPANY_TIMEZONE' && $settings[$counter]['value'] !== null && $settings[$counter]['value'] !== '') {
                    //    date_default_timezone_set($settings[$counter]['value']);
                    //    $timezone = $settings[$counter]['value'];
                    //}
                }
                if($found) {
                    if($setting['value'] !== null && $setting['value'] !== '') {
                        $settings[$counter]['value'] = 'HAS VALUE';
                    }                    
                }
                $counter++;
            }
            $result = [];
            $result["total"] = count($settings);
            $result["setting"] = $settings;
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_editSettingvalue', 'dragonecommercereservezyx987_editSettingvalue');
function dragonecommercereservezyx987_editSettingvalue() {
    check_ajax_referer('dragonecommercereservezyx987_editSettingvalue', 'dragonecommercereservezyx987_hidden_security_editsettingvalue');
    $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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $settingid_temp = empty($_POST['id']) ? 0 : sanitize_text_field($_POST['id']);
        $settingid_temp = strip_tags($settingid_temp);
        $settingid = intval($settingid_temp);
        
        if($settingid <= 0 || $_POST['value'] === null) {echo "Invalid id.";exit();}    

        $settingname_temp = $_POST['name'] === null ? '' : sanitize_text_field($_POST['name']);
        $settingname_temp = strip_tags($settingname_temp);
        $settingname = $settingname_temp;        

        $settingvalue_temp = $_POST['value'] === null ? '' : sanitize_text_field($_POST['value']);
        $settingvalue_temp = strip_tags($settingvalue_temp);
        $settingvalue = $settingvalue_temp;

        $settingvalue2 = "";
        //if($settingname === 'COMPANY_TIMEZONE' && ($settingvalue === '-1' || $settingvalue === '')) {
        //    echo "Please choose a timezone.";exit();
        //}
        //if($settingname === 'COMPANY_TIMEZONE') {
        //    $temp = explode("|", $settingvalue);
        //    $settingvalue = $temp[0];
        //    $settingvalue2 = $temp[1];
        //}    
        if($settingvalue2 === "" || $settingvalue2 === null) {
            $settingvalue2 = "+00:00";
        }
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_setting';
        $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[] = &$settingvalue;
            
            $types .= 'i';
            $parameterArray[] = &$settingid;                                
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            if($wpdb->dbh->errno > 0 || $stmt->errno > 0) {
                $finalresult .= 'Edit setting id: ' . $settingid . ' failed. ';
            }            
            $stmt->close();
            
            /*if($settingname === 'COMPANY_TIMEZONE' && $settingvalue2 !== '') {
                $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[] = &$settingvalue2;                            
                
                $parameterArray[0] = $types;
                call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                $stmt->execute();
                if($wpdb->dbh->errno > 0 || $stmt->errno > 0) {
                    $finalresult .= 'Edit setting 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_dragonecommercereservezyx987_getDiscounts', 'dragonecommercereservezyx987_getDiscounts');
function dragonecommercereservezyx987_getDiscounts() {
    check_ajax_referer('dragonecommercereservezyx987_getDiscounts', 'dragonecommercereservezyx987_hidden_security_getdiscounts');
    $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 json_encode("{}");    
        exit();
    }
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $startDate = empty($_POST['start']) ? '' : sanitize_text_field($_POST['start']);
        $startDate = strip_tags($startDate);
        $startDate = sanitize_text_field(str_ireplace("T"," ",$startDate));
        $startDate = sanitize_text_field(str_ireplace("Z","",$startDate));
        
        $endDate = empty($_POST['end']) ? '' : sanitize_text_field($_POST['end']);
        $endDate = strip_tags($endDate);
        $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_dragonecommercereservezyx987_setting';
        $table_name2 = 'wp_dragonecommercereservezyx987_group';
        $table_name3 = 'wp_dragonecommercereservezyx987_group_property';                                                                        
        $table_name4 = 'wp_dragonecommercereservezyx987_propertyvalue';
        
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $query = "SELECT d.* FROM $table_name4 d WHERE d.propertyid = (SELECT c.propertyid FROM $table_name3 c WHERE c.groupid = (SELECT b.id FROM $table_name2 b WHERE b.groupcategoryid = (SELECT CAST(a.value AS UNSIGNED) FROM $table_name a WHERE a.name = 'GROUP_CATEGORY_ID_FOR_DISCOUNT' and a.status = 1 LIMIT 1)) LIMIT 1);";
            $stmt = $wpdb->dbh->prepare($query);

            $stmt->execute();
            $myresult = $stmt->get_result();
            $discounts = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            foreach($discounts as $discount) {
                foreach($discount as $key => $value) {                
                    $discount[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["discount"] = $discounts;
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_approveUser', 'dragonecommercereservezyx987_approveUser');
function dragonecommercereservezyx987_approveUser() {
    check_ajax_referer('dragonecommercereservezyx987_approveUser', 'dragonecommercereservezyx987_hidden_security_approveuser');
    $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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $userid_temp = empty($_POST['id']) ? 0 : sanitize_text_field($_POST['id']);
        $userid_temp = strip_tags($userid_temp);
        $userid = intval($userid_temp);
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_user_status';
        $table_name2 = 'wp_dragonecommercereservezyx987_emailmethod';
        $table_name3 = 'wp_dragonecommercereservezyx987_setting';
        $finalresult = 'Success';
            
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $query = "UPDATE $table_name SET admin_approved = 1, updatetimeutc = UTC_TIMESTAMP() WHERE userid = ? ";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');
            
            $types .= 'i';
            $parameterArray[] = &$userid;                                
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            if($wpdb->dbh->errno > 0 || $stmt->errno > 0) {
                $finalresult = 'Approve user failed';
            }                
            $stmt->close();                
            if($finalresult === 'Success') {
                //1. get setting table: EMAIL_METHOD
                $setting_email_method = ''; 
                $mailgun_api_key = "";
                $mailgun_api_url = "";
                $mailgun_domain = "";
                $mailgun_fromname = 'NO-REPLY';    
                $mailchimp_api_key = "";
                $mailchimp_api_url = "";
                $mailchimp_fromemail = "";
                $mailchimp_fromname = "";
                $sendgrid_api_key = "";
                $sendgrid_api_url = "";
                $sendgrid_fromemail = "";
                $sendgrid_fromname = "";
                
                $query = "SELECT a.name, b.name as 'settingname', b.value from $table_name2 a RIGHT JOIN $table_name3 b ON  CAST(b.value AS UNSIGNED) = a.id ";
                $query .= " WHERE b.name IN ('EMAIL_METHOD','MAILGUN_APIKEY','MAILGUN_DOMAIN','MAILGUN_API_URL','MAILGUN_FROMNAME',";
                $query .= " 'MAILCHIMP_APIKEY','MAILCHIMP_API_URL','MAILCHIMP_FROMEMAIL','MAILCHIMP_FROMNAME','SENDGRID_APIKEY','SENDGRID_API_URL','SENDGRID_FROMEMAIL','SENDGRID_FROMNAME') ";
                $result = $wpdb->get_results($query);                
                if(count($result) > 0) {
                    for($i=0; $i<count($result); $i++) {
                        if($result[$i]->settingname === 'EMAIL_METHOD') {
                           $setting_email_method = trim($result[$i]->name);
                        } elseif($result[$i]->settingname === 'MAILGUN_APIKEY') {
                           $mailgun_api_key = $result[$i]->value;
                        } elseif($result[$i]->settingname === 'MAILGUN_API_URL') {
                           $mailgun_api_url = $result[$i]->value;
                        } elseif($result[$i]->settingname === 'MAILGUN_DOMAIN') {
                           $mailgun_domain = $result[$i]->value;
                        } elseif($result[$i]->settingname === 'MAILGUN_FROMNAME') {
                           $mailgun_fromname = $result[$i]->value;
                        } elseif($result[$i]->settingname === 'MAILCHIMP_APIKEY') {
                           $mailchimp_api_key = $result[$i]->value;
                        } elseif($result[$i]->settingname === 'MAILCHIMP_API_URL') {
                           $mailchimp_api_url = $result[$i]->value;
                        } elseif($result[$i]->settingname === 'MAILCHIMP_FROMEMAIL') {
                           $mailchimp_fromemail = $result[$i]->value;
                        } elseif($result[$i]->settingname === 'MAILCHIMP_FROMNAME') {
                           $mailchimp_fromname = $result[$i]->value;
                        } elseif($result[$i]->settingname === 'SENDGRID_APIKEY') {
                           $sendgrid_api_key = $result[$i]->value;
                        } elseif($result[$i]->settingname === 'SENDGRID_API_URL') {
                           $sendgrid_api_url = $result[$i]->value;
                        } elseif($result[$i]->settingname === 'SENDGRID_FROMEMAIL') {
                           $sendgrid_fromemail = $result[$i]->value;
                        } elseif($result[$i]->settingname === 'SENDGRID_FROMNAME') {
                           $sendgrid_fromname = $result[$i]->value;
                        }                                            
                    }
                }
                $result = null;                    
                if(trim($setting_email_method) === '') {
                    $temp = "Email method is not set by website admin. Please contact website admin.";                    
                    dragonecommercereservezyx987_saveToLogTable($temp, 'approve user', 'error', intval($current_user->data->ID));                    
                    echo esc_html($temp);
                    exit();
                }
                if(trim($setting_email_method) === 'Mailgun') {            
                    if($mailgun_api_key === '' || $mailgun_domain === '' || $mailgun_api_url === '') {    
                        $temp = "Mailgun email settings are not set by website admin. Please contact website admin.";
                        dragonecommercereservezyx987_saveToLogTable($temp, 'approve user', 'error', intval($current_user->data->ID));                
                        echo esc_html($temp);
                        exit();
                    }
                    //if mailgun_api_url does not end with /, add /
                    if($mailgun_api_url !== null && $mailgun_api_url !== '' && substr($mailgun_api_url, -1, 1) !== '/') {
                        $mailgun_api_url = $mailgun_api_url . "/";
                    }
                }
                if(trim($setting_email_method) === 'Mailchimp') {            
                    if($mailchimp_api_key === '' || $mailchimp_fromemail === '' || $mailchimp_api_url === '') {    
                        $temp = "Mailchimp email settings are not set by website admin. Please contact website admin.";
                        dragonecommercereservezyx987_saveToLogTable($temp, 'approve user', 'error', intval($current_user->data->ID));                
                        echo esc_html($temp);
                        exit();
                    }
                }            
                if(trim($setting_email_method) === 'SendGrid') {            
                    if($sendgrid_api_key === '' || $sendgrid_fromemail === '' || $sendgrid_api_url === '') {    
                        $temp = "SendGrid email settings are not set by website admin. Please contact website admin.";
                        dragonecommercereservezyx987_saveToLogTable($temp, 'approve user', 'error', intval($current_user->data->ID));                
                        echo esc_html($temp);
                        exit();
                    }
                }
                    
                //2. get user id by email address        
                $table_name = $wpdb->prefix . 'users';
                if($wpdb->use_mysqli) {
                    if($wpdb->dbh->connect_error) {
                        die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
                    }
                    $stmt = $wpdb->dbh->prepare("SELECT user_login, user_email FROM $table_name WHERE ID = ?");
                    $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) {
                        //send email
                        $bccemail = get_option('admin_email');        
                        $finalresult = '';        
                        $username = $result[0]["user_login"];
                        $email = $result[0]["user_email"];                                        
                        $websiteurl = sanitize_text_field($_POST['pluginurl']);
                        $subject = "Your " . $websiteurl . " account is approved by admin";
                        $msg = '<div id="dragonecommercezyx987"><title></title>'
                               .'<style type="text/css">@media screen and (max-width:449px) {#dragonecommercezyx987 .dragonecommercezyx987standalone-paragraph-huge-left .dragonecommercezyx987inner-nested {font-size:26px !important;line-height:30px !important;}}@media screen and (max-width:449px) {'
                               .'#dragonecommercezyx987 .dragonecommercezyx987standalone-paragraph-huge-center .dragonecommercezyx987inner-nested {font-size:26px !important;line-height:30px !important;}}@media screen and (min-width:5px) {#dragonecommercezyx987 body {}#dragonecommercezyx987 .dragonecommercezyx987outer, #dragonecommercezyx987 .dragonecommercezyx987webkit {width:100% !important;min-width:0 !important;max-width:580px !important;}'
                               .'#dragonecommercezyx987 .dragonecommercezyx987section-dark .dragonecommercezyx987inner-nested a {color:#FFFFFF !important;text-decoration:underline !important;}}@media screen and (max-width:449px) {#dragonecommercezyx987 .dragonecommercezyx987contents {font-size:15px !important;line-height:1.625em !important;}#dragonecommercezyx987 .dragonecommercezyx987column, #dragonecommercezyx987 .dragonecommercezyx987image img {max-width:99% !important;}'
                               .'#dragonecommercezyx987 .dragonecommercezyx987three-col .dragonecommercezyx987contents, #dragonecommercezyx987 .dragonecommercezyx987two-col .dragonecommercezyx987contents {font-size:13px !important;}#dragonecommercezyx987 .dragonecommercezyx987three-col .dragonecommercezyx987column img, #dragonecommercezyx987 .dragonecommercezyx987four-col .dragonecommercezyx987column img {max-width:100% !important;}'
                               .'#dragonecommercezyx987 .dragonecommercezyx987one-col .dragonecommercezyx987h6, #dragonecommercezyx987 .dragonecommercezyx987three-col .dragonecommercezyx987h6, #dragonecommercezyx987 .dragonecommercezyx987four-col .dragonecommercezyx987h6, #dragonecommercezyx987 .dragonecommercezyx987two-col .dragonecommercezyx987h6 {font-size:13px !important;margin-bottom:2px !important;}#dragonecommercezyx987 .dragonecommercezyx987h1 {font-size:26px !important;'
                               .'line-height:30px !important;}#dragonecommercezyx987 .dragonecommercezyx987h3 {font-size:26px !important;}}@media screen and (min-width:450px) and (max-width:600px) {#dragonecommercezyx987 .dragonecommercezyx987two-col .dragonecommercezyx987buffered, #dragonecommercezyx987 .dragonecommercezyx987four-col .dragonecommercezyx987buffered, #dragonecommercezyx987 .dragonecommercezyx987three-col .dragonecommercezyx987buffered {padding-left:6px !important;padding-right:6px !important;}'
                               .'#dragonecommercezyx987 .dragonecommercezyx987two-col .dragonecommercezyx987inner, #dragonecommercezyx987 .dragonecommercezyx987four-col .dragonecommercezyx987inner, #dragonecommercezyx987 .dragonecommercezyx987three-col .dragonecommercezyx987inner {}}@media screen and (max-width:449px) {#dragonecommercezyx987 .dragonecommercezyx987buffered {padding-left:0 !important;padding-right:0 !important;}}'
                               .'@media screen and (min-width:450px) and (max-width:655px) {#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987narrow {max-width:40% !important;}#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987wide {max-width:60% !important;}#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987image img {max-width:100% !important;}'
                               .'#dragonecommercezyx987 .dragonecommercezyx987left-round {text-align:left !important;}#dragonecommercezyx987 .dragonecommercezyx987right-round {text-align:right !important;}}@media screen and (max-width:600px) {#dragonecommercezyx987 .dragonecommercezyx987preheader {display:none !important;}#dragonecommercezyx987 .dragonecommercezyx987layout-preheader .dragonecommercezyx987inner {padding:10px !important;}#dragonecommercezyx987 .dragonecommercezyx987webversion {text-align:center !important;}'
                               .'#dragonecommercezyx987 .dragonecommercezyx987inner {padding-left:7% !important;padding-right:7% !important;}#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar p {font-size:13px !important;line-height:1.6em !important;}#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987h3 {font-size:21px !important;}#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987h5 {font-size:13px !important;}'
                               .'#dragonecommercezyx987 .dragonecommercezyx987mob-hide {display:none !important;}}@media screen and (min-width:5px) {#dragonecommercezyx987 img {height:auto !important;max-width:100% !important;}#dragonecommercezyx987 .dragonecommercezyx987hide {display:none !important;}}@media screen and (min-width:656px) {#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987narrow {max-width:31% !important;}'
                               .'#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987wide {max-width:69% !important;}}@media screen and ( _filtered_a )</style>'
                               .'<div><table class="dragonecommercezyx987hide" style="width:580px;min-width:580px;" cellspacing="0" cellpadding="0" border="0"><tbody><tr><td style="font-size:1px;line-height:1px;min-width:580px;" width="580"></td></tr></tbody></table>'
                               .'<div class="dragonecommercezyx987ios9"> &nbsp;<table class="dragonecommercezyx987wrapper dragonecommercezyx987section-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;table-layout:fixed;width:100%;border-collapse:separate;text-align:left;color:#303030;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#087197" align="center"><tbody><tr>'
                               .'<td align="center"><center><div class="dragonecommercezyx987webkit" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;">  <table class="dragonecommercezyx987outer" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                               .'<td> <table class="dragonecommercezyx987layout-preheader" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr class="dragonecommercezyx987one-col">'
                               .'<td class="dragonecommercezyx987inner dragonecommercezyx987contents" style="padding-left:20px;padding-right:20px;padding-bottom:18px;font-size:13px;line-height:14px;padding-top:18px;font-weight:500;color:#303030;">'
                               .'</td></tr></tbody></table></td></tr></tbody></table>'
                               .'</div></center></td></tr></tbody></table><table class="dragonecommercezyx987wrapper dragonecommercezyx987section-" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;table-layout:fixed;width:100%;border-collapse:separate;text-align:left;color:#303030;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF" align="center"><tbody><tr>'
                               .'<td align="center"> <center> <div class="dragonecommercezyx987webkit" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;">  <table class="dragonecommercezyx987outer dragonecommercezyx987boxed-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF"><tbody><tr>'
                               .'<td> <table class="dragonecommercezyx987layout-solologo dragonecommercezyx987boxed dragonecommercezyx987left" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr class="dragonecommercezyx987one-col">'
                               .'<td class="dragonecommercezyx987inner" style="padding-left:18px;padding-right:18px;padding-bottom:18px;padding-top:18px;"> <table width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                               .'<td class="dragonecommercezyx987inner-nested" style="padding-top:12px;padding-bottom:12px;padding-right:0px;padding-left:0px;"> <table class="dragonecommercezyx987contents" style="text-align:left;font-size:16px;line-height:22px;" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                               .'<td class="dragonecommercezyx987logo" style="font-weight:bold;font-size:18px;color:#087197;"><a rel="nofollow noopener noreferrer" target="_blank" href="%%%companyurl%%%" style="text-decoration:none;color:#087197;">%%%companyname%%%</a> </td> </tr></tbody></table>'
                               .'</td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table>'
                               .'</div></center></td></tr></tbody></table><table class="dragonecommercezyx987wrapper dragonecommercezyx987section-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;table-layout:fixed;width:100%;border-collapse:separate;text-align:left;color:#303030;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF" align="center"><tbody><tr>'
                               .'<td align="center"> <center> <div class="dragonecommercezyx987webkit" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;">  <table class="dragonecommercezyx987outer dragonecommercezyx987boxed-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF"><tbody><tr>'
                               .'<td> <table class="dragonecommercezyx987contents dragonecommercezyx987feature-callout-cta dragonecommercezyx987cta" style="color:#303030;" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr class="dragonecommercezyx987two-col">'
                               .'<td class="dragonecommercezyx987inner" style="padding-left:10px;padding-right:10px;"><table class="dragonecommercezyx987contents" style="font-size:16px;line-height:22px;color:#303030;" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                               .'<td class="dragonecommercezyx987feature-callout-bottom" style="padding-top:20px;padding-bottom:20px;padding-right:10px;padding-left:10px;" width="100%" valign="middle"> <table class="dragonecommercezyx987contents" style="font-size:16px;line-height:22px;color:#303030;" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                               .'<td class="dragonecommercezyx987inner-nested" style="padding-top:12px;padding-bottom:12px;padding-right:0px;padding-left:0;" valign="middle">'
                               .'<p class="dragonecommercezyx987h3" style="margin-top:0;margin-bottom:30px !important;font-weight:500;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;font-size:38px;line-height:36px;">%%%title%%%</p>'
                               .'<p>Hi %%%username%%%,</p><p>%%%header%%%</p><p>%%%content%%%</p><p>For more information, check out the <a rel="nofollow noopener noreferrer" target="_blank" href="%%%companyurl%%%">company website</a>.</p><p>Thanks,</p><p>%%%companyname%%%</p></td></tr></tbody></table>'
                               .'<table class="dragonecommercezyx987buttonwrapper dragonecommercezyx987cta-option-standard-tall" style="font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;background-color:#6ca12b;overflow:hidden;border-radius:5px;margin-top:30px;margin-bottom:40px;margin-right:auto;margin-left:0;font-size:16px;line-height:18px;font-weight:bold;" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                               .'<td class="dragonecommercezyx987button">'
                               .'</td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></div></center></td></tr></tbody></table>'
                               .'<table class="dragonecommercezyx987wrapper dragonecommercezyx987section-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;table-layout:fixed;width:100%;border-collapse:separate;text-align:left;color:#303030;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF" align="center"><tbody><tr>'
                               .'<td align="center"> <center> <div class="dragonecommercezyx987webkit" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;">  <table class="dragonecommercezyx987outer" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                               .'<td><div class="dragonecommercezyx987spacer" style="font-size:40px;line-height:40px;display:block;color:#ffffff;text-align:center;">&nbsp;</div> </td> </tr></tbody></table>'
                               .'</div> </center> </td> </tr></tbody></table><table class="dragonecommercezyx987wrapper dragonecommercezyx987section-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;table-layout:fixed;width:100%;border-collapse:separate;text-align:left;color:#303030;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF" align="center"><tbody><tr>'
                               .'<td align="center"> <center> <div class="dragonecommercezyx987webkit" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;">  <table class="dragonecommercezyx987outer dragonecommercezyx987boxed-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF"><tbody><tr>'
                               .'<td><table class="dragonecommercezyx987footer-container" width="100%" cellspacing="0" cellpadding="0" border="0" align="center">'
                               .'<tbody><tr class="dragonecommercezyx987one-col">'
                               .'<td class="dragonecommercezyx987inner dragonecommercezyx987footer-row-top" style="padding-left:20px;padding-right:20px;padding-bottom:0px;padding-top:20px;"> <table class="dragonecommercezyx987fluid" style="border-top-width:2px;border-top-style:solid;border-top-color:#ECECEE;border-bottom-width:2px;border-bottom-style:solid;border-bottom-color:#ECECEE;" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr>'
                               .'<td class="dragonecommercezyx987hh-force-col-center" style="text-align:center;padding-top:25px;padding-bottom:40px;padding-right:0;padding-left:0;" valign="top"> <a rel="nofollow noopener noreferrer" target="_blank" href="%%%companyurl%%%" style="text-decoration:none;color:#959597;">%%%companyname%%%</a> </td> </tr></tbody></table>'
                               .'</td></tr>'
                               .'<tr class="dragonecommercezyx987one-col"><td class="dragonecommercezyx987inner dragonecommercezyx987footer-row-bottom" style="padding-left:20px;padding-right:20px;padding-bottom:0px;padding-top:20px;"> <table class="dragonecommercezyx987fluid" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr>'
                               .'<td class="dragonecommercezyx987hh-force-col-center dragonecommercezyx987footer-text-left" style="text-align:left;padding-top:0px;padding-bottom:40px;padding-right:0;padding-left:0;" valign="top">'
                               .'<p style="display:none;"></p></td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></div></center></td></tr></tbody></table></div></div></div>';
                        $msg = str_replace("%%%companyname%%%", $websiteurl, $msg);                            
                        $msg = str_replace("%%%title%%%", $websiteurl, $msg);
                        
                        $content = '';
                        $msg = str_replace("%%%username%%%", $username, $msg);
                        $msg = str_replace("%%%header%%%", 'Congratulations! Your account is approved by admin. Now you can log on from our ecommerce website %%%companyurl%%%', $msg);
                        $msg = str_replace("%%%content%%%", $content, $msg);
                        $msg = str_replace("%%%companyurl%%%", $websiteurl, $msg);                                                                                    
                        $msg = str_replace("%%%address1%%%", '', $msg);                                                                                    
                        $msg = str_replace("%%%address2%%%", '', $msg);
                                    
                        if($setting_email_method === 'WordPress Email') {
                            $headers = 'From: '. $bccemail . "\r\n" .
                                'Reply-To: ' . $email . "\r\n" .
                                'Bcc: ' . $bccemail . "\r\n";
                             
                            //Validation and send mail
                            add_filter('wp_mail_content_type', function($content_type) {
                                        return 'text/html';
                            });
                            $sent = wp_mail($email, $subject, $msg, $headers);
                            if($sent) {
                            } else {//message wasn't sent
                                $finalresult .= "Admin approval email was not sent to you. Please contact website admin. ";    
                                dragonecommercereservezyx987_saveToLogTable($finalresult, 'approve user', 'error', intval($current_user->data->ID));                                
                            }                                        
                        } elseif($setting_email_method === 'Mailgun') {
                            $data = array(
                                'from' => $mailgun_fromname . ' <mailgun@' . $mailgun_domain . '>',
                                'to' => $email,
                                'bcc' => $bccemail,
                                'subject' => $subject,
                                'html' => $msg,
                                'o:tracking' => false);
                            $auth = base64_encode('api:'.$mailgun_api_key);
                            $args = [
                                'headers' => ['Authorization' => "Basic $auth"],
                                'body' => $data
                            ];
                            $mailgun_result = wp_remote_post($mailgun_api_url . $mailgun_domain . '/messages', $args);    
                            if(is_wp_error($mailgun_result)) {
                                $finalresult .= 'Mailgun result: ' . json_encode($mailgun_result);  //$mailgun_result->get_error_message();
                                $emailsent = 0;
                            }
                        } elseif($setting_email_method === 'Mailchimp') {
                            $data = array(
                                "key"=> $mailchimp_api_key, 
                                "message"=> array(
                                    "from_email"=> $mailchimp_fromemail,
                                    "from_name"=> $mailchimp_fromname,
                                    "subject"=> $subject, 
                                    "html"=> $msg,
                                    "to"=> array(array("email"=> $email, "name"=> "", "type"=>"to"), array("email"=> $bccemail, "name"=> "", "type"=>"bcc")),
                                    "track_opens"=>true,
                                    "track_clicks"=>true
                                )
                            );
                            $data2 = json_encode($data);
                            $auth = base64_encode('authorization: apikey '.$mailchimp_api_key);
                            $args = [
                                'headers' => ['Authorization' => "Basic $auth"],
                                'body' => $data2
                            ];
                            $response = wp_remote_post($mailchimp_api_url, $args);
                            if(is_wp_error($response)) {
                                $finalresult .= 'Mailchimp result: ' . $response->get_error_message();
                                $emailsent = 0;
                            }
                            //$response = json_decode($response0, true);
                            if($response !== null && is_array($response) && count($response) > 0 && isset($response[0]["status"]) && ($response[0]["status"] === 'rejected' || $response[0]["status"] === 'invalid')) {
                                $finalresult .= 'Mailchimp result: ' . json_encode($response);
                                $emailsent = 0;
                            }
                            //error_log("at 10923, mailchimp send email response: " . $response[0]["status"] . ", error: " . $finalresult);                
                        } elseif($setting_email_method === 'SendGrid') {
                            $data = array(
                                "personalizations"=> array(
                                    array(
                                        "to"=> array(array("email"=> $email)),
                                        "bcc"=> array(array("email"=> $bccemail))
                                    )
                                ), 
                                "from"=>array(
                                    "email"=> $sendgrid_fromemail,
                                    "name"=> $sendgrid_fromname
                                ),
                                "subject"=>$subject,
                                "content"=>array(
                                    array(
                                        "type"=> "text/html", 
                                        "value"=> $msg
                                    )                            
                                )
                            );
                            $data2 = json_encode($data);
                            //$auth = base64_encode('api:'.$sendgrid_api_key);
                            $args = array(
                                'headers' => array("Authorization" => "Bearer " . $sendgrid_api_key, "Content-Type" => "application/json"),
                                'body' => $data2
                            );    
                            $response = wp_remote_post($sendgrid_api_url, $args);    
                            if(is_wp_error($response)) {
                                $finalresult .= 'SendGrid result: ' . $response->get_error_message();
                                $emailsent = 0;
                            }
                            //$response = json_decode($response0, true);
                            if($response !== null && $response !== '' && is_array($response) && count($response) > 0 && (!empty($response["body"]["errors"]))) {
                                $finalresult .= 'SendGrid result: ' . json_encode($response);
                                $emailsent = 0;
                            }
                            //error_log("at 10960, sendgrid send email response: " . $response0 . ", error: " . $finalresult);                        
                        }    
                        if($finalresult === '') {                        
                            $finalresult .= "Success";
                        }
                        echo esc_html($finalresult);
                        exit();                        
                    } else {
                        echo "We found " . count($result) . " user(s) for this email address. Please contact website admin.";
                        exit();                            
                    }
                } else {
                    echo 'This website can not use mysqli. Please contact website admin.';
                    exit();
                }                    
            }                
            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_dragonecommercereservezyx987_disapproveUser', 'dragonecommercereservezyx987_disapproveUser');
function dragonecommercereservezyx987_disapproveUser() {
    check_ajax_referer('dragonecommercereservezyx987_disapproveUser', 'dragonecommercereservezyx987_hidden_security_disapproveuser');
    $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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $userid_temp = empty($_POST['id']) ? 0 : sanitize_text_field($_POST['id']);
        $userid_temp = strip_tags($userid_temp);
        $userid = intval($userid_temp);
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_user_status';
        $finalresult = 'Success';            
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $query = "UPDATE $table_name SET admin_approved = 0 , updatetimeutc = UTC_TIMESTAMP() WHERE userid = ? ";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');            
            $types .= 'i';
            $parameterArray[] = &$userid;                                            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            if($wpdb->dbh->errno > 0 || $stmt->errno > 0) {
                $finalresult = 'Disapprove user failed';
            }            
            $stmt->close();            
            if($finalresult === 'Success') {
                $setting_email_method = ''; 
                $mailgun_api_key = "";
                $mailgun_api_url = "";
                $mailgun_domain = "";
                $mailgun_fromname = 'NO-REPLY';    
                $mailchimp_api_key = "";
                $mailchimp_api_url = "";
                $mailchimp_fromemail = "";
                $mailchimp_fromname = "";
                $sendgrid_api_key = "";
                $sendgrid_api_url = "";
                $sendgrid_fromemail = "";
                $sendgrid_fromname = "";                
                $table_name = 'wp_dragonecommercereservezyx987_emailmethod';
                $table_name2 = 'wp_dragonecommercereservezyx987_setting';
                $query = "SELECT a.name, b.name as 'settingname', b.value from $table_name a RIGHT JOIN $table_name2 b ON  CAST(b.value AS UNSIGNED) = a.id ";
                $query .= " WHERE b.name IN ('EMAIL_METHOD','MAILGUN_APIKEY','MAILGUN_DOMAIN','MAILGUN_API_URL','MAILGUN_FROMNAME',";
                $query .= " 'MAILCHIMP_APIKEY','MAILCHIMP_API_URL','MAILCHIMP_FROMEMAIL','MAILCHIMP_FROMNAME','SENDGRID_APIKEY','SENDGRID_API_URL','SENDGRID_FROMEMAIL','SENDGRID_FROMNAME') ";
                $result = $wpdb->get_results($query);                
                if(count($result) > 0) {
                    for($i=0; $i<count($result); $i++) {
                        if($result[$i]->settingname === 'EMAIL_METHOD') {
                           $setting_email_method = trim($result[$i]->name);
                        } elseif($result[$i]->settingname === 'MAILGUN_APIKEY') {
                           $mailgun_api_key = $result[$i]->value;
                        } elseif($result[$i]->settingname === 'MAILGUN_API_URL') {
                           $mailgun_api_url = $result[$i]->value;
                        } elseif($result[$i]->settingname === 'MAILGUN_DOMAIN') {
                           $mailgun_domain = $result[$i]->value;
                        } elseif($result[$i]->settingname === 'MAILGUN_FROMNAME') {
                           $mailgun_fromname = $result[$i]->value;
                        } elseif($result[$i]->settingname === 'MAILCHIMP_APIKEY') {
                           $mailchimp_api_key = $result[$i]->value;
                        } elseif($result[$i]->settingname === 'MAILCHIMP_API_URL') {
                           $mailchimp_api_url = $result[$i]->value;
                        } elseif($result[$i]->settingname === 'MAILCHIMP_FROMEMAIL') {
                           $mailchimp_fromemail = $result[$i]->value;
                        } elseif($result[$i]->settingname === 'MAILCHIMP_FROMNAME') {
                           $mailchimp_fromname = $result[$i]->value;
                        } elseif($result[$i]->settingname === 'SENDGRID_APIKEY') {
                           $sendgrid_api_key = $result[$i]->value;
                        } elseif($result[$i]->settingname === 'SENDGRID_API_URL') {
                           $sendgrid_api_url = $result[$i]->value;
                        } elseif($result[$i]->settingname === 'SENDGRID_FROMEMAIL') {
                           $sendgrid_fromemail = $result[$i]->value;
                        } elseif($result[$i]->settingname === 'SENDGRID_FROMNAME') {
                           $sendgrid_fromname = $result[$i]->value;
                        }                                            
                    }
                }
                $result = null;                    
                if(trim($setting_email_method) === '') {
                    $temp = "Email method is not set by website admin. Please contact website admin.";
                    dragonecommercereservezyx987_saveToLogTable($temp, 'disapprove user', 'error', intval($current_user->data->ID));                    
                    echo esc_html($temp);
                    exit();
                }
                if(trim($setting_email_method) === 'Mailgun') {            
                    if($mailgun_api_key === '' || $mailgun_domain === '' || $mailgun_api_url === '') {    
                        $temp = "Mailgun email settings are not set by website admin. Please contact website admin.";
                        dragonecommercereservezyx987_saveToLogTable($temp, 'disapprove user', 'error', intval($current_user->data->ID));                
                        echo esc_html($temp);
                        exit();
                    }
                    //if mailgun_api_url does not end with /, add /
                    if($mailgun_api_url !== null && $mailgun_api_url !== '' && substr($mailgun_api_url, -1, 1) !== '/') {
                        $mailgun_api_url = $mailgun_api_url . "/";
                    }
                }
                if(trim($setting_email_method) === 'Mailchimp') {            
                    if($mailchimp_api_key === '' || $mailchimp_fromemail === '' || $mailchimp_api_url === '') {    
                        $temp = "Mailchimp email settings are not set by website admin. Please contact website admin.";
                        dragonecommercereservezyx987_saveToLogTable($temp, 'disapprove user', 'error', intval($current_user->data->ID));                
                        echo esc_html($temp);
                        exit();
                    }
                }            
                if(trim($setting_email_method) === 'SendGrid') {            
                    if($sendgrid_api_key === '' || $sendgrid_fromemail === '' || $sendgrid_api_url === '') {    
                        $temp = "SendGrid email settings are not set by website admin. Please contact website admin.";
                        dragonecommercereservezyx987_saveToLogTable($temp, 'disapprove user', 'error', intval($current_user->data->ID));                
                        echo esc_html($temp);
                        exit();
                    }
                }                    
                //get user id by email address        
                $table_name = $wpdb->prefix . 'users';
                if($wpdb->use_mysqli) {
                    if($wpdb->dbh->connect_error) {
                        die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
                    }
                    $stmt = $wpdb->dbh->prepare("SELECT user_login, user_email FROM $table_name WHERE ID = ?");
                    $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) {
                        //send email
                        $bccemail = get_option('admin_email');        
                        $finalresult = '';        
                        $username = $result[0]["user_login"];
                        $email = $result[0]["user_email"];                                        
                        $websiteurl = sanitize_text_field($_POST['pluginurl']);
                        $subject = "Your " . $websiteurl . " account has been disapproved by admin";
                        $msg = '<div id="dragonecommercezyx987"><title></title>'
                               .'<style type="text/css">@media screen and (max-width:449px) {#dragonecommercezyx987 .dragonecommercezyx987standalone-paragraph-huge-left .dragonecommercezyx987inner-nested {font-size:26px !important;line-height:30px !important;}}@media screen and (max-width:449px) {'
                               .'#dragonecommercezyx987 .dragonecommercezyx987standalone-paragraph-huge-center .dragonecommercezyx987inner-nested {font-size:26px !important;line-height:30px !important;}}@media screen and (min-width:5px) {#dragonecommercezyx987 body {}#dragonecommercezyx987 .dragonecommercezyx987outer, #dragonecommercezyx987 .dragonecommercezyx987webkit {width:100% !important;min-width:0 !important;max-width:580px !important;}'
                               .'#dragonecommercezyx987 .dragonecommercezyx987section-dark .dragonecommercezyx987inner-nested a {color:#FFFFFF !important;text-decoration:underline !important;}}@media screen and (max-width:449px) {#dragonecommercezyx987 .dragonecommercezyx987contents {font-size:15px !important;line-height:1.625em !important;}#dragonecommercezyx987 .dragonecommercezyx987column, #dragonecommercezyx987 .dragonecommercezyx987image img {max-width:99% !important;}'
                               .'#dragonecommercezyx987 .dragonecommercezyx987three-col .dragonecommercezyx987contents, #dragonecommercezyx987 .dragonecommercezyx987two-col .dragonecommercezyx987contents {font-size:13px !important;}#dragonecommercezyx987 .dragonecommercezyx987three-col .dragonecommercezyx987column img, #dragonecommercezyx987 .dragonecommercezyx987four-col .dragonecommercezyx987column img {max-width:100% !important;}'
                               .'#dragonecommercezyx987 .dragonecommercezyx987one-col .dragonecommercezyx987h6, #dragonecommercezyx987 .dragonecommercezyx987three-col .dragonecommercezyx987h6, #dragonecommercezyx987 .dragonecommercezyx987four-col .dragonecommercezyx987h6, #dragonecommercezyx987 .dragonecommercezyx987two-col .dragonecommercezyx987h6 {font-size:13px !important;margin-bottom:2px !important;}#dragonecommercezyx987 .dragonecommercezyx987h1 {font-size:26px !important;'
                               .'line-height:30px !important;}#dragonecommercezyx987 .dragonecommercezyx987h3 {font-size:26px !important;}}@media screen and (min-width:450px) and (max-width:600px) {#dragonecommercezyx987 .dragonecommercezyx987two-col .dragonecommercezyx987buffered, #dragonecommercezyx987 .dragonecommercezyx987four-col .dragonecommercezyx987buffered, #dragonecommercezyx987 .dragonecommercezyx987three-col .dragonecommercezyx987buffered {padding-left:6px !important;padding-right:6px !important;}'
                               .'#dragonecommercezyx987 .dragonecommercezyx987two-col .dragonecommercezyx987inner, #dragonecommercezyx987 .dragonecommercezyx987four-col .dragonecommercezyx987inner, #dragonecommercezyx987 .dragonecommercezyx987three-col .dragonecommercezyx987inner {}}@media screen and (max-width:449px) {#dragonecommercezyx987 .dragonecommercezyx987buffered {padding-left:0 !important;padding-right:0 !important;}}'
                               .'@media screen and (min-width:450px) and (max-width:655px) {#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987narrow {max-width:40% !important;}#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987wide {max-width:60% !important;}#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987image img {max-width:100% !important;}'
                               .'#dragonecommercezyx987 .dragonecommercezyx987left-round {text-align:left !important;}#dragonecommercezyx987 .dragonecommercezyx987right-round {text-align:right !important;}}@media screen and (max-width:600px) {#dragonecommercezyx987 .dragonecommercezyx987preheader {display:none !important;}#dragonecommercezyx987 .dragonecommercezyx987layout-preheader .dragonecommercezyx987inner {padding:10px !important;}#dragonecommercezyx987 .dragonecommercezyx987webversion {text-align:center !important;}'
                               .'#dragonecommercezyx987 .dragonecommercezyx987inner {padding-left:7% !important;padding-right:7% !important;}#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar p {font-size:13px !important;line-height:1.6em !important;}#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987h3 {font-size:21px !important;}#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987h5 {font-size:13px !important;}'
                               .'#dragonecommercezyx987 .dragonecommercezyx987mob-hide {display:none !important;}}@media screen and (min-width:5px) {#dragonecommercezyx987 img {height:auto !important;max-width:100% !important;}#dragonecommercezyx987 .dragonecommercezyx987hide {display:none !important;}}@media screen and (min-width:656px) {#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987narrow {max-width:31% !important;}'
                               .'#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987wide {max-width:69% !important;}}@media screen and ( _filtered_a )</style>'
                               .'<div><table class="dragonecommercezyx987hide" style="width:580px;min-width:580px;" cellspacing="0" cellpadding="0" border="0"><tbody><tr><td style="font-size:1px;line-height:1px;min-width:580px;" width="580"></td></tr></tbody></table>'
                               .'<div class="dragonecommercezyx987ios9"> &nbsp;<table class="dragonecommercezyx987wrapper dragonecommercezyx987section-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;table-layout:fixed;width:100%;border-collapse:separate;text-align:left;color:#303030;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#087197" align="center"><tbody><tr>'
                               .'<td align="center"><center><div class="dragonecommercezyx987webkit" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;">  <table class="dragonecommercezyx987outer" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                               .'<td> <table class="dragonecommercezyx987layout-preheader" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr class="dragonecommercezyx987one-col">'
                               .'<td class="dragonecommercezyx987inner dragonecommercezyx987contents" style="padding-left:20px;padding-right:20px;padding-bottom:18px;font-size:13px;line-height:14px;padding-top:18px;font-weight:500;color:#303030;">'
                               .'</td></tr></tbody></table></td></tr></tbody></table>'
                               .'</div></center></td></tr></tbody></table><table class="dragonecommercezyx987wrapper dragonecommercezyx987section-" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;table-layout:fixed;width:100%;border-collapse:separate;text-align:left;color:#303030;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF" align="center"><tbody><tr>'
                               .'<td align="center"> <center> <div class="dragonecommercezyx987webkit" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;">  <table class="dragonecommercezyx987outer dragonecommercezyx987boxed-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF"><tbody><tr>'
                               .'<td> <table class="dragonecommercezyx987layout-solologo dragonecommercezyx987boxed dragonecommercezyx987left" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr class="dragonecommercezyx987one-col">'
                               .'<td class="dragonecommercezyx987inner" style="padding-left:18px;padding-right:18px;padding-bottom:18px;padding-top:18px;"> <table width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                               .'<td class="dragonecommercezyx987inner-nested" style="padding-top:12px;padding-bottom:12px;padding-right:0px;padding-left:0px;"> <table class="dragonecommercezyx987contents" style="text-align:left;font-size:16px;line-height:22px;" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                               .'<td class="dragonecommercezyx987logo" style="font-weight:bold;font-size:18px;color:#087197;"><a rel="nofollow noopener noreferrer" target="_blank" href="%%%companyurl%%%" style="text-decoration:none;color:#087197;">%%%companyname%%%</a> </td> </tr></tbody></table>'
                               .'</td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table>'
                               .'</div></center></td></tr></tbody></table><table class="dragonecommercezyx987wrapper dragonecommercezyx987section-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;table-layout:fixed;width:100%;border-collapse:separate;text-align:left;color:#303030;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF" align="center"><tbody><tr>'
                               .'<td align="center"> <center> <div class="dragonecommercezyx987webkit" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;">  <table class="dragonecommercezyx987outer dragonecommercezyx987boxed-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF"><tbody><tr>'
                               .'<td> <table class="dragonecommercezyx987contents dragonecommercezyx987feature-callout-cta dragonecommercezyx987cta" style="color:#303030;" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr class="dragonecommercezyx987two-col">'
                               .'<td class="dragonecommercezyx987inner" style="padding-left:10px;padding-right:10px;"><table class="dragonecommercezyx987contents" style="font-size:16px;line-height:22px;color:#303030;" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                               .'<td class="dragonecommercezyx987feature-callout-bottom" style="padding-top:20px;padding-bottom:20px;padding-right:10px;padding-left:10px;" width="100%" valign="middle"> <table class="dragonecommercezyx987contents" style="font-size:16px;line-height:22px;color:#303030;" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                               .'<td class="dragonecommercezyx987inner-nested" style="padding-top:12px;padding-bottom:12px;padding-right:0px;padding-left:0;" valign="middle">'
                               .'<p class="dragonecommercezyx987h3" style="margin-top:0;margin-bottom:30px !important;font-weight:500;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;font-size:38px;line-height:36px;">%%%title%%%</p>'
                               .'<p>Hi %%%username%%%,</p><p>%%%header%%%</p><p>%%%content%%%</p><p>For more information, check out the <a rel="nofollow noopener noreferrer" target="_blank" href="%%%companyurl%%%">company website</a>.</p><p>Thanks,</p><p>%%%companyname%%%</p></td></tr></tbody></table>'
                               .'<table class="dragonecommercezyx987buttonwrapper dragonecommercezyx987cta-option-standard-tall" style="font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;background-color:#6ca12b;overflow:hidden;border-radius:5px;margin-top:30px;margin-bottom:40px;margin-right:auto;margin-left:0;font-size:16px;line-height:18px;font-weight:bold;" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                               .'<td class="dragonecommercezyx987button">'
                               .'</td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></div></center></td></tr></tbody></table>'
                               .'<table class="dragonecommercezyx987wrapper dragonecommercezyx987section-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;table-layout:fixed;width:100%;border-collapse:separate;text-align:left;color:#303030;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF" align="center"><tbody><tr>'
                               .'<td align="center"> <center> <div class="dragonecommercezyx987webkit" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;">  <table class="dragonecommercezyx987outer" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                               .'<td><div class="dragonecommercezyx987spacer" style="font-size:40px;line-height:40px;display:block;color:#ffffff;text-align:center;">&nbsp;</div> </td> </tr></tbody></table>'
                               .'</div> </center> </td> </tr></tbody></table><table class="dragonecommercezyx987wrapper dragonecommercezyx987section-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;table-layout:fixed;width:100%;border-collapse:separate;text-align:left;color:#303030;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF" align="center"><tbody><tr>'
                               .'<td align="center"> <center> <div class="dragonecommercezyx987webkit" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;">  <table class="dragonecommercezyx987outer dragonecommercezyx987boxed-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF"><tbody><tr>'
                               .'<td><table class="dragonecommercezyx987footer-container" width="100%" cellspacing="0" cellpadding="0" border="0" align="center">'
                               .'<tbody><tr class="dragonecommercezyx987one-col">'
                               .'<td class="dragonecommercezyx987inner dragonecommercezyx987footer-row-top" style="padding-left:20px;padding-right:20px;padding-bottom:0px;padding-top:20px;"> <table class="dragonecommercezyx987fluid" style="border-top-width:2px;border-top-style:solid;border-top-color:#ECECEE;border-bottom-width:2px;border-bottom-style:solid;border-bottom-color:#ECECEE;" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr>'
                               .'<td class="dragonecommercezyx987hh-force-col-center" style="text-align:center;padding-top:25px;padding-bottom:40px;padding-right:0;padding-left:0;" valign="top"> <a rel="nofollow noopener noreferrer" target="_blank" href="%%%companyurl%%%" style="text-decoration:none;color:#959597;">%%%companyname%%%</a> </td> </tr></tbody></table>'
                               .'</td></tr>'
                               .'<tr class="dragonecommercezyx987one-col"><td class="dragonecommercezyx987inner dragonecommercezyx987footer-row-bottom" style="padding-left:20px;padding-right:20px;padding-bottom:0px;padding-top:20px;"> <table class="dragonecommercezyx987fluid" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr>'
                               .'<td class="dragonecommercezyx987hh-force-col-center dragonecommercezyx987footer-text-left" style="text-align:left;padding-top:0px;padding-bottom:40px;padding-right:0;padding-left:0;" valign="top">'
                               .'<p style="display:none;"></p></td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></div></center></td></tr></tbody></table></div></div></div>';
                        $msg = str_replace("%%%companyname%%%", $websiteurl, $msg);                            
                        $msg = str_replace("%%%title%%%", $websiteurl, $msg);                        
                        $content = '';
                        $msg = str_replace("%%%username%%%", $username, $msg);
                        $msg = str_replace("%%%header%%%", 'Bad news. Your account has been disapproved by admin. Now you can NOT log on from our ecommerce website %%%companyurl%%%', $msg);
                        $msg = str_replace("%%%content%%%", $content, $msg);
                        $msg = str_replace("%%%companyurl%%%", $websiteurl, $msg);                                                                                    
                        $msg = str_replace("%%%address1%%%", '', $msg);                                                                                    
                        $msg = str_replace("%%%address2%%%", '', $msg);                                    
                        if($setting_email_method === 'WordPress Email') {
                            $headers = 'From: '. $bccemail . "\r\n" .
                                'Reply-To: ' . $email . "\r\n" .
                                'Bcc: ' . $bccemail . "\r\n";
                             
                            //Validation and send mail
                            add_filter('wp_mail_content_type', function($content_type) {
                                        return 'text/html';
                            });
                            $sent = wp_mail($email, $subject, $msg, $headers);
                            if($sent) {
                            } else {//message wasn't sent
                                $finalresult .= "Admin disapproval email was not sent to you. Please contact website admin. ";        
                                dragonecommercereservezyx987_saveToLogTable($finalresult, 'disapprove user', 'error', intval($current_user->data->ID));                                
                            }                                        
                        } elseif($setting_email_method === 'Mailgun') {
                            $data = array(
                                'from' => $mailgun_fromname . ' <mailgun@' . $mailgun_domain . '>',
                                'to' => $email,
                                'bcc' => $bccemail,
                                'subject' => $subject,
                                'html' => $msg,
                                'o:tracking' => false);
                            $auth = base64_encode('api:'.$mailgun_api_key);
                            $args = [
                                'headers' => ['Authorization' => "Basic $auth"],
                                'body' => $data
                            ];
                            $mailgun_result = wp_remote_post($mailgun_api_url . $mailgun_domain . '/messages', $args);    
                            if(is_wp_error($mailgun_result)) {
                                $finalresult .= 'Mailgun result: ' . json_encode($mailgun_result);
                                $emailsent = 0;
                            }
                        } elseif($setting_email_method === 'Mailchimp') {
                            $data = array(
                                "key"=> $mailchimp_api_key, 
                                "message"=> array(
                                    "from_email"=> $mailchimp_fromemail,
                                    "from_name"=> $mailchimp_fromname,
                                    "subject"=> $subject, 
                                    "html"=> $msg,
                                    "to"=> array(array("email"=> $email, "name"=> "", "type"=>"to"), array("email"=> $bccemail, "name"=> "", "type"=>"bcc")),
                                    "track_opens"=>true,
                                    "track_clicks"=>true
                                )
                            );
                            $data2 = json_encode($data);
                            $auth = base64_encode('authorization: apikey '.$mailchimp_api_key);
                            $args = [
                                'headers' => ['Authorization' => "Basic $auth"],
                                'body' => $data2
                            ];
                            $response = wp_remote_post($mailchimp_api_url, $args);
                            if(is_wp_error($response)) {
                                $finalresult .= 'Mailchimp result: ' . $response->get_error_message();
                                $emailsent = 0;
                            }
                            //$response = json_decode($response0, true);
                            if($response !== null && is_array($response) && count($response) > 0 && isset($response[0]["status"]) && ($response[0]["status"] === 'rejected' || $response[0]["status"] === 'invalid')) {
                                $finalresult .= 'Mailchimp result: ' . json_encode($response);
                                $emailsent = 0;
                            }
                        } elseif($setting_email_method === 'SendGrid') {
                            $data = array(
                                "personalizations"=> array(
                                    array(
                                        "to"=> array(array("email"=> $email)),
                                        "bcc"=> array(array("email"=> $bccemail))
                                    )
                                ), 
                                "from"=>array(
                                    "email"=> $sendgrid_fromemail,
                                    "name"=> $sendgrid_fromname
                                ),
                                "subject"=>$subject,
                                "content"=>array(
                                    array(
                                        "type"=> "text/html", 
                                        "value"=> $msg
                                    )                            
                                )
                            );
                            $data2 = json_encode($data);
                            //$auth = base64_encode('api:'.$sendgrid_api_key);
                            $args = array(
                                'headers' => array("Authorization" => "Bearer " . $sendgrid_api_key, "Content-Type" => "application/json"),
                                'body' => $data2
                            );    
                            $response = wp_remote_post($sendgrid_api_url, $args);    
                            if(is_wp_error($response)) {
                                $finalresult .= 'SendGrid result: ' . $response->get_error_message();
                                $emailsent = 0;
                            }
                            //$response = json_decode($response0, true);
                            if($response !== null && $response !== '' && is_array($response) && count($response) > 0 && (!empty($response["body"]["errors"]))) {
                                $finalresult .= 'SendGrid result: ' . json_encode($response);
                                $emailsent = 0;
                            }                
                        }        
                        if($finalresult === '') {                        
                            $finalresult .= "Success";
                        }
                        echo esc_html($finalresult);
                        exit();                                                                                    
                    } else {
                        echo "We found " . count($result) . " user(s) for this email address. Please contact website admin.";
                        exit();                            
                    }
                } else {
                    echo 'This website can not use mysqli. Please contact website admin.';
                    exit();
                }                    
            }                
            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_dragonecommercereservezyx987_disableProduct', 'dragonecommercereservezyx987_disableProductByAjax');
function dragonecommercereservezyx987_disableProductByAjax() {
    check_ajax_referer('dragonecommercereservezyx987_disableProduct', 'dragonecommercereservezyx987_hidden_security_disableproduct');
    $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();
    }
    $myerrormessage = '';
    if((in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $productid_temp = empty($_POST['id']) ? 0 : sanitize_text_field($_POST['id']);
        $productid_temp = strip_tags($productid_temp);
        $productid = intval($productid_temp);
        if($productid > 0) {
            global $wpdb;
            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
            $table_name = 'wp_dragonecommercereservezyx987_product';                
            $result = $wpdb->query($wpdb->prepare("UPDATE $table_name SET status = 0 WHERE id = %d", $productid));
            if($result === FALSE) {
                $dragon_ecommerce_dbResult .= 'Error disabling a record from table ' . $table_name . ", id: " . $productid . ". ";
                echo 'Error disabling a record from table ' . $table_name . ", id: " . $productid . ".";
                exit();
            } else {
                echo "success";exit();
            }
        } else {
            $dragon_ecommerce_dbResult .= 'Error disabling a record from table ' . $table_name . ", wrong id: " . $productid . ". ";
            echo 'Error disabling a record from table ' . $table_name . ", wrong id: " . $productid . ".";
            exit();
        }
    } else {
        $myerrormessage = 'You do not have administrator role or it is not a POST request.';
    }
    echo esc_html($myerrormessage);
    exit();    
}

add_action('wp_ajax_dragonecommercereservezyx987_enableProduct', 'dragonecommercereservezyx987_enableProductByAjax');
function dragonecommercereservezyx987_enableProductByAjax() {
    check_ajax_referer('dragonecommercereservezyx987_enableProduct', 'dragonecommercereservezyx987_hidden_security_enableproduct');
    $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();
    }
    $myerrormessage = '';
    if(in_array('administrator', (array) $current_user->roles) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $productid_temp = empty($_POST['id']) ? 0 : sanitize_text_field($_POST['id']);
        $productid_temp = strip_tags($productid_temp);
        $productid = intval($productid_temp);        
        if($productid > 0) {
            global $wpdb;
            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
            $table_name = 'wp_dragonecommercereservezyx987_product';                
            $result = $wpdb->query($wpdb->prepare("UPDATE $table_name SET status = 1 WHERE id = %d", $productid));
            if($result === FALSE) {
                $dragon_ecommerce_dbResult .= 'Error enabling a record from table ' . $table_name . ", id: " . $productid . ". ";
                exit();
            } else {
                echo "success";exit();
            }
        } else {
            $dragon_ecommerce_dbResult .= 'Error enabling a record from table ' . $table_name . ", wrong id: " . $productid . ". ";
            exit();
        }
    } else {
        $myerrormessage = 'You do not have administrator role or it is not a POST request.';
    }
    echo esc_html($myerrormessage);
    exit();    
}

//only for admin page, logged in 
add_action('wp_ajax_dragonecommercereservezyx987_getoneproductadmin', 'dragonecommercereservezyx987_getOneProductAdmin');
function dragonecommercereservezyx987_getOneProductAdmin() {
    check_ajax_referer('dragonecommercereservezyx987_getoneproductadmin', 'dragonecommercereservezyx987_hidden_security_getoneproductadmin');
    if((!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $productid_temp = empty($_POST['id']) ? '' : sanitize_text_field($_POST['id']);
        $productid_temp = strip_tags($productid_temp);
        $productid = intval($productid_temp);
        if($productid_temp == $_POST['id'] && $productid > 0 && ((string)(int)$productid_temp == $productid_temp)) {                                
            global $wpdb;
            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
            $table_name = 'wp_dragonecommercereservezyx987_product';
            $table_name2 = 'wp_dragonecommercereservezyx987_department';
            $table_name3 = 'wp_dragonecommercereservezyx987_product_group';
            $table_name4 = 'wp_dragonecommercereservezyx987_product_store';
            $table_name5 = 'wp_dragonecommercereservezyx987_currency';                
            $table_name6 = 'wp_dragonecommercereservezyx987_group';
            $table_name7 = 'wp_dragonecommercereservezyx987_setting';
            $table_name8 = 'wp_dragonecommercereservezyx987_group_property';
            $table_name9 = 'wp_dragonecommercereservezyx987_propertyvalue';
            $table_name10 = 'wp_dragonecommercereservezyx987_property';                
            $table_name11 = 'wp_dragonecommercereservezyx987_product_propertyvalue';
            $table_name12 = 'wp_dragonecommercereservezyx987_store';
            $table_name13 = 'wp_dragonecommercereservezyx987_weight';
            $table_name14 = 'wp_dragonecommercereservezyx987_distance';            
            if($wpdb->use_mysqli) {
                if($wpdb->dbh->connect_error) {
                    die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
                }
                //if one product has more than one group, log error
                $dbcount = $wpdb->get_var("SELECT COUNT(*) FROM $table_name3 WHERE productid = " . $productid);
                if($dbcount !== '0' && $dbcount !== '1') {
                    $message = "Error: product id: " . $productid . " is in more than one group: in " . $dbcount . " groups.";
                    dragonecommercereservezyx987_saveToLogTable($message, "ADMIN PAGE GET ONE PRODUCT", 'error');
                    header("Content-Type: application/json");
                    echo json_encode("{}");    
                    exit();                    
                }                
                $query = "SELECT a.id,min(a.quantity) 'quantity',min(a.originalquantity) 'originalquantity',min(a.departmentid) 'departmentid',"
                        . " min(a.name) 'name',min(a.description) 'description',min(a.imagefilenames) 'imagefilenames',min(a.weightlb) 'weightlb',"
                        . " min(a.price) 'price',min(a.saleprice) 'saleprice',min(a.isonsale) 'isonsale',min(a.istaxfree) 'istaxfree',"
                        . " min(a.barcode) 'barcode',min(a.createtimeutc) 'createtimeutc',min(a.shipfromnearestbranch) 'shipfromnearestbranch',"
                        . " min(a.onsalestartdateutc) 'onsalestartdateutc',min(a.onsaleenddateutc) 'onsaleenddateutc',"
                        . " min(b.name) as 'departmentname',group_concat(c.groupid) as 'groups',"
                        . " group_concat(concat(f.countryid, '|', f.provinceid, '|', f.cityid,'|', d.productquantity)) as 'locations' "
                        . " from $table_name a LEFT JOIN $table_name2 b on a.departmentid = b.id "                        
                        . " left join $table_name3 c on a.id = c.productid left join $table_name4 d on a.id = d.productid "
                        . " left join $table_name12 f ON d.storeid = f.id WHERE a.id = ? group by a.id";
                $stmt = $wpdb->dbh->prepare($query);
                $stmt->bind_param("i", $productid);
                $stmt->execute();
                $myresult = $stmt->get_result();
                $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
                $stmt->close();
                //if product isonsale = 1, onsalestartdateutc > UTC_TIMESTAMP() or a.onsaleenddateutc < UTC_TIMESTAMP(), then use price, not saleprice for customer to buy, isonsale set to 0 on the webpage
                //error_log("at 11436, result: " . json_encode($result));                    
                //error_log("at 11437, is_admin(): " . (is_admin()===true?'YES':'NO'));
                $query = "SELECT pg.groupid, gp.propertyid, p.shownname AS 'propertyname',pv.id AS 'propertyvalueid', pv.shownname AS 'propertyvaluename' "
                        . " FROM $table_name3 pg "
                        . " JOIN $table_name6 g "
                        . " on pg.groupid = g.id "
                        . " AND g.status = 1 "
                        . " AND g.groupcategoryid = ( "
                        . " SELECT CAST(value AS UNSIGNED) AS 'id' FROM $table_name7 "
                        . " WHERE name = 'GROUP_CATEGORY_ID_FOR_CUSTOMER_CHOOSE_PRODUCT_DETAILS' "                        
                        . " ) "
                        . " AND pg.productid = ? "                            
                        . " join $table_name8 gp "
                        . " ON gp.groupid = pg.groupid "
                        . " join $table_name9 pv "
                        . " ON gp.propertyid = pv.propertyid "
                        . " AND pv.status = 1 "
                        . " join $table_name10 p "
                        . " ON gp.propertyid = p.id "
                        . " AND p.status = 1"
                        . " order by pg.groupid, gp.propertyid, pv.id ";
                $stmt = $wpdb->dbh->prepare($query);
                $stmt->bind_param("i", $productid);
                $stmt->execute();
                $myresult = $stmt->get_result();
                $result2 = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
                $stmt->close();

                $query = "SELECT distinct propertyvalueids, quantity FROM $table_name11 where status = 1 AND productid = ? AND (quantity is null or quantity > 0)";
                $stmt = $wpdb->dbh->prepare($query);
                $stmt->bind_param("i", $productid);
                $stmt->execute();
                $myresult = $stmt->get_result();
                $result3 = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
                $result4 = array();
                foreach ($result3 as $temp) {
                    $result4[] = $temp["propertyvalueids"];
                }
                $stmt->close();
                
                $finalresult = [];
                $finalresult["productdetails1"] = $result;
                $finalresult["productdetails2"] = $result2;
                $finalresult["productoptions"] = $result4;                
                header("Content-Type: application/json");
                echo json_encode($finalresult);    
                exit();
            }
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();    
}

//only for customer shopping page, both logged in and NOT logged in
add_action('wp_ajax_dragonecommercereservezyx987_getoneproduct', 'dragonecommercereservezyx987_getOneProduct');
add_action('wp_ajax_nopriv_dragonecommercereservezyx987_getoneproduct', 'dragonecommercereservezyx987_getOneProduct'); 
function dragonecommercereservezyx987_getOneProduct() {
    check_ajax_referer('dragonecommercereservezyx987_getoneproduct', 'dragonecommercereservezyx987_hidden_security_getoneproduct');
    if((!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $productid_temp = empty($_POST['id']) ? '' : sanitize_text_field($_POST['id']);
        $productid_temp = strip_tags($productid_temp);
        $productid = intval($productid_temp);
        if($productid_temp == $_POST['id'] && $productid > 0 && ((string)(int)$productid_temp == $productid_temp)) {                                
            global $wpdb;
            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
            $table_name = 'wp_dragonecommercereservezyx987_product';
            $table_name2 = 'wp_dragonecommercereservezyx987_department';
            $table_name3 = 'wp_dragonecommercereservezyx987_product_group';
            $table_name4 = 'wp_dragonecommercereservezyx987_product_store';
            $table_name5 = 'wp_dragonecommercereservezyx987_currency';                
            $table_name6 = 'wp_dragonecommercereservezyx987_group';
            $table_name7 = 'wp_dragonecommercereservezyx987_setting';
            $table_name8 = 'wp_dragonecommercereservezyx987_group_property';
            $table_name9 = 'wp_dragonecommercereservezyx987_propertyvalue';
            $table_name10 = 'wp_dragonecommercereservezyx987_property';                
            $table_name11 = 'wp_dragonecommercereservezyx987_product_propertyvalue';
            $table_name12 = 'wp_dragonecommercereservezyx987_store';
            $table_name13 = 'wp_dragonecommercereservezyx987_weight';
            $table_name14 = 'wp_dragonecommercereservezyx987_distance';            
            if($wpdb->use_mysqli) {
                if($wpdb->dbh->connect_error) {
                    die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
                }
                //if one product has more than one group, log error
                $dbcount = $wpdb->get_var("SELECT COUNT(*) FROM $table_name3 WHERE productid = " . $productid);
                if($dbcount !== '0' && $dbcount !== '1') {
                    $message = "Error: product id: " . $productid . " is in more than one group: in " . $dbcount . " groups.";
                    dragonecommercereservezyx987_saveToLogTable($message, "GET ONE PRODUCT", 'error');
                    header("Content-Type: application/json");
                    echo json_encode("{}");    
                    exit();                    
                }                                
                $query = "SELECT a.id,min(a.quantity) 'quantity',min(a.originalquantity) 'originalquantity',min(a.departmentid) 'departmentid',"
                        . " min(a.name) 'name',min(a.description) 'description',min(a.imagefilenames) 'imagefilenames',min(a.weightlb) 'weightlb',"
                        . " min(a.price) 'price',min(a.saleprice) 'saleprice',min(a.isonsale) 'isonsale',min(a.istaxfree) 'istaxfree',"
                        . " min(a.barcode) 'barcode',min(a.createtimeutc) 'createtimeutc',min(a.shipfromnearestbranch) 'shipfromnearestbranch',"
                        . " min(a.onsalestartdateutc) 'onsalestartdateutc',min(a.onsaleenddateutc) 'onsaleenddateutc',"
                        . " min(b.name) as 'departmentname',group_concat(c.groupid) as 'groups',"
                        . " group_concat(concat(f.countryid, '|', f.provinceid, '|', f.cityid,'|', d.productquantity)) as 'locations' "
                        . " from $table_name a LEFT JOIN $table_name2 b on a.departmentid = b.id "                        
                        . " left join $table_name3 c on a.id = c.productid left join $table_name4 d on a.id = d.productid "
                        . " left join $table_name12 f ON d.storeid = f.id WHERE a.id = ? group by a.id";
                $stmt = $wpdb->dbh->prepare($query);
                $stmt->bind_param("i", $productid);
                $stmt->execute();
                $myresult = $stmt->get_result();
                $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
                $stmt->close();
                //if product isonsale = 1, onsalestartdateutc > UTC_TIMESTAMP() or a.onsaleenddateutc < UTC_TIMESTAMP(), then use price, not saleprice for customer to buy, isonsale set to 0 on the webpage
                //error_log("at 11547, result: " . json_encode($result));
                for ($i=0; $i<count($result); $i++) {
                    if($result[$i]["isonsale"] === 1) {
                        if($result[$i]["onsalestartdateutc"] !== null && $result[$i]["onsalestartdateutc"] !== '' && $result[$i]["onsalestartdateutc"] > gmdate("Y-m-d H:i:s")) {
                            $result[$i]["isonsale"] = 0;
                        } elseif($result[$i]["onsaleenddateutc"] !== null && $result[$i]["onsaleenddateutc"] !== '' && $result[$i]["onsaleenddateutc"] < gmdate("Y-m-d H:i:s")) {
                            $result[$i]["isonsale"] = 0;
                        }                    
                    }
                }    
                //error_log("at 11557, result: " . json_encode($result));                
                //error_log("at 11558, is_admin(): " . (is_admin()===true?'YES':'NO'));
                $query = "SELECT pg.groupid, gp.propertyid, p.shownname AS 'propertyname',pv.id AS 'propertyvalueid', pv.shownname AS 'propertyvaluename' "
                        . " FROM $table_name3 pg "
                        . " JOIN $table_name6 g "
                        . " on pg.groupid = g.id "
                        . " AND g.status = 1 "
                        . " AND g.groupcategoryid = ( "
                        . " SELECT CAST(value AS UNSIGNED) AS 'id' FROM $table_name7 "
                        . " WHERE name = 'GROUP_CATEGORY_ID_FOR_CUSTOMER_CHOOSE_PRODUCT_DETAILS' "                        
                        . " ) "
                        . " AND pg.productid = ? "                            
                        . " join $table_name8 gp "
                        . " ON gp.groupid = pg.groupid "
                        . " join $table_name9 pv "
                        . " ON gp.propertyid = pv.propertyid "
                        . " AND pv.status = 1 "
                        . " join $table_name10 p "
                        . " ON gp.propertyid = p.id "
                        . " AND p.status = 1"
                        . " order by pg.groupid, gp.propertyid, pv.id ";
                $stmt = $wpdb->dbh->prepare($query);
                $stmt->bind_param("i", $productid);
                $stmt->execute();
                $myresult = $stmt->get_result();
                $result2 = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
                $stmt->close();

                $query = "";
                $ENABLE_PRODUCT_QUANTITY_AUTO_DEDUCT = $wpdb->get_var("SELECT value FROM $table_name7 WHERE name = 'ENABLE_PRODUCT_QUANTITY_AUTO_DEDUCT'");
                if($ENABLE_PRODUCT_QUANTITY_AUTO_DEDUCT === '1') {
                    $query = "SELECT distinct propertyvalueids, quantity FROM $table_name11 where status = 1 AND productid = ? AND (quantity is null or quantity > 0)";
                } else {
                    $query = "SELECT distinct propertyvalueids, quantity FROM $table_name11 where status = 1 AND productid = ? ";                    
                }
                $stmt = $wpdb->dbh->prepare($query);
                $stmt->bind_param("i", $productid);
                $stmt->execute();
                $myresult = $stmt->get_result();
                $result3 = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
                $result4 = array();
                foreach ($result3 as $temp) {
                    $result4[] = $temp["propertyvalueids"];
                }
                $stmt->close();
                
                $finalresult = [];
                $finalresult["productdetails1"] = $result;
                $finalresult["productdetails2"] = $result2;
                $finalresult["productoptions"] = $result4;                
                header("Content-Type: application/json");
                echo json_encode($finalresult);    
                exit();
            }
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();    
}

add_action('wp_ajax_dragonecommercereservezyx987_getshippinghandlingtaxpreorderdata', 'dragonecommercereservezyx987_getShippingHandlingTaxPreorderData');
function dragonecommercereservezyx987_getShippingHandlingTaxPreorderData() {
    check_ajax_referer('dragonecommercereservezyx987_getshippinghandlingtaxpreorderdata', 'dragonecommercereservezyx987_hidden_security_getshippinghandlingtaxpreorderdata');
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        $result = array("status"=>"fail", "result"=>"User is not logged in");
        header("Content-Type: application/json");
        echo json_encode($result);
        exit();
    }
    if($current_user->roles !== null && (!in_array('dragonecommercereservecustomer', (array) $current_user->roles))) {
        $result = array("status"=>"fail", "result"=>"User does not have the role to reserve on this ecommerce website");
        header("Content-Type: application/json");
        echo json_encode($result);
        exit();
    }    
    if((in_array('dragonecommercereservecustomer', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $tocountry_temp = empty($_POST['tocountry']) ? '' : sanitize_text_field($_POST['tocountry']);
        $tocountry_temp = strip_tags($tocountry_temp);
        $tocountry = $tocountry_temp;
        $tostateprovinceid_temp = empty($_POST['tostateprovinceid']) ? '' : sanitize_text_field($_POST['tostateprovinceid']);
        $tostateprovinceid_temp = strip_tags($tostateprovinceid_temp);
        $tostateprovinceid = intval($tostateprovinceid_temp);
        $subtotal_temp = empty($_POST['subtotal']) ? '' : sanitize_text_field($_POST['subtotal']);
        $subtotal_temp = strip_tags($subtotal_temp);
        $subtotal = floatval($subtotal_temp);                        
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');            
        $table_name5 = 'wp_dragonecommercereservezyx987_country';
        $table_name6 = 'wp_dragonecommercereservezyx987_group';
        $table_name7 = 'wp_dragonecommercereservezyx987_setting';
        $table_name8 = 'wp_dragonecommercereservezyx987_group_property';
        $table_name9 = 'wp_dragonecommercereservezyx987_propertyvalue';
        $table_name10 = 'wp_dragonecommercereservezyx987_property';    
        $table_name11 = 'wp_dragonecommercereservezyx987_chargetype';                
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }                    
            $query = "SELECT gp.propertyid, g.groupcategoryid, s.name AS 'settingname', p.chargetypeid, p.shownname AS 'propertyname',pv.id AS 'propertyvalueid', pv.name AS 'propertyvaluename',pv.* "
                    . " FROM $table_name6 g "
                    . " join $table_name7 s "
                    . " ON g.groupcategoryid = CAST(s.value AS UNSIGNED) "
                    . " AND g.status = 1 "
                    . " AND (" 
                    . " (s.name = 'GROUP_CATEGORY_ID_FOR_ORDER_SHIPPING_DETAILS' "    
                    . " AND g.id = (SELECT CAST(value AS UNSIGNED) from $table_name7 WHERE name = 'GROUP_ID_FOR_ORDER_SHIPPING_DETAILS')) "
                    . " OR "
                    . " (s.name = 'GROUP_CATEGORY_ID_FOR_ORDER_HANDLING_DETAILS' "
                    . " AND g.id = (SELECT CAST(value AS UNSIGNED) from $table_name7 WHERE name = 'GROUP_ID_FOR_ORDER_HANDLING_DETAILS')) "
                    . " OR s.name = 'GROUP_CATEGORY_ID_FOR_ORDER_TAX_DETAILS' "    
                    . " OR s.name = 'GROUP_CATEGORY_ID_FOR_PREORDER_AND_STORE_BUYPICKUP_DETAILS' "
                    . " OR s.name = 'GROUP_CATEGORY_ID_FOR_DISCOUNT') "                                
                    . " join $table_name8 gp "
                    . " ON gp.groupid = g.id "
                    . " left join $table_name9 pv "
                    . " ON gp.propertyid = pv.propertyid "
                    . " AND pv.status = 1 "                                        
                    . " AND (pv.start is null or pv.start = '' or pv.start <= UTC_TIMESTAMP()) "    
                    . " AND (pv.end is null or pv.end = '' or pv.end >= UTC_TIMESTAMP()) "                                        
                    . " join $table_name10 p "
                    . " ON gp.propertyid = p.id "    
                    . " AND p.status = 1"                            
                    . " AND p.shownname IS NOT NULL"
                    . " WHERE (p.chargetypeid = (SELECT id from $table_name11 WHERE id is not null and name = 'location' LIMIT 1) AND pv.tocountryid = (SELECT id FROM $table_name5 WHERE abbreviation = ? LIMIT 1)  AND pv.tostateprovinceid = ?)"
                    . " OR (p.chargetypeid is null OR p.chargetypeid != (SELECT id from $table_name11 WHERE id is not null and name = 'location' LIMIT 1))"                                                    
                    . " order by g.id, gp.propertyid, pv.id ";
            $stmt = $wpdb->dbh->prepare($query);
            $stmt->bind_param("si", $tocountry, $tostateprovinceid);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $result2 = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            //error_log("at 11691, for landing page javascript: result2: " . json_encode($result2));
            $result3 = array();
            foreach ($result2 as $temp) {
                if(!empty($temp["minordersubtotal"])) {
                    if($subtotal >= $temp["minordersubtotal"]) {
                        $result3[] = $temp;
                    }
                } elseif($temp["minordersubtotal"] === 0 || $temp["minordersubtotal"] === null) {
                    $result3[] = $temp;
                }
            }
            $result = array("status"=>"success", "result"=>$result3);
            header("Content-Type: application/json");
            echo json_encode($result);
            exit();
        } else {
            $result = array("status"=>"fail", "result"=>"This website can not use mysqli. Please contact website admin.");
            header("Content-Type: application/json");
            echo json_encode($result);
            exit();
        }
    }
    $result = array("status"=>"fail", "result"=>"Something wrong with your order. Please contact website admin.");
    header("Content-Type: application/json");
    echo json_encode($result);
    exit();    
}

add_action('wp_ajax_dragonecommercereservezyx987_validatecoupon', 'dragonecommercereservezyx987_validateCoupon');
function dragonecommercereservezyx987_validateCoupon() {
    check_ajax_referer('dragonecommercereservezyx987_validatecoupon', 'dragonecommercereservezyx987_hidden_security_validatecoupon');
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        $result = array("status"=>"fail", "result"=>"User is not logged in");
        header("Content-Type: application/json");
        echo json_encode($result);
        exit();
    }
    if($current_user->roles !== null && (!in_array('dragonecommercereservecustomer', (array) $current_user->roles))) {
        $result = array("status"=>"fail", "result"=>"User does not have the role to reserve on this ecommerce website");
        header("Content-Type: application/json");
        echo json_encode($result);
        exit();
    }
    
    if((in_array('dragonecommercereservecustomer', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $couponcode_temp = empty($_POST['coupon']) ? '' : sanitize_text_field($_POST['coupon']);
        $couponcode = strip_tags($couponcode_temp);                            
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_propertyvalue';
        
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }                    
            $query = "SELECT * FROM $table_name WHERE code = ? "
                    . " AND (`start` is null or `start` = '' or `start` <= UTC_TIMESTAMP()) "    
                    . " AND (`end` is null or `end` = '' or `end` >= UTC_TIMESTAMP()) "
                    . " AND status = 1 order by fee, rate LIMIT 1";
            $stmt = $wpdb->dbh->prepare($query);
            $stmt->bind_param("s", $couponcode);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();                    
            if(empty($result)) {
                $result2 = array("status"=>"fail", "result"=>"This coupon is not valid");
                header("Content-Type: application/json");
                echo json_encode($result2);
                exit();                        
            }                    
            $result2 = array("status"=>"success", "result"=>$result);
            header("Content-Type: application/json");
            echo json_encode($result2);
            exit();
        } else {
            $result = array("status"=>"fail", "result"=>"This website can not use mysqli. Please contact website admin.");
            header("Content-Type: application/json");
            echo json_encode($result);
            exit();
        }
    }
    $result = array("status"=>"fail", "result"=>"Something wrong with your order. Please contact website admin.");
    header("Content-Type: application/json");
    echo json_encode($result);
    exit();    
}

add_action('wp_ajax_dragonecommercereservezyx987_getdisabledProducts', 'dragonecommercereservezyx987_getdisabledProducts');
function dragonecommercereservezyx987_getdisabledProducts() {
    check_ajax_referer('dragonecommercereservezyx987_getdisabledProducts', 'dragonecommercereservezyx987_hidden_security_getdisabledproducts');
    $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 json_encode("{}");
        exit();
    }
    if(in_array('administrator', (array) $current_user->roles) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_product';
        $table_name2 = 'wp_dragonecommercereservezyx987_department';
        $storedprocedure_name = 'wp_dragonecommercereservezyx987_getProductList';

        $productstatus = 0;            
        $amountperpage = empty($_POST['amountperpage']) ? '10' : sanitize_text_field($_POST['amountperpage']);
        $amountperpage = strip_tags($amountperpage);
        $amountperpage = intval($amountperpage);    
        if($amountperpage === -1) {$amountperpage = 10;}
                    
        $pagenumber = empty($_POST['pagenumber']) ? '1' : sanitize_text_field($_POST['pagenumber']);;
        $pagenumber = strip_tags($pagenumber);
        $pagenumber = intval($pagenumber);
        
        $myoffset = ($pagenumber - 1) * $amountperpage;
        
        $mysortby = empty($_POST['sortby']) ? '' : sanitize_text_field($_POST['sortby']);
        $mysortby = strip_tags($mysortby);
        $mysortby = $mysortby === '' ? 'id' : $mysortby;
        
        //this is order the SQL result asc or desc, not the order table
        $myorder = empty($_POST['order']) ? '' : sanitize_text_field($_POST['order']);
        $myorder = strip_tags($myorder);
        $myorder = $myorder === '' ? 'asc' : $myorder;
        
        $searchwords = empty($_POST['searchwords']) ? '' : sanitize_text_field($_POST['searchwords']);
        $searchwords = strip_tags($searchwords);
        $barcode = empty($_POST['barcode']) ? '' : sanitize_text_field($_POST['barcode']);
        $barcode = strip_tags($barcode);

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

        $minprice = empty($_POST['minprice']) ? '0.00' : sanitize_text_field($_POST['minprice']);
        $minprice = strip_tags($minprice);
        $minprice = floatval($minprice);            

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

        $isonsale_temp = (!isset($_POST['isonsale'])) ? '0' : sanitize_text_field($_POST['isonsale']);
        $isonsale_temp = strip_tags($isonsale_temp);
        $isonsale = intval($isonsale_temp);

        $istaxfree_temp = (!isset($_POST['istaxfree'])) ? '0' : sanitize_text_field($_POST['istaxfree']);
        $istaxfree_temp = strip_tags($istaxfree_temp);
        $istaxfree = intval($istaxfree_temp);
        
        if(dragonecommercereservezyx987_validateDate($fromdate) && dragonecommercereservezyx987_validateDate($todate)) {
            if($fromdate > $todate) {
                echo "Error. From date is later than to date.";exit();                        
            }
        }else{
            echo "Error. Please enter a valid date.";exit();    
        }
        if($isonsale === 0 || $isonsale === -1 || $isonsale === 1) {
        } else {
            echo "Error. Incorrect is on sale value: " . $isonsale;exit();            
        }
        if($istaxfree === 0 || $istaxfree === -1 || $istaxfree === 1) {
        } else {
            echo "Error. Incorrect is tax free value: " . $istaxfree;exit();            
        }        
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $query = "CALL " . $storedprocedure_name . "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, @outvalue, @outvalue2);";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');
            
            $types .= 'i';
            $parameterArray[] = &$isonsale;

            $types .= 'i';
            $parameterArray[] = &$istaxfree;
            
            $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[] = &$barcode;
            
            $types .= 'i';
            $parameterArray[] = &$departmentid;        

            $types .= 'd';
            $minprice2 = floatval($minprice);
            $parameterArray[] = &$minprice2;    

            $types .= 'd';
            $maxprice2 = floatval($maxprice);
            $parameterArray[] = &$maxprice2;

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

            $types .= 's';
            $parameterArray[] = &$todate;                
            
            $types .= 'i'; //0: inactive, 1: active, -1: both
            $parameterArray[] = &$productstatus;            
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $products = $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 ($products as $product) {
                foreach ($product as $key => $value) {
                    $product[$key] = $value === null ? '' : deslash($value);
                }
            }
            $result = [];
            $result["product"] = $products;
            $result["total"] = $total;
            header("Content-Type: application/json");
            echo json_encode($result);    
            exit();                        
        }
    }
    header("Content-Type: application/json");
    echo json_encode("{}");    
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_addOrderByBraintreeByAjax', 'dragonecommercereservezyx987_addOrderByBraintreeByAjax'); 
function dragonecommercereservezyx987_addOrderByBraintreeByAjax() {
    check_ajax_referer('dragonecommercereservezyx987_addOrderByBraintreeByAjax', 'dragonecommercereservezyx987_hidden_security_addOrderByBraintreeByAjax');
    //first, check if the user is admin or dragonecommercereservecustomer role:
    $current_user = wp_get_current_user();
    if($current_user === null || $current_user->data->ID === null || intval($current_user->data->ID) <= 0) {
        $message = "Save reservation to DB: You are not logged in. Not saved.";
        dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error');
        echo esc_html($message);
        exit();    
    }
    $myuserid_temp = empty($_POST['userid']) ? '0' : sanitize_text_field($_POST['userid']);
    $myuserid_temp = strip_tags($myuserid_temp);
    $myuserid = intval($myuserid_temp);
    if($myuserid === 0) {
        $message = "Save reservation to DB: You are not logged in according to the data you posted to server. Not saved.";
        dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error');
        echo esc_html($message);
        exit();    
    }
    if($myuserid !== intval($current_user->data->ID)) {
        $message = "Save reservation to DB: You are logged in using a special way. Please contact website admin. Not saved.";
        dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error');
        echo esc_html($message);
        exit();    
    }    
    if(in_array('dragonecommercereservecustomer', (array) $current_user->roles) ) {
        //The user has the admin or "dragonecommercereservecustomer" role
    } else {
        $message = 'Save reservation to DB: You do not have the right role for ordering on this ecommerce website. Not saved.';
        dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', intval($current_user->data->ID));
        echo esc_html($message);
        exit();        
    }    
    $sessionAndCookieCompareUserid = dragonecommercereservezyx987_sessionAndCookieCompareUserid();
    if($sessionAndCookieCompareUserid !== 'Logged in, equal') {
        header("Content-Type: application/json");
        $message = '{"error":"' . $sessionAndCookieCompareUserid . '. Please log in. If you are already logged in, please log out and log in from this ecommerce website landing page. Not saved."}';    
        dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', intval($current_user->data->ID));
        echo esc_html($message);
        exit();    
    }
    if((!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $totalfee_temp = empty($_POST['totalfee']) ? '0' : sanitize_text_field($_POST['totalfee']);
        $totalfee_temp = strip_tags($totalfee_temp);        
        $totalfee = floatval($totalfee_temp);    
        $subtotal_temp = empty($_POST['subtotal']) ? '0' : sanitize_text_field($_POST['subtotal']);
        $subtotal_temp = strip_tags($subtotal_temp);            
        $subtotal = floatval($subtotal_temp);        
        if($totalfee <= 0) {
            $message = "Save reservation to DB: Total fee is not greater than 0. Not saved. ";
            dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', intval($current_user->data->ID));
            echo esc_html($message);
            exit();
        }                    
        $shippingname = empty($_POST['shippingname']) ? '' : sanitize_text_field($_POST['shippingname']);
        $shippingname = strip_tags($shippingname);            
        $shippingNameArr = explode(' ', $shippingname, 2);
        $shippingfirstname = '';
        $shippinglastname = '';
        if(count($shippingNameArr) === 2) {
            $shippingfirstname = trim($shippingNameArr[0]);
            $shippinglastname = trim($shippingNameArr[1]);    
        }                        
        $shippingaddress1 = empty($_POST['shippingaddress1']) ? '' : sanitize_text_field($_POST['shippingaddress1']);
        $shippingaddress1 = strip_tags($shippingaddress1);                    
        $shippingaddress2 = empty($_POST['shippingaddress2']) ? '' : sanitize_text_field($_POST['shippingaddress2']);
        $shippingaddress2 = strip_tags($shippingaddress2);                    
        $shippingcity = empty($_POST['shippingcity']) ? '' : sanitize_text_field($_POST['shippingcity']);
        $shippingcity = strip_tags($shippingcity);                                        
        $shippingprovinceid_temp = empty($_POST['shippingprovince']) ? '' : sanitize_text_field($_POST['shippingprovince']);
        $shippingprovinceid_temp = strip_tags($shippingprovinceid_temp);
        $shippingprovinceid = intval($shippingprovinceid_temp);
        $shippingprovincename = empty($_POST['shippingprovincename']) ? '' : sanitize_text_field($_POST['shippingprovincename']);
        $shippingprovincename = strip_tags($shippingprovincename);                
        $shippingcountryalpha2 = empty($_POST['shippingcountry']) ? '' : sanitize_text_field($_POST['shippingcountry']);
        $shippingcountryalpha2 = strip_tags($shippingcountryalpha2);            
        $shippingpostalcode = empty($_POST['shippingpostalcode']) ? '' : sanitize_text_field($_POST['shippingpostalcode']);
        $shippingpostalcode = strip_tags($shippingpostalcode);                                        
        $shippingphonenumber = empty($_POST['shippingphonenumber']) ? '' : sanitize_text_field($_POST['shippingphonenumber']);
        $shippingphonenumber = strip_tags($shippingphonenumber);                    
        $shippingemail = empty($_POST['shippingemail']) ? '' : sanitize_text_field($_POST['shippingemail']);
        $shippingemail = strip_tags($shippingemail);                                            
        $shippingdescription = empty($_POST['shippingdescription']) ? '' : sanitize_text_field($_POST['shippingdescription']);
        $shippingdescription = strip_tags($shippingdescription);
        $handlingdescription = empty($_POST['handlingdescription']) ? '' : sanitize_text_field($_POST['handlingdescription']);
        $handlingdescription = strip_tags($handlingdescription);

        $shippingidid_temp = empty($_POST['shippingid']) ? '-1' : sanitize_text_field($_POST['shippingid']);
        $shippingidid_temp = strip_tags($shippingidid_temp);
        $shippingid = intval($shippingidid_temp);
        
        $handlingid_temp = empty($_POST['handlingid']) ? '-1' : sanitize_text_field($_POST['handlingid']);
        $handlingid_temp = strip_tags($handlingid_temp);
        $handlingid = intval($handlingid_temp);
 
        $taxid_temp = empty($_POST['taxid']) ? '-1' : sanitize_text_field($_POST['taxid']);
        $taxid_temp = strip_tags($taxid_temp);
        $taxid = intval($taxid_temp);

        $discountids_temp = empty($_POST['discountids']) ? '' : sanitize_text_field($_POST['discountids']);
        $discountids = strip_tags($discountids_temp);
        $discountidsArr = array();
        if(trim($discountids) !== '') {
            $discountidsArr = explode("|",$discountids);
        }
        $couponids_temp = empty($_POST['couponids']) ? '' : sanitize_text_field($_POST['couponids']);
        $couponids = strip_tags($couponids_temp);    
        $couponidsArr = array();
        if(trim($couponids) !== '') {
            $couponidsArr = explode("|",$couponids);        
        }
        $discountdescription = '';
        $discountdescriptionforuser = '';
        $coupondescription = '';
        $coupondescriptionforuser = '';
        $shippingfee_temp = empty($_POST['shippingfee']) ? '0' : sanitize_text_field($_POST['shippingfee']);
        $shippingfee_temp = strip_tags($shippingfee_temp);        
        $shippingfee = floatval($shippingfee_temp);        
        $handlingfee_temp = empty($_POST['handlingfee']) ? '0' : sanitize_text_field($_POST['handlingfee']);
        $handlingfee_temp = strip_tags($handlingfee_temp);            
        $handlingfee = floatval($handlingfee_temp);
        $tax_temp = empty($_POST['tax']) ? '0' : sanitize_text_field($_POST['tax']);
        $tax_temp = strip_tags($tax_temp);            
        $tax = floatval($tax_temp);

        $shippingArr = null;
        $handlingArr = null;
        $taxArr = null;
        
        //$shippingname,$shippingfirstname,$shippinglastname,$shippingemail,$shippingphonenumber,$shippingaddress1,
        //$shippingcity,$shippingprovinceid,$shippingprovincename,$shippingcountryalpha2,$shippingpostalcode should not be empty
        if($shippingname === "" || $shippingfirstname === "" || $shippinglastname === "") {
            $message = "Save reservation to DB: Not saved. Please fill all the fields in the address and service. First name and last name are required.";
            dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', intval($current_user->data->ID));
            echo esc_html($message);
            exit();                
        }

        if($shippingemail === "" || $shippingphonenumber === "") {
            $message = "Save reservation to DB: Not saved. Please fill all the fields in the address and service. Shipping email and phone number are required.";
            dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', intval($current_user->data->ID));
            echo esc_html($message);
            exit();                
        }
        
        if($shippingaddress1 === "") {
            $message = "Save reservation to DB: Not saved. Please fill all the fields in the address and service. Shipping address 1 is required.";
            dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', intval($current_user->data->ID));
            echo esc_html($message);
            exit();                
        }

        if($shippingcity === "") {
            $message = "Save reservation to DB: Not saved. Please fill all the fields in the address and service. Shipping city is required.";
            dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', intval($current_user->data->ID));
            echo esc_html($message);
            exit();                
        }

        if($shippingprovinceid <= 0 || $shippingprovincename === "") {
            $message = "Save reservation to DB: Not saved. Please fill all the fields in the address and service. Shipping province id and province name are required.";
            dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', intval($current_user->data->ID));
            echo esc_html($message);
            exit();                
        }

        if($shippingcountryalpha2 === "-1") {
            $message = "Save reservation to DB: Not saved. Please fill all the fields in the address and service. Shipping country is required.";
            dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', intval($current_user->data->ID));
            echo esc_html($message);
            exit();                
        }

        if($shippingpostalcode === "") {
            $message = "Save reservation to DB: Not saved. Please fill all the fields in the address and service. Shipping postal code is required.";
            dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', intval($current_user->data->ID));
            echo esc_html($message);
            exit();                
        }

        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_order';
        $table_name2 = 'wp_dragonecommercereservezyx987_province';
        $table_name3 = 'wp_dragonecommercereservezyx987_country';
        $table_name4 = 'wp_dragonecommercereservezyx987_product_order';
        $table_name5 = 'wp_dragonecommercereservezyx987_order_propertyvalue';
        $table_name6 = 'wp_dragonecommercereservezyx987_product';
        $table_name7 = 'wp_dragonecommercereservezyx987_setting';
        $table_name8 = 'wp_dragonecommercereservezyx987_group_property';
        $table_name9 = 'wp_dragonecommercereservezyx987_propertyvalue';
        $table_name10 = 'wp_dragonecommercereservezyx987_property';    
        $table_name11 = 'wp_dragonecommercereservezyx987_chargetype';                
        $table_name12 = 'wp_dragonecommercereservezyx987_group';
        $table_name13 = 'wp_dragonecommercereservezyx987_emailmethod';
        $table_name14 = 'wp_dragonecommercereservezyx987_user_status';
        $table_name15 = 'wp_dragonecommercereservezyx987_product_propertyvalue';
        $table_name16 = 'wp_dragonecommercereservezyx987_processstatus';

        $ENABLE_SHIPPING_CHARGE_TEMP = $wpdb->get_var("SELECT value FROM $table_name7 WHERE name = 'ENABLE_SHIPPING_CHARGE'");    
        $ENABLE_SHIPPING_CHARGE = $ENABLE_SHIPPING_CHARGE_TEMP === null ? 0 : intval($ENABLE_SHIPPING_CHARGE_TEMP);        
        if($ENABLE_SHIPPING_CHARGE === 1 && $shippingid < 1) {
            $message = "Save reservation to DB: Not saved. Please fill all the fields in the address and service. Shipping id is required.";
            dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', intval($current_user->data->ID));
            echo esc_html($message);
            exit();                
        }
                        
        $ENABLE_HANDLING_CHARGE_TEMP = $wpdb->get_var("SELECT value FROM $table_name7 WHERE name = 'ENABLE_HANDLING_CHARGE'");    
        $ENABLE_HANDLING_CHARGE = $ENABLE_HANDLING_CHARGE_TEMP === null ? 0 : intval($ENABLE_HANDLING_CHARGE_TEMP);
        if($ENABLE_HANDLING_CHARGE === 1 && $handlingid < 1) {
            $message = "Save reservation to DB: Not saved. Please fill all the fields in the address and service. Handling id is required.";
            dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', intval($current_user->data->ID));
            echo esc_html($message);
            exit();                
        }

        if($taxid < 1) {
            $message = "Save reservation to DB: Not saved. Please fill all the fields in the address and service. Tax id is required.";
            dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', intval($current_user->data->ID));
            echo esc_html($message);
            exit();                
        }

        //validate shipping email if not empty string
        if(($shippingemail !== "") && (!filter_var($shippingemail, FILTER_VALIDATE_EMAIL))) {
            $message = "Save reservation to DB: Shipping email is not valid. Not saved. ";
            dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', intval($current_user->data->ID));
            echo esc_html($message);
            exit();            
        }            
        $orderid = 0;        
        $userid = intval($current_user->data->ID);        
        $MAX_PROMOTION_PER_ORDER = 0;
        $MAX_DISCOUNT_PER_ORDER = 0;
        $MAX_COUPON_PER_ORDER = 0;        
        $setting_email_method = ""; 
        
        $mailgun_api_key = "";
        $mailgun_api_url = "";
        $mailgun_domain = "";
        $mailgun_fromname = 'NO-REPLY';    
        $mailchimp_api_key = "";
        $mailchimp_api_url = "";
        $mailchimp_fromemail = "";
        $mailchimp_fromname = "";
        $sendgrid_api_key = "";
        $sendgrid_api_url = "";
        $sendgrid_fromemail = "";
        $sendgrid_fromname = "";
        
        $RESERVE_NEED_ADMIN_APPROVE = 1;
        $ENABLE_PRODUCT_QUANTITY_AUTO_DEDUCT = 0;
        
        if($userid === null || $userid <= 0) {
            $message = "Save reservation to DB: You are not logged in. Not saved. ";
            dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error');
            echo esc_html($message);
            exit();                
        }
        //check if subtotal > 0, shipping >= 0, handling >= 0, tax >= 0, totalfee > 0
        if($subtotal > 0 && $shippingfee >= 0 && $handlingfee >= 0 && $tax >= 0 && $totalfee > 0) {
        } else {
            $message = "Save reservation to DB: Not saved. One or more fields are not valid in your reservation summary. subtotal: " . $subtotal . ", shipping fee: " . $shippingfee . ", handling fee: " . $handlingfee . ", tax: ". $tax . ", total fee: " . $totalfee;
            dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', $userid);
            echo esc_html($message);
            exit();            
        }                
        //validate if the subtotal is the sum of all reservation items price, prevent hackers from changing reservation data
        $shoppingcartitems = empty($_POST['shoppingcartitems']) ? '' : sanitize_text_field($_POST['shoppingcartitems']);
        $shoppingcartitems = strip_tags($shoppingcartitems);
        $shoppingcartitems = stripslashes($shoppingcartitems);
        $shoppingcartitemsArr = json_decode($shoppingcartitems, true);
        if($shoppingcartitems === '' || count($shoppingcartitemsArr) === 0) {echo "Shopping cart is empty.";exit();}        
        //error_log("at 12231, shoppingcartitems: " . $shoppingcartitems);
        $productidArr = array();
        $preparedStatementQuestionsMarkArr = array();
        $allorderproducts_propertyvalueidsArr = array();
        for($i=0; $i < count($shoppingcartitemsArr); $i++) {
            $productidArr[] = intval($shoppingcartitemsArr[$i]["id"]);;
            $preparedStatementQuestionsMarkArr[] = '?';
            $productpropertyvalueids = $shoppingcartitemsArr[$i]["propertyvalueids"];
            $productpropertyvalueidsArr = explode("|", $productpropertyvalueids);
            if(count($productpropertyvalueidsArr) > 0) {                                                                               
                for($j=0; $j < count($productpropertyvalueidsArr); $j++) {                                
                    $allorderproducts_propertyvalueidsArr[] = intval($productpropertyvalueidsArr[$j]);    
                }
            }
        }
        $productids = join(",", $productidArr);
        $preparedStatementQuestionsMarks = join(",", $preparedStatementQuestionsMarkArr);
        $allorderproducts_propertyvalueidsArr2 = array_unique($allorderproducts_propertyvalueidsArr);        
        $allorderproducts_propertyvalueids = join(",", $allorderproducts_propertyvalueidsArr2);
        $allorderproducts_propertyvalueidsArr = null;
        //error_log("at 12251, subtotal: " . $subtotal);
        $query = "SELECT a.name, b.name as 'settingname', b.value from $table_name13 a RIGHT JOIN $table_name7 b ON  CAST(b.value AS UNSIGNED) = a.id ";
        $query .= " WHERE b.name IN ('ENABLE_PRODUCT_QUANTITY_AUTO_DEDUCT', 'RESERVE_NEED_ADMIN_APPROVE', 'MAX_PROMOTION_PER_ORDER',";
        $query .= " 'MAX_DISCOUNT_PER_ORDER','MAX_COUPON_PER_ORDER','EMAIL_METHOD','MAILGUN_APIKEY','MAILGUN_DOMAIN','MAILGUN_API_URL','MAILGUN_FROMNAME',";
        $query .= " 'MAILCHIMP_APIKEY','MAILCHIMP_API_URL','MAILCHIMP_FROMEMAIL','MAILCHIMP_FROMNAME','SENDGRID_APIKEY','SENDGRID_API_URL','SENDGRID_FROMEMAIL','SENDGRID_FROMNAME') ";
        $result = $wpdb->get_results($query);                
        if(count($result) > 0) {
            for($i=0; $i<count($result); $i++) {
                if($result[$i]->settingname === 'EMAIL_METHOD') {
                   $setting_email_method = $result[$i]->name;
                } elseif($result[$i]->settingname === 'MAILGUN_APIKEY') {
                   $mailgun_api_key = $result[$i]->value;
                } elseif($result[$i]->settingname === 'MAILGUN_API_URL') {
                   $mailgun_api_url = $result[$i]->value;
                } elseif($result[$i]->settingname === 'MAILGUN_DOMAIN') {
                   $mailgun_domain = $result[$i]->value;
                } elseif($result[$i]->settingname === 'MAILGUN_FROMNAME') {
                   $mailgun_fromname = $result[$i]->value;
                } elseif($result[$i]->settingname === 'MAX_PROMOTION_PER_ORDER') {
                   $MAX_PROMOTION_PER_ORDER = intval($result[$i]->value);
                } elseif($result[$i]->settingname === 'MAX_DISCOUNT_PER_ORDER') {
                   $MAX_DISCOUNT_PER_ORDER = intval($result[$i]->value);
                } elseif($result[$i]->settingname === 'MAX_COUPON_PER_ORDER') {
                   $MAX_COUPON_PER_ORDER = intval($result[$i]->value);
                } elseif($result[$i]->settingname === 'RESERVE_NEED_ADMIN_APPROVE') {
                   $RESERVE_NEED_ADMIN_APPROVE = intval($result[$i]->value);
                } elseif($result[$i]->settingname === 'ENABLE_PRODUCT_QUANTITY_AUTO_DEDUCT') {
                   $ENABLE_PRODUCT_QUANTITY_AUTO_DEDUCT = intval($result[$i]->value);
                } elseif($result[$i]->settingname === 'MAILCHIMP_APIKEY') {
                   $mailchimp_api_key = $result[$i]->value;
                } elseif($result[$i]->settingname === 'MAILCHIMP_API_URL') {
                   $mailchimp_api_url = $result[$i]->value;
                } elseif($result[$i]->settingname === 'MAILCHIMP_FROMEMAIL') {
                   $mailchimp_fromemail = $result[$i]->value;
                } elseif($result[$i]->settingname === 'MAILCHIMP_FROMNAME') {
                   $mailchimp_fromname = $result[$i]->value;
                } elseif($result[$i]->settingname === 'SENDGRID_APIKEY') {
                   $sendgrid_api_key = $result[$i]->value;
                } elseif($result[$i]->settingname === 'SENDGRID_API_URL') {
                   $sendgrid_api_url = $result[$i]->value;
                } elseif($result[$i]->settingname === 'SENDGRID_FROMEMAIL') {
                   $sendgrid_fromemail = $result[$i]->value;
                } elseif($result[$i]->settingname === 'SENDGRID_FROMNAME') {
                   $sendgrid_fromname = $result[$i]->value;
                }                                            
            }
        }
        $result = null;    
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                $message = "Save reservation to DB: Not saved. Connection failed: " . esc_html($wpdb->dbh->connect_error);
                dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', intval($current_user->data->ID));
                echo esc_html($message);
                exit();
            }            
            //if $RESERVE_NEED_ADMIN_APPROVE == 1, check db if this user is activated and has been approved by admin
            if($RESERVE_NEED_ADMIN_APPROVE === 1) {
                $result = $wpdb->get_results("SELECT user_status,admin_approved FROM $table_name14 WHERE userid = " . $userid . ' LIMIT 1');
                $user_status = 0;         
                $admin_approved = 0;
                if(count($result) === 1) {
                    for($i=0; $i<count($result); $i++) {
                        $user_status = intval($result[$i]->user_status);
                        $admin_approved = intval($result[$i]->admin_approved);                        
                    }
                }
                if($user_status !== 1 || $admin_approved !== 1) {
                    $message = "Save reservation to DB: Not saved. RESERVE_NEED_ADMIN_APPROVE is 1. But, user_status: " . $user_status . ", admin_approved: " . $admin_approved;
                    dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', $userid);
                    echo esc_html($message);                    
                    exit();                    
                }    
            }            
            $query = "SELECT distinct p.id, p.name, p.isonsale, p.quantity 'productquantity',p.price, p.saleprice, p.istaxfree, "
                    . " p.onsalestartdateutc, p.onsaleenddateutc, ppv.propertyvalueids, ppv.quantity "
                    . " FROM $table_name6 p LEFT JOIN $table_name15 ppv ON p.id = ppv.productid and ppv.status = 1 "                     
                    . " WHERE p.id IN ( " . $preparedStatementQuestionsMarks . " ) and p.status = 1 order by p.id, ppv.id";
            $stmt6 = $wpdb->dbh->prepare($query); 
            $types = ''; 
            $parameterArray = array('');            
            for($i = 0; $i < count($productidArr); $i++) {
                $types .= 'i';
                $parameterArray[] = &$productidArr[$i];            
            }                                    
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt6, 'bind_param'), $parameterArray);            
            $stmt6->execute();
            $myresult = $stmt6->get_result();
            $result6 = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt6->close();
            //if product isonsale = 1, onsalestartdateutc > UTC_TIMESTAMP() or a.onsaleenddateutc < UTC_TIMESTAMP(), then use price, not saleprice for customer to buy, isonsale set to 0 on the webpage
            //error_log("at 12342, result6: " . json_encode($result6));
            for ($i=0; $i<count($result6); $i++) {
                if($result6[$i]["isonsale"] === 1) {
                    if($result6[$i]["onsalestartdateutc"] !== null && $result6[$i]["onsalestartdateutc"] !== '' && $result6[$i]["onsalestartdateutc"] > gmdate("Y-m-d H:i:s")) {
                        $result6[$i]["isonsale"] = 0;
                    } elseif($result6[$i]["onsaleenddateutc"] !== null && $result6[$i]["onsaleenddateutc"] !== '' && $result6[$i]["onsaleenddateutc"] < gmdate("Y-m-d H:i:s")) {
                        $result6[$i]["isonsale"] = 0;
                    }                    
                }
            }
            
            //error_log("at 12353, result6: " . json_encode($result6) . ", productidArr: " . json_encode($productidArr) . ", preparedStatementQuestionsMarks: " . json_encode($preparedStatementQuestionsMarks));
            $subtotal_db = 0;
            $subtotalfortax_db = 0;
            $productquantityArr_db = array();
            $product_propertyvalueids_quantityArr_db = array();            
            for($i=0; $i < count($shoppingcartitemsArr); $i++) {
                $productid = intval($shoppingcartitemsArr[$i]["id"]);
                $productpropertyvalueids = $shoppingcartitemsArr[$i]["propertyvalueids"];
                $productdescription = $shoppingcartitemsArr[$i]["details"];                    
                $price = floatval($shoppingcartitemsArr[$i]["price"]);
                $isonsale = intval($shoppingcartitemsArr[$i]["isonsale"]);
                $istaxfree = intval($shoppingcartitemsArr[$i]["istaxfree"]);
                $quantity = intval($shoppingcartitemsArr[$i]["quantity"]);
                $arr_temp = strval($productid) . '_' . $productpropertyvalueids;                
                if($productid > 0 && is_numeric($price) && $price > 0 && $quantity >= 1){
                } else {
                    $message = "Save reservation to DB: Not saved. One shopping cart item has wrong product id, price or quantity. Product id: " . $productid . ", price: ". $price . ", quantity: " . $quantity;
                    dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', $userid);
                    echo esc_html($message);                    
                    exit();
                }
                //some product may have more records in _product_propertyvalue table than what this customer buys
                //and, some product may not have any records in _product_propertyvalue table
                //so, count($result6) and count($productidArr) can not compare which is bigger
                $found = false;
                for($j=0; $j<count($result6); $j++) {                                                
                    $result61 = $result6[$j];                
                    if($productid === $result61["id"] && (($productpropertyvalueids === '' && $result61["propertyvalueids"] === null) || $productpropertyvalueids === $result61["propertyvalueids"])) {
                        $found = true;
                        if(!isset($productquantityArr_db[strval($productid)])){
                            $productquantityArr_db[strval($productid)] = intval($result61["productquantity"]);
                        }
                        if(!isset($product_propertyvalueids_quantityArr_db[$arr_temp])){                        
                            $product_propertyvalueids_quantityArr_db[$arr_temp] = intval($result61["quantity"]);
                        }
                        if($result61["isonsale"] === $isonsale) {
                            if($result61["isonsale"] === 1) {
                                if(floatval($result61["saleprice"]) === $price && $price <= floatval($result61["price"])) {

                                } else {
                                    $message = "Save reservation to DB: Error. Not saved. This product is on sale, and its price should be sale price, which is lower than original price. User submits reservation data which shows it is " . ($isonsale ? "" : "not") . " on sale with price: " . $price  . ". From database, this product sale price is " . ($result61["saleprice"] === null ? '' : $result61["saleprice"]) . ", and price is " . $result61["price"] . ". Product id: " . $productid . ". ";
                                    dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', $userid);
                                    echo esc_html($message);                    
                                    exit();                            
                                }
                            } else {                                
                                if(floatval($result61["price"]) === $price) {
                                } else {
                                    $message = "Save reservation to DB: Error. Not saved. This product is not on sale, and its db price is different from user submitted product price. User submits reservation data which shows it is " . ($isonsale ? "" : "not") . " on sale with price: " . $price  . ". From database, this product sale price is " . ($result61["saleprice"] === null ? '' : $result61["saleprice"]) . ", and price is " . $result61["price"] . ". Product id: " . $productid . ". ";
                                    dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', $userid);
                                    echo esc_html($message);                    
                                    exit();                                
                                }                                    
                            }
                        } else {
                            $message = "Save reservation to DB: Error. Not saved. This product is on sale or not? User submits reservation data which shows it is " . ($isonsale ? "" : "not") . " on sale, but from database it is " . ($result61["isonsale"] ? "" : "not") . " on sale. Product id: " . $productid . ". ";
                            dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', $userid);
                            echo esc_html($message);                    
                            exit();                                
                        }                                                    
                        //if setting table set enable quantity
                        if($ENABLE_PRODUCT_QUANTITY_AUTO_DEDUCT === 1 && $result61["propertyvalueids"] !== null) {
                            if((!empty($result61["quantity"])) && intval($result61["quantity"]) > 0) {
                                if(intval($result61["quantity"]) < $quantity) {
                                    $message = "Save reservation to DB: One shopping cart item quantity is bigger than stock quantity. Customer submit product id: " . $productid . ", price: ". $price . ", quantity: " . $quantity;
                                    dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', $userid);
                                    $message2 = "Sorry. One shopping cart item " . $result61["name"] . " quantity " . $quantity . " is bigger than stock quantity " . $result61["quantity"] . ". Please reduce your quantity and try again. Not saved. ";
                                    echo esc_html($message2);                    
                                    exit();                            
                                }                                    
                            }
                        }
                        $subtotal_db += $quantity * $price;
                        if($result61["istaxfree"] === $istaxfree) {
                            if($istaxfree === 1) {
                            } else {
                                $subtotalfortax_db += $quantity * $price;
                            }                                
                        }                            
                    }                        
                }
                if(!$found) {
                    $message = "Save reservation to DB: Error. This product id " . $productid . " or propertyvalueids " . $productpropertyvalueids . " is not found in db. ";
                    if($isonsale !== $result61["isonsale"]) {
                        $message .= "User submits reservation data which shows it is " . ($isonsale ? "" : "not") . " on sale, but from database it is " . ($result61["isonsale"] ? "" : "not") . " on sale. ";
                    }
                    $message .= "Not saved. ";
                    dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', $userid);
                    echo esc_html($message);                    
                    exit();                        
                }                
            }
            //error_log("at 12445, before reducing discount and coupon, subtotal_db: " . $subtotal_db . ", subtotalfortax_db: " . $subtotalfortax_db);            
            //at this time, $subtotal_db is not reduced by discount and coupon
            if($subtotal !== $subtotal_db && abs($subtotal_db - $subtotal) >= 0.005) {
                $message = "Save reservation to DB: Calculated subtotal is different from subtotal submitted from user data: calculated subtotal: " . $subtotal_db . ", subtotal submitted from user data: " . $subtotal . ". Not saved. ";
                dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', $userid);
                echo esc_html($message);
                exit();                
            }                                                                            
            $query = "SELECT gp.propertyid, g.groupcategoryid, s.name AS 'settingname', s.value AS 'settingvalue', p.chargetypeid, p.shownname AS 'propertyname',pv.id AS 'propertyvalueid', pv.name AS 'propertyvaluename', "
                    . " pv.usefee,pv.minordersubtotal,pv.userate,pv.code,pv.fee,pv.rate,pv.description,pv.taxincludeshipping,pv.taxincludehandling,pv.tocountryid,pv.tostateprovinceid,pv.shownname "
                    . " FROM $table_name12 g "
                    . " join $table_name7 s "
                    . " ON g.groupcategoryid = CAST(s.value AS UNSIGNED) "
                    . " AND g.status = 1 "                    
                    . " join $table_name8 gp "
                    . " ON gp.groupid = g.id "
                    . " left join $table_name9 pv "
                    . " ON gp.propertyid = pv.propertyid "
                    . " AND pv.status = 1 "                                        
                    . " AND (pv.start is null or pv.start = '' or pv.start <= UTC_TIMESTAMP()) "    
                    . " AND (pv.end is null or pv.end = '' or pv.end >= UTC_TIMESTAMP()) "                                        
                    . " join $table_name10 p "
                    . " ON gp.propertyid = p.id "    
                    . " AND p.status = 1"                            
                    . " AND p.shownname IS NOT NULL"
                    . " WHERE ((p.chargetypeid = (SELECT id from $table_name11 WHERE id is not null and name = 'location' LIMIT 1) AND pv.tocountryid = (SELECT id FROM $table_name3 WHERE abbreviation = ? LIMIT 1)  AND pv.tostateprovinceid = ?)"
                    . " OR (p.chargetypeid is null OR p.chargetypeid != (SELECT id from $table_name11 WHERE id is not null and name = 'location' LIMIT 1))) "    
                    . " AND (" 
                    . " (s.name = 'GROUP_CATEGORY_ID_FOR_ORDER_SHIPPING_DETAILS' "    
                    . " AND pv.id = ? AND g.id = (SELECT CAST(value AS UNSIGNED) from $table_name7 WHERE name = 'GROUP_ID_FOR_ORDER_SHIPPING_DETAILS')) "
                    . " OR "
                    . " (s.name = 'GROUP_CATEGORY_ID_FOR_ORDER_HANDLING_DETAILS' "
                    . " AND pv.id = ? AND g.id = (SELECT CAST(value AS UNSIGNED) from $table_name7 WHERE name = 'GROUP_ID_FOR_ORDER_HANDLING_DETAILS')) "
                    . " OR (s.name = 'GROUP_CATEGORY_ID_FOR_ORDER_TAX_DETAILS' AND pv.id = ? ) "
                    . " OR s.name = 'GROUP_CATEGORY_ID_FOR_DISCOUNT' "        
                    . " OR s.name = 'GROUP_CATEGORY_ID_FOR_COUPON') "                                
                    . " order by pv.id ";
            $stmt = $wpdb->dbh->prepare($query);
            $stmt->bind_param("siiii", $shippingcountryalpha2, $shippingprovinceid, $shippingid, $handlingid, $taxid);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $result2 = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            $stmt = null;
            $myresult = null;

            $result3 = array();            
            foreach($result2 as $temp) {
                if(!empty($temp["minordersubtotal"])) {
                    if($subtotal >= floatval($temp["minordersubtotal"])) {
                        $result3[] = $temp;
                    }
                } elseif(floatval($temp["minordersubtotal"]) == 0) {
                    $result3[] = $temp;
                }
            }
            $result2 = null;                                
            $query = "SELECT pv.id AS 'propertyvalueid',p.shownname AS 'propertyname',pv.shownname FROM $table_name9 pv LEFT JOIN $table_name10 p ON pv.propertyid = p.id WHERE "
                     . ($allorderproducts_propertyvalueids !== '' ? (" pv.id IN ( "    . $allorderproducts_propertyvalueids . ") ")    : "");                                
            $stmt = $wpdb->dbh->prepare($query);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $result4 = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            $stmt = null;
            $myresult = null;
            $allorderproducts_property_propertyvalue_id2nameArr = array();            
            foreach($result4 as $temp) {
                if(in_array(intval($temp["propertyvalueid"]), $allorderproducts_propertyvalueidsArr2)) {
                    $pvid = strval($temp["propertyvalueid"]);
                    $allorderproducts_property_propertyvalue_id2nameArr[$pvid] = $temp["propertyname"] . ': ' . $temp["shownname"];
                }
            }
            $result4 = null;                                
            $allorderproducts_propertyvalueidsArr2 = null;
            //error_log("at 12520, result3: ". json_encode($result3));
            //error_log("at 12521, allorderproducts_property_propertyvalue_id2nameArr: ". json_encode($allorderproducts_property_propertyvalue_id2nameArr));
            $discountArr = [];
            $couponArr = [];        
            for($i=0; $i < count($result3); $i++) {
                if($result3[$i]["settingname"] === 'GROUP_CATEGORY_ID_FOR_ORDER_SHIPPING_DETAILS') {
                    $shippingArr = $result3[$i];
                } elseif($result3[$i]["settingname"] === 'GROUP_CATEGORY_ID_FOR_ORDER_HANDLING_DETAILS') {
                    $handlingArr = $result3[$i];                            
                } elseif($result3[$i]["settingname"] === 'GROUP_CATEGORY_ID_FOR_ORDER_TAX_DETAILS') {
                    $taxArr = $result3[$i];                            
                } elseif($result3[$i]["settingname"] === 'GROUP_CATEGORY_ID_FOR_DISCOUNT') {                
                    if($MAX_PROMOTION_PER_ORDER === -1) {
                        if($MAX_DISCOUNT_PER_ORDER >= 0) {
                            if(count($discountArr) < $MAX_DISCOUNT_PER_ORDER) {
                                if($result3[$i]["usefee"] === 1) {
                                    //check if subtotal amount is big enough to get those coupon and discount
                                    if($result3[$i]["minordersubtotal"] != null && floatval($result3[$i]["minordersubtotal"]) <= $subtotal) {
                                        $temp = strval($result3[$i]["propertyvalueid"]);
                                        if(in_array($temp, $discountidsArr)) {
                                            $discountArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                        }
                                    } elseif($result3[$i]["minordersubtotal"] === null) {
                                        $temp = strval($result3[$i]["propertyvalueid"]);
                                        if(in_array($temp, $discountidsArr)) {
                                            $discountArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                        }                                    
                                    }
                                } elseif($result3[$i]["userate"] === 1) {
                                    //if discount is use rate, it also needs to have minordersubtotal <= $subtotal
                                    if($result3[$i]["minordersubtotal"] != null && floatval($result3[$i]["minordersubtotal"]) <= $subtotal) {    
                                        $temp = strval($result3[$i]["propertyvalueid"]);                                    
                                        if(in_array($temp, $discountidsArr)) {
                                            $discountArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                        }
                                    } elseif($result3[$i]["minordersubtotal"] === null) {
                                        $temp = strval($result3[$i]["propertyvalueid"]);
                                        if(in_array($temp, $discountidsArr)) {
                                            $discountArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                        }                                    
                                    }
                                }
                            }
                        } elseif($MAX_DISCOUNT_PER_ORDER === -1) {
                            if($result3[$i]["usefee"] === 1) {
                                //check if subtotal amount is big enough to get those coupon and discount
                                if($result3[$i]["minordersubtotal"] !== null && floatval($result3[$i]["minordersubtotal"]) <= $subtotal) {
                                    $temp = strval($result3[$i]["propertyvalueid"]);
                                    if(in_array($temp, $discountidsArr)) {
                                        $discountArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                    }
                                } elseif($result3[$i]["minordersubtotal"] === null) {
                                    $temp = strval($result3[$i]["propertyvalueid"]);
                                    if(in_array($temp, $discountidsArr)) {
                                        $discountArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                    }
                                }
                            } elseif($result3[$i]["userate"] === 1) {
                                if($result3[$i]["minordersubtotal"] !== null && floatval($result3[$i]["minordersubtotal"]) <= $subtotal) {    
                                    $temp = strval($result3[$i]["propertyvalueid"]);                                
                                    if(in_array($temp, $discountidsArr)) {
                                        $discountArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                    }
                                } elseif($result3[$i]["minordersubtotal"] === null) {
                                    $temp = strval($result3[$i]["propertyvalueid"]);
                                    if(in_array($temp, $discountidsArr)) {
                                        $discountArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                    }                                    
                                }
                            }
                        }                                
                    } elseif($MAX_PROMOTION_PER_ORDER > 0) {
                        if($MAX_DISCOUNT_PER_ORDER >= 0) {
                            if(count($discountArr) < $MAX_DISCOUNT_PER_ORDER) {
                                if($result3[$i]["usefee"] === 1) {
                                    //check if subtotal amount is big enough to get those coupon and discount
                                    if($result3[$i]["minordersubtotal"] !== null && floatval($result3[$i]["minordersubtotal"]) <= $subtotal) {
                                        $temp = strval($result3[$i]["propertyvalueid"]);
                                        if(in_array($temp, $discountidsArr)) {
                                            $discountArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                        }
                                    } elseif($result3[$i]["minordersubtotal"] === null) {
                                        $temp = strval($result3[$i]["propertyvalueid"]);
                                        if(in_array($temp, $discountidsArr)) {
                                            $discountArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                        }                                    
                                    }
                                } elseif($result3[$i]["userate"] === 1) {
                                    if($result3[$i]["minordersubtotal"] !== null && floatval($result3[$i]["minordersubtotal"]) <= $subtotal) {
                                        $temp = strval($result3[$i]["propertyvalueid"]);                                            
                                        if(in_array($temp, $discountidsArr)) {
                                            $discountArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                        }
                                    } elseif($result3[$i]["minordersubtotal"] === null) {
                                        $temp = strval($result3[$i]["propertyvalueid"]);
                                        if(in_array($temp, $discountidsArr)) {
                                            $discountArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                        }                                    
                                    }                                
                                }
                            }
                        } elseif($MAX_DISCOUNT_PER_ORDER === -1) {
                            if($result3[$i]["usefee"] === 1) {
                                //check if subtotal amount is big enough to get those coupon and discount
                                if($result3[$i]["minordersubtotal"] !== null && floatval($result3[$i]["minordersubtotal"]) <= $subtotal) {
                                    $temp = strval($result3[$i]["propertyvalueid"]);
                                    if(in_array($temp, $discountidsArr)) {
                                        $discountArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                    }
                                } elseif($result3[$i]["minordersubtotal"] === null) {
                                    $temp = strval($result3[$i]["propertyvalueid"]);
                                    if(in_array($temp, $discountidsArr)) {
                                        $discountArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                    }                                    
                                }
                            } elseif($result3[$i]["userate"] === 1) {
                                if($result3[$i]["minordersubtotal"] !== null && floatval($result3[$i]["minordersubtotal"]) <= $subtotal) {    
                                    $temp = strval($result3[$i]["propertyvalueid"]);                                    
                                    if(in_array($temp, $discountidsArr)) {
                                        $discountArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                    }
                                } elseif($result3[$i]["minordersubtotal"] === null) {
                                    $temp = strval($result3[$i]["propertyvalueid"]);
                                    if(in_array($temp, $discountidsArr)) {
                                        $discountArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                    }                                    
                                }
                            }
                        }
                    }                                                                                                                                        
                } elseif($result3[$i]["settingname"] === 'GROUP_CATEGORY_ID_FOR_COUPON') {                    
                    if($MAX_PROMOTION_PER_ORDER === -1) {
                        if($MAX_COUPON_PER_ORDER >= 0) {
                            if(count($couponArr) < $MAX_COUPON_PER_ORDER) {
                                if($result3[$i]["usefee"] === 1) {
                                    //check if subtotal amount is big enough to get those coupon and discount
                                    if($result3[$i]["minordersubtotal"] !== null && floatval($result3[$i]["minordersubtotal"]) <= $subtotal) {
                                        $temp = strval($result3[$i]["propertyvalueid"]);
                                        if(in_array($temp, $couponidsArr)) {
                                            $couponArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                        }
                                    } elseif($result3[$i]["minordersubtotal"] !== null && floatval($result3[$i]["minordersubtotal"]) > $subtotal) {
                                    } elseif($result3[$i]["minordersubtotal"] === null) {
                                        $temp = strval($result3[$i]["propertyvalueid"]);
                                        if(in_array($temp, $discountidsArr)) {
                                            $discountArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                        }                                    
                                    }
                                } elseif($result3[$i]["userate"] === 1) {
                                    if($result3[$i]["minordersubtotal"] !== null && floatval($result3[$i]["minordersubtotal"]) <= $subtotal) {
                                        $temp = strval($result3[$i]["propertyvalueid"]);
                                        if(in_array($temp, $couponidsArr)) {
                                            $couponArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                        }
                                    } elseif($result3[$i]["minordersubtotal"] === null) {
                                        $temp = strval($result3[$i]["propertyvalueid"]);
                                        if(in_array($temp, $discountidsArr)) {
                                            $discountArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                        }                                    
                                    }
                                }
                            }
                        } elseif($MAX_COUPON_PER_ORDER === -1) {
                            if($result3[$i]["usefee"] === 1) {
                                //check if subtotal amount is big enough to get those coupon and discount
                                if($result3[$i]["minordersubtotal"] !== null && floatval($result3[$i]["minordersubtotal"]) <= $subtotal) {
                                    $temp = strval($result3[$i]["propertyvalueid"]);
                                    if(in_array($temp, $couponidsArr)) {
                                        $couponArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                    }
                                } elseif($result3[$i]["minordersubtotal"] !== null && floatval($result3[$i]["minordersubtotal"]) > $subtotal) {
                                } elseif($result3[$i]["minordersubtotal"] === null) {
                                    $temp = strval($result3[$i]["propertyvalueid"]);
                                    if(in_array($temp, $discountidsArr)) {
                                        $discountArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                    }                                    
                                }
                            } elseif($result3[$i]["userate"] === 1) {
                                if($result3[$i]["minordersubtotal"] !== null && floatval($result3[$i]["minordersubtotal"]) <= $subtotal) {
                                    $temp = strval($result3[$i]["propertyvalueid"]);
                                    if(in_array($temp, $couponidsArr)) {
                                        $couponArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                    }
                                } elseif($result3[$i]["minordersubtotal"] === null) {
                                    $temp = strval($result3[$i]["propertyvalueid"]);
                                    if(in_array($temp, $discountidsArr)) {
                                        $discountArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                    }                                    
                                }
                            }
                        }                        
                    } elseif($MAX_PROMOTION_PER_ORDER > 0) {
                        if($MAX_COUPON_PER_ORDER >= 0) {
                            if(count($couponArr) < $MAX_COUPON_PER_ORDER) {
                                if($result3[$i]["usefee"] === 1) {
                                    //check if subtotal amount is big enough to get those coupon and discount
                                    if($result3[$i]["minordersubtotal"] !== null && floatval($result3[$i]["minordersubtotal"]) <= $subtotal) {
                                        $temp = strval($result3[$i]["propertyvalueid"]);
                                        if(in_array($temp, $couponidsArr)) {
                                            $couponArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                        }
                                    } elseif($result3[$i]["minordersubtotal"] !== null && floatval($result3[$i]["minordersubtotal"]) > $subtotal) {
                                    } elseif($result3[$i]["minordersubtotal"] === null) {
                                        $temp = strval($result3[$i]["propertyvalueid"]);
                                        if(in_array($temp, $discountidsArr)) {
                                            $discountArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                        }                                    
                                    }
                                } elseif($result3[$i]["userate"] === 1) {
                                    if($result3[$i]["minordersubtotal"] !== null && floatval($result3[$i]["minordersubtotal"]) <= $subtotal) {
                                        $temp = strval($result3[$i]["propertyvalueid"]);
                                        if(in_array($temp, $couponidsArr)) {
                                            $couponArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                        }
                                    } elseif($result3[$i]["minordersubtotal"] === null) {
                                        $temp = strval($result3[$i]["propertyvalueid"]);
                                        if(in_array($temp, $discountidsArr)) {
                                            $discountArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                        }                                    
                                    }
                                }
                            }
                        } elseif($MAX_COUPON_PER_ORDER === -1) {
                            if($result3[$i]["usefee"] === 1) {
                                //check if subtotal amount is big enough to get those coupon and discount
                                if($result3[$i]["minordersubtotal"] !== null && floatval($result3[$i]["minordersubtotal"]) <= $subtotal) {
                                    $temp = strval($result3[$i]["propertyvalueid"]);
                                    if(in_array($temp, $couponidsArr)) {
                                        $couponArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                    }
                                } elseif($result3[$i]["minordersubtotal"] !== null && floatval($result3[$i]["minordersubtotal"]) > $subtotal) {
                                } elseif($result3[$i]["minordersubtotal"] === null) {
                                    $temp = strval($result3[$i]["propertyvalueid"]);
                                    if(in_array($temp, $discountidsArr)) {
                                        $discountArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                    }                                    
                                }
                            } elseif($result3[$i]["userate"] === 1) {
                                if($result3[$i]["minordersubtotal"] !== null && floatval($result3[$i]["minordersubtotal"]) <= $subtotal) {
                                    $temp = strval($result3[$i]["propertyvalueid"]);
                                    if(in_array($temp, $couponidsArr)) {
                                        $couponArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                    }
                                } elseif($result3[$i]["minordersubtotal"] === null) {
                                    $temp = strval($result3[$i]["propertyvalueid"]);
                                    if(in_array($temp, $discountidsArr)) {
                                        $discountArr[] = json_encode($result3[$i]);$result3[$i]=null;
                                    }                                    
                                }
                            }
                        }
                    }                    
                }
            }
            $result3 = null;
            while($MAX_PROMOTION_PER_ORDER > 0 && (count($discountArr) + count($couponArr)) > $MAX_PROMOTION_PER_ORDER) {
                //first, remove coupon item
                if(count($couponArr) > 0) {
                    array_pop($couponArr);
                } elseif(count($discountArr) > 0) {
                    array_pop($discountArr);
                }                
            }
            //check if the POSTed shippingid(must be >0, even if the shipping fee is 0), handlingid(optional), taxid (must be >0), discountids, couponids are the correct ones            
            if($ENABLE_SHIPPING_CHARGE === 1 && (empty($shippingArr) || $shippingArr["propertyvalueid"] <= 0 || $shippingArr["propertyvalueid"] !== $shippingid)) {
                $message = "Save reservation to DB: Shipping  is wrong. Not saved. Shipping details: " . (empty($shippingArr) ? 'empty' : json_encode($shippingArr));
                dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', $userid);
                echo esc_html($message);                    
                exit();                
            }            
            if($ENABLE_HANDLING_CHARGE === 1 && (empty($handlingArr) || $handlingArr["propertyvalueid"] <= 0 || $handlingArr["propertyvalueid"] !== $handlingid)) {
                $message = "Save reservation to DB: Handling is wrong. Not saved. Handling details: " . (empty($handlingArr) ? 'empty' : json_encode($handlingArr));
                dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', $userid);
                echo esc_html($message);                    
                exit();                
            }
            if(empty($taxArr) || $taxArr["propertyvalueid"] <= 0 || $taxArr["propertyvalueid"] !== $taxid) {
                $message = "Save reservation to DB: Tax is wrong. Not saved. Tax details: " . (empty($taxArr) ? 'empty' : json_encode($taxArr));
                dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', $userid);
                echo esc_html($message);                    
                exit();                
            }
            //$discountids, $discountidsArr are from customer submit data. $discountArr is from database
            if(count($discountidsArr) > count($discountArr)) {
                $message = "Save reservation to DB: Discount is wrong. Not saved. You submitted discount IDs: " . (empty($discountidsArr) ? 'empty' : json_encode($discountidsArr)) . ". Discount details from database: " . (empty($discountArr) ? 'empty' : json_encode($discountArr));
                dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', $userid);
                echo esc_html($message);                    
                exit();                    
            } else {//compare if all the ids are the same
                if(count($discountidsArr) !== 0) {
                    foreach($discountidsArr as $discountid) {
                        $found = false;
                        foreach($discountArr as $val) {
                            $val_temp = json_decode($val, true);
                            if(intval($discountid) === $val_temp["propertyvalueid"]) {
                                $found = true;break;
                            }
                        }
                        if(!$found) {
                            $message = "Save reservation to DB: Discount is wrong. Not saved. You submitted discount IDs: " . (empty($discountidsArr) ? 'empty' : json_encode($discountidsArr)) . ". Discount details from database: " . (empty($discountArr) ? 'empty' : json_encode($discountArr));
                            dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', $userid);
                            echo esc_html($message);                    
                            exit();                            
                        }
                    }
                }
            }
            //$couponids are customer submitted, $couponArr are from database query            
            //$couponids, $couponidsArr are from customer submit data. $couponArr is from database
            if(count($couponidsArr) > count($couponArr)) {
                $message = "Save reservation to DB: Coupon is wrong. Not saved. You submitted coupon IDs: " . (empty($couponidsArr) ? 'empty' : json_encode($couponidsArr)) . ". Coupon details from database: " . (empty($couponArr) ? 'empty' : json_encode($couponArr));
                dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', $userid);
                echo esc_html($message);                    
                exit();                    
            } else {//compare if all the ids belong to the ids from the db
                if(count($couponidsArr) !== 0) {
                    foreach($couponidsArr as $couponid) {
                        $found = false;
                        foreach($couponArr as $val) {
                            $val_temp = json_decode($val, true);
                            if(intval($couponid) === $val_temp["propertyvalueid"]) {
                                $found = true;break;
                            }
                        }
                        if(!$found) {
                            $message = "Save reservation to DB: Coupon is wrong. Not saved. You submitted coupon IDs: " . (empty($couponidsArr) ? 'empty' : json_encode($couponidsArr)) . ". Coupon details from database: " . (empty($couponArr) ? 'empty' : json_encode($couponArr));
                            dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', $userid);
                            echo esc_html($message);                    
                            exit();                            
                        }
                    }                    
                }                
            }            
            //error_log("at 12853, shippingArr: " . json_encode($shippingArr));            
            //error_log("at 12854, handlingArr: " . json_encode($handlingArr));    
            //error_log("at 12855, taxArr: " . json_encode($taxArr));                                
            //check if the shipping fee, handling fee(if setting table set it to on, check it), tax are reasonable, based on time or location or weight
            //server side calculate tax, see if it's the same as customer submit tax value
            //$taxArr[$i]["taxincludeshipping"] = 1/0
            //$taxArr[$i]["taxincludehandling"] = 1/0            
            //get shippingfee, handlingfeee, tax from _propertyvalue table. tax could be taxincludeshipping = 0 or taxincludehandling = 0
            //tax should be charged after the discount and coupon is applied        
            $shipping = 0;
            $handling = 0;            
            $mydiscountfee = 0;        
            $mycouponfee = 0;
            $taxrate = floatval($taxArr["rate"]);
            $mytax = 0;
            $myreducedfeebydiscount = 0;
            $myreducedfeebycoupon = 0;
            $myreducedfeebydiscountfortax = 0;
            $myreducedfeebycouponfortax = 0;            
            if($shippingArr["usefee"] === 1) {
                $shipping = floatval($shippingArr["fee"]);
            } elseif($shippingArr["userate"] === 1) {
                $shipping = floatval($shippingArr["rate"]);            
            }
            if($handlingArr["usefee"] === 1) {
                $handling = floatval($handlingArr["fee"]);
            } elseif($shippingArr["userate"] === 1) {
                $handling = floatval($handlingArr["rate"]);            
            }        
            //discount: fee, rate, usefee, userate
            //coupon: fee, rate, usefee, userate            
            if(count($discountArr) > 0) {
                for($i=0; $i<count($discountArr); $i++) {
                    $val_temp = json_decode($discountArr[$i], true);
                    if($val_temp["usefee"] === 1) {
                        $mydiscountfee += floatval($val_temp["fee"]);
                    } elseif($val_temp["userate"] === 1) {
                        $mydiscountrate = floatval($val_temp["rate"]);
                        if($mydiscountrate >= 1 || $mydiscountrate <= 0) {
                            $message = "Save reservation to DB: Discount is not correct: " . $mydiscountrate . ". Not saved. Please contact website admin.";
                            dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', $userid);
                            echo esc_html($message);                    
                            exit();
                        }
                        $myreducedfeebydiscount += $subtotal_db * (1 - $mydiscountrate);
                        $myreducedfeebydiscountfortax += $subtotalfortax_db * (1 - $mydiscountrate);
                    }                
                }
            }                
            if(count($couponArr) > 0) {
                for($i=0; $i<count($couponArr); $i++) {
                    $val_temp = json_decode($couponArr[$i], true);
                    if($val_temp["usefee"] === 1) {
                        $mycouponfee += floatval($val_temp["fee"]);
                    } elseif($val_temp["userate"] === 1) {
                        $mycouponrate = floatval($val_temp["rate"]);
                        if($mycouponrate >= 1 || $mycouponrate <= 0) {
                            $message = "Save reservation to DB: Coupon is not correct: " . $mycouponrate . ". Not saved. Please contact website admin.";
                            dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', $userid);
                            echo esc_html($message);                    
                            exit();
                        }
                        $myreducedfeebycoupon += $subtotal_db * (1 - $mycouponrate);
                        $myreducedfeebycouponfortax += $subtotalfortax_db * (1 - $mycouponrate);
                    }                
                }
            }
            //error_log("at 12920, couponArr: " . json_encode($couponArr));    
            if($mydiscountfee !== 0) {
                $subtotal_db = $subtotal_db - $mydiscountfee;
                if($subtotalfortax_db > 0) {
                    $subtotalfortax_db = $subtotalfortax_db - $mydiscountfee;
                }
            }            
            if($mycouponfee !== 0) {
                $subtotal_db = $subtotal_db - $mycouponfee;
                if($subtotalfortax_db > 0) {                
                    $subtotalfortax_db = $subtotalfortax_db - $mycouponfee;
                }                
            }
            $subtotal_db = $subtotal_db - $myreducedfeebydiscount - $myreducedfeebycoupon;                    
            if($subtotal_db < 0) {
                $message = "Save reservation to DB: Discount and coupon are not correct. Subtotal after discount and coupon: " . $subtotal_db . ". Not saved. Please contact website admin.";
                dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', $userid);
                echo esc_html($message);                    
                exit();
            }
            if($subtotalfortax_db > 0 && $myreducedfeebydiscountfortax >= 0 && $myreducedfeebycouponfortax >= 0) {
                $subtotalfortax_db = $subtotalfortax_db - $myreducedfeebydiscountfortax - $myreducedfeebycouponfortax;
            }
            if($myreducedfeebydiscountfortax < 0) {
                $message = "Save reservation to DB: Reduced fee by discount for tax is negative:  " . $myreducedfeebydiscountfortax . ". Not saved. Please contact website admin.";
                dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', $userid);
                echo esc_html($message);                    
                exit();
            }
            if($myreducedfeebycouponfortax < 0) {
                $message = "Save reservation to DB: Reduced fee by coupon for tax is negative:  " . $myreducedfeebycouponfortax . ". Not saved. Please contact website admin.";
                dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', $userid);
                echo esc_html($message);                    
                exit();                
            }
            if($subtotalfortax_db < 0) {
                $message = "Save reservation to DB: Discount and coupon are not correct. Subtotalfortax after discount and coupon:  " . $subtotalfortax_db . ". Not saved. Please contact website admin.";
                dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', $userid);
                echo esc_html($message);                    
                exit();
            }        
            //tax should be charged after the discount and coupon are applied
            if($taxArr["taxincludeshipping"] === 1) {
                if($ENABLE_SHIPPING_CHARGE === 1) {
                    if($taxArr["taxincludehandling"] === 1) {
                        if($ENABLE_HANDLING_CHARGE === 1) {
                            $mytax = ($subtotalfortax_db * $taxrate) + ($shipping * $taxrate) + ($handling * $taxrate);
                        } else {
                            $mytax = ($subtotalfortax_db * $taxrate) + ($shipping * $taxrate);
                        }
                    } else {
                        $mytax = ($subtotalfortax_db * $taxrate) + ($shipping * $taxrate);
                    }            
                } else {
                    if($taxArr["taxincludehandling"] === 1) {
                        if($ENABLE_HANDLING_CHARGE === 1) {
                            $mytax = ($subtotalfortax_db * $taxrate) + ($handling * $taxrate);
                        } else {
                            $mytax = ($subtotalfortax_db * $taxrate);
                        }
                    } else {
                        $mytax = ($subtotalfortax_db * $taxrate);
                    }                        
                }
            } else {
                if($taxArr["taxincludehandling"] === 1) {
                    if($ENABLE_HANDLING_CHARGE === 1) {
                        $mytax = ($subtotalfortax_db * $taxrate) + ($handling * $taxrate);
                    } else {
                        $mytax = ($subtotalfortax_db * $taxrate);
                    }
                } else {
                    $mytax = $subtotalfortax_db * $taxrate;
                }            
            }
            if($mytax >= 0) {
                $mytotal = $subtotal_db + $shipping + $handling + $mytax;
                if($mytotal < 0) {
                    $message = "Save reservation to DB: Total is not correct: " . $mytotal . ". Not saved. Please contact website admin.";
                    dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', $userid);
                    echo esc_html($message);                    
                    exit();
                }
            } else {
                $message = "Save reservation to DB: Tax calculation is negative value: " . $mytax . ". Not saved. Please contact website admin.";
                dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', $userid);
                echo esc_html($message);                    
                exit();
            }                        
            //error_log("at 13009, after reduce, subtotal_db: " . $subtotal_db . ", subtotalfortax_db: " . $subtotalfortax_db);
            //error_log("at 13010, mydiscountfee: " . $mydiscountfee . ", myreducedfeebydiscount: " . $myreducedfeebydiscount . ", myreducedfeebydiscountfortax: " . $myreducedfeebydiscountfortax);
            //error_log("at 13011, mycouponfee: " . $mycouponfee . ", myreducedfeebycoupon: " . $myreducedfeebycoupon . ", myreducedfeebycouponfortax: " . $myreducedfeebycouponfortax);            
            if($shippingfee !== $shipping && abs($shippingfee - $shipping) >= 0.005) {
                $message = "Save reservation to DB: Calculated shipping fee is different from shipping fee submitted from user data: calculated shipping fee: " . $shipping . ", shipping fee submitted from customer: " . $shippingfee . ". Not saved. ";
                dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', $userid);
                echo esc_html($message);
                exit();                
            }
            if($handlingfee !== $handling && abs($handlingfee - $handling) >= 0.005) {
                $message = "Save reservation to DB: Calculated handling fee is different from handling fee submitted from user data: calculated handling fee: " . $handling . ", handling fee submitted from customer: " . $handlingfee . ". Not saved. ";
                dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', $userid);
                echo esc_html($message);
                exit();
            }
            if($tax !== $mytax && abs($tax - $mytax) >= 0.005) {
                $message = "Save reservation to DB: Calculated tax is different from tax submitted from user data: calculated tax: " . $mytax . ", tax submitted from customer: " . $tax . ". ";
                dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', $userid);
                echo esc_html($message);
                exit();                
            }            
            if($totalfee !== $mytotal && abs($totalfee - $mytotal) >= 0.005) {
                $message = "Save reservation to DB: Calculated total fee is different from total fee submitted from user data: calculated total fee: " . $mytotal . ", total fee submitted from customer: " . $totalfee . ". Not saved. ";
                dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', $userid);
                echo esc_html($message);
                exit();                
            }            
            $shippingdescription2 = empty($shippingArr["shownname"]) ? $shippingArr["propertyvaluename"] : $shippingArr["shownname"];
            $handlingdescription2 = empty($handlingArr["shownname"]) ? $handlingArr["propertyvaluename"] : $handlingArr["shownname"];            
            
            //get coupon and discount details by id
            $discountidsArr2 = [];
            $discontdescriptionArr2 = [];
            $discontdescriptionforuserArr2 = [];            
            for($i=0; $i < count($discountArr); $i++) {
                $temp_discount = json_decode($discountArr[$i], true);
                $discountidsArr2[] = $temp_discount["propertyvalueid"];
                $temp_discountArr = array();
                $temp_discountArr["id"] = $temp_discount["propertyvalueid"];
                $temp_discountArr["name"] = $temp_discount["propertyvaluename"];
                $temp_discountArr["description"] = $temp_discount["description"];
                $temp_discountArr["usefee"] = $temp_discount["usefee"];
                $temp_discountArr["fee"] = $temp_discount["fee"];
                $temp_discountArr["userate"] = $temp_discount["userate"];
                $temp_discountArr["rate"] = $temp_discount["rate"];                        
                $discountobject = (object)$temp_discountArr;
                $discontdescriptionArr2[] = $discountobject;
                
                $temp_discountforuserArr = array();
                if($temp_discount["usefee"] === 1) {
                    $temp_discountforuserArr["usefee"] = $temp_discount["usefee"];
                    $temp_discountforuserArr["fee"] = $temp_discount["fee"];
                }
                if($temp_discount["userate"] === 1) {
                    $temp_discountforuserArr["userate"] = $temp_discount["userate"];
                    $temp_discountforuserArr["rate"] = $temp_discount["rate"];    
                }                        
                $discountforuserobject = (object)$temp_discountforuserArr;
                $discontdescriptionforuserArr2[] = $discountforuserobject;                        
            }
            $discountids2 = join("|", $discountidsArr2);
            $discountidsArr2 = null;
            $discountdescription2 = json_encode($discontdescriptionArr2);
            $discontdescriptionArr2 = null;
            $discountdescriptionforuser2 = json_encode($discontdescriptionforuserArr2);
            $discontdescriptionforuserArr2 = null;

            $couponidsArr2 = [];
            $coupondescriptionArr2 = [];
            $coupondescriptionforuserArr2 = [];            
            for($i=0; $i < count($couponArr); $i++) {
                $temp_coupon = json_decode($couponArr[$i], true);
                $couponidsArr2[] = $temp_coupon["propertyvalueid"];
                $temp_couponArr = array();
                $temp_couponArr["id"] = $temp_coupon["propertyvalueid"];
                $temp_couponArr["name"] = $temp_coupon["propertyvaluename"];
                $temp_couponArr["description"] = $temp_coupon["description"];
                $temp_couponArr["code"] = $temp_coupon["code"];
                if($temp_coupon["usefee"] === 1) {
                    $temp_couponArr["usefee"] = $temp_coupon["usefee"];
                    $temp_couponArr["fee"] = $temp_coupon["fee"];
                }
                if($temp_coupon["userate"] === 1) {
                    $temp_couponArr["userate"] = $temp_coupon["userate"];
                    $temp_couponArr["rate"] = $temp_coupon["rate"];
                }                        
                $couponobject = (object)$temp_couponArr;
                $coupondescriptionArr2[] = $couponobject;
                
                $temp_couponforuserArr = array();
                $temp_couponforuserArr["usefee"] = $temp_coupon["usefee"];
                $temp_couponforuserArr["fee"] = $temp_coupon["fee"];
                $temp_couponforuserArr["userate"] = $temp_coupon["userate"];
                $temp_couponforuserArr["rate"] = $temp_coupon["rate"];                        
                $couponforuserobject = (object)$temp_couponforuserArr;
                $coupondescriptionforuserArr2[] = $couponforuserobject;
            }                        

            $couponids2 = join("|", $couponidsArr2);
            $couponidsArr2 = null;
            $coupondescription2 = json_encode($coupondescriptionArr2);
            $coupondescriptionArr2 = null;
            $coupondescriptionforuser2 = json_encode($coupondescriptionforuserArr2);    
            $coupondescriptionforuserArr2 = null;
            $shippingcountryname = '';
            $stmt99 = $wpdb->dbh->prepare("SELECT name from $table_name3 Where abbreviation = ? LIMIT 1");
            $stmt99->bind_param("s", $shippingcountryalpha2);
            $stmt99->execute();
            $myresult = $stmt99->get_result();
            $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt99->close();    
            if(count($result) === 1) {
                $shippingcountryname = $result[0]["name"];
            }
            //end of validation. next step: begin transaction, insert into database                    
            try {
                $wpdb->dbh->begin_transaction();                                                                                                
                $query = "INSERT INTO " . $table_name . " (`status`,`discountfee`,`couponfee`,`isreserve`,`userid`,`shippingname`,`shippingaddress1`,`shippingaddress2`,`shippingcity`,`shippingstateprovinceid`,`shippingstateprovince`,`shippingcountryid`,`shippingcountry`,`shippingzippostalcode`,`shippingphonenumber`,`shippingemail`,`totalfee`,`subtotal`,`discountids`,`couponids`,`discountdescription`,`discountdescriptionforuser`,`coupondescription`,`coupondescriptionforuser`,`shippingfee`,`handlingfee`,`tax`,`shippingdescription`,`handlingdescription`,`createtimeutc`) VALUES ((SELECT id from " . $table_name16 . " Where name = 'reserved' LIMIT 1),?,?,1,?,?,?,?,?,?, (SELECT name from " . $table_name2 . " Where id = ? LIMIT 1), (SELECT id from " . $table_name3 . " Where abbreviation = ? LIMIT 1), (SELECT name from " . $table_name3 . " Where abbreviation = ? LIMIT 1), ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,UTC_TIMESTAMP())";
                $stmt = $wpdb->dbh->prepare($query);
                $types = '';
                $parameterArray = array('');
                
                $types .= 'd';
                $discountfee = $mydiscountfee + $myreducedfeebydiscount;
                $discountfee = round($discountfee, 6);
                $parameterArray[] = &$discountfee;

                $types .= 'd';
                $couponfee = $mycouponfee + $myreducedfeebycoupon;
                $couponfee = round($couponfee, 6);
                $parameterArray[] = &$couponfee;
                                
                $types .= 'i';
                $parameterArray[] = &$userid;

                $types .= 's';
                $shippingname = stripslashes($shippingname);
                $parameterArray[] = &$shippingname;

                $types .= 's';
                $shippingaddress1 = stripslashes($shippingaddress1);
                $parameterArray[] = &$shippingaddress1;

                $types .= 's';
                $shippingaddress2 = stripslashes($shippingaddress2);
                $parameterArray[] = &$shippingaddress2;
                
                $types .= 's';
                $shippingcity = stripslashes($shippingcity);
                $parameterArray[] = &$shippingcity;
                
                $types .= 'i';
                $parameterArray[] = &$shippingprovinceid;

                $types .= 'i';
                $parameterArray[] = &$shippingprovinceid;
                
                $types .= 's';
                $parameterArray[] = &$shippingcountryalpha2;
                
                $types .= 's';
                $parameterArray[] = &$shippingcountryalpha2;
                
                $types .= 's';
                $shippingpostalcode = stripslashes($shippingpostalcode);
                $parameterArray[] = &$shippingpostalcode;
                
                $types .= 's';
                $shippingphonenumber = stripslashes($shippingphonenumber);
                $parameterArray[] = &$shippingphonenumber;
                
                $types .= 's';
                $parameterArray[] = &$shippingemail;                    
                
                $types .= 'd';
                $parameterArray[] = &$totalfee;
                
                $types .= 'd';
                $parameterArray[] = &$subtotal;
                
                $types .= 's';
                $parameterArray[] = &$discountids2;
                
                $types .= 's';
                $parameterArray[] = &$couponids2;
                
                $types .= 's';
                $discountdescription2 = stripslashes($discountdescription2);
                $parameterArray[] = &$discountdescription2;

                $types .= 's';
                $discountdescriptionforuser2 = stripslashes($discountdescriptionforuser2);
                $parameterArray[] = &$discountdescriptionforuser2;
                
                $types .= 's';
                $coupondescription2 = stripslashes($coupondescription2);                
                $parameterArray[] = &$coupondescription2;                    

                $types .= 's';
                $coupondescriptionforuser2 = stripslashes($coupondescriptionforuser2);
                $parameterArray[] = &$coupondescriptionforuser2;
                
                $types .= 'd';
                $parameterArray[] = &$shippingfee;

                $types .= 'd';
                $parameterArray[] = &$handlingfee;
                
                $types .= 'd';
                $parameterArray[] = &$tax;

                $types .= 's';
                $shippingdescription2 = stripslashes($shippingdescription2);
                $parameterArray[] = &$shippingdescription2;
                
                $types .= 's';
                $handlingdescription2 = stripslashes($handlingdescription2);
                $parameterArray[] = &$handlingdescription2;
                
                $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 reservation into table ' . $table_name . ", id: " . $braintreeid . ". ";
                    throw new Exception($dragon_ecommerce_dbResult);
                } else {
                    $orderid = $myresult;                    
                    for($i=0; $i < count($shoppingcartitemsArr); $i++) {
                        $productid = intval($shoppingcartitemsArr[$i]["id"]);
                        $productpropertyvalueids = $shoppingcartitemsArr[$i]["propertyvalueids"];
                        $productdescription = deslash($shoppingcartitemsArr[$i]["details"]);                    
                        $price = floatval($shoppingcartitemsArr[$i]["price"]);
                        $isonsale = $shoppingcartitemsArr[$i]["isonsale"];
                        $quantity = intval($shoppingcartitemsArr[$i]["quantity"]);
                
                        //create description from productpropertyvalueids
                        $productpropertyvalueidsArr = array();
                        if($productpropertyvalueids !== '') {
                            $productpropertyvalueidsArr = explode("|", $productpropertyvalueids);                                            
                        }
                        $productdescription2Arr = array();
                        if(count($productpropertyvalueidsArr) > 0) {
                            for($j=0; $j < count($productpropertyvalueidsArr); $j++) {                                
                                $propertyvalueidstring = strval($productpropertyvalueidsArr[$j]);
                                if(isset($allorderproducts_property_propertyvalue_id2nameArr[$propertyvalueidstring])) {
                                    $productdescription2Arr[] = $allorderproducts_property_propertyvalue_id2nameArr[$propertyvalueidstring];
                                }                                                                                            
                            }
                        }                            
                        $productdescription2 = join(", ", $productdescription2Arr);
                        //error_log("at 13262, productdescription2: " . $productdescription2);                                                        
                        //insert into _product_order table
                        $query = "INSERT INTO " . $table_name4 . " (`orderid`,`productid`,`productpropertyvalueids`,`productdescription`,`quantity`,`unitpriceexcltax`,`isonsale`,`createtimeutc`) VALUES (?,?,?,?,?,?,?,UTC_TIMESTAMP())";
                        $stmt = $wpdb->dbh->prepare($query);
                        $types = '';
                        $parameterArray = array('');
                        
                        $types .= 'i';
                        $parameterArray[] = &$orderid;

                        $types .= 'i';
                        $parameterArray[] = &$productid;                            
                        
                        $types .= 's';
                        $parameterArray[] = &$productpropertyvalueids;

                        $types .= 's';
                        $parameterArray[] = &$productdescription2;
                        
                        $types .= 'i';
                        $parameterArray[] = &$quantity;

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

                        $types .= 'i';
                        $parameterArray[] = &$isonsale;
                        
                        $parameterArray[0] = $types;
                        call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                        $stmt->execute();
                        $myresult2 = $stmt->insert_id;
                        $stmt->close();
                        
                        if($myresult2 <= 0) {
                            $dragon_ecommerce_dbResult .= 'Error adding a reservation into table ' . $table_name4 . ", id: " . $braintreeid . ". ";                            
                            throw new Exception($dragon_ecommerce_dbResult);
                        }
                        $productpropertyvalueidsArr = array();
                        if($productpropertyvalueids !== '') {
                            $productpropertyvalueidsArr = explode("|", $productpropertyvalueids);                                            
                        }
                        if(count($productpropertyvalueidsArr) > 0) {                                                                              
                            for($j=0; $j < count($productpropertyvalueidsArr); $j++) {                                
                                $propertyvalueid = intval($productpropertyvalueidsArr[$j]);
                                //insert into _order_propertyvalue table
                                $query = "INSERT INTO " . $table_name5 . " (`orderid`,`productid`,`propertyvalueid`,`propertyvalueids`,`createtimeutc`) VALUES (?,?,?,?,UTC_TIMESTAMP())";
                                $stmt = $wpdb->dbh->prepare($query);
                                $types = '';
                                $parameterArray = array('');
                                
                                $types .= 'i';
                                $parameterArray[] = &$orderid;

                                $types .= 'i';
                                $parameterArray[] = &$productid;
                                
                                $types .= 'i';
                                $parameterArray[] = &$propertyvalueid;                                                                

                                $types .= 's';
                                $parameterArray[] = &$productpropertyvalueids;    
                                
                                $parameterArray[0] = $types;
                                call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                                $stmt->execute();
                                $myresult3 = $stmt->insert_id;                                            
                                $stmt->close();                                                
                                if($myresult3 <= 0) {
                                    $dragon_ecommerce_dbResult .= 'Error adding a reservation into table ' . $table_name5 . ", id: " . $braintreeid . ". ";
                                    throw new Exception($dragon_ecommerce_dbResult);
                                }
                            }
                        }
                        //update _product, _product_propertyvalue tables
                        //if setting table set enable quantity
                        //error_log("at 13338, productquantityArr_db: " . json_encode($productquantityArr_db) . ", product_propertyvalueids_quantityArr_db: " . json_encode($product_propertyvalueids_quantityArr_db));
                        if($ENABLE_PRODUCT_QUANTITY_AUTO_DEDUCT === 1 && $productquantityArr_db[strval($productid)] !== null && $productquantityArr_db[strval($productid)] !== "" && ($productquantityArr_db[strval($productid)] - $quantity >= 0)) {
                            $query = "UPDATE " . $table_name6 . " SET quantity = ?, updatetimeutc = UTC_TIMESTAMP() WHERE id = ?";
                            $stmt = $wpdb->dbh->prepare($query);
                            $types = '';
                            $parameterArray = array('');
                            
                            $types .= 'i';
                            $newquantity = $productquantityArr_db[strval($productid)] - $quantity;
                            $productquantityArr_db[strval($productid)] = $newquantity;
                            $parameterArray[] = &$newquantity;

                            $types .= 'i';
                            $parameterArray[] = &$productid;                            
                            
                            $parameterArray[0] = $types;
                            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                            $stmt->execute();
                            if($wpdb->dbh->errno > 0 || $stmt->errno > 0) {
                                $dragon_ecommerce_dbResult .= 'Error updating quantity in table ' . $table_name6 . ". ";
                                throw new Exception($dragon_ecommerce_dbResult);
                            }                                        
                            $stmt->close();                                                                                        
                        }
                        $arr_temp = strval($productid) . '_' . $productpropertyvalueids;
                        if($ENABLE_PRODUCT_QUANTITY_AUTO_DEDUCT === 1 && $product_propertyvalueids_quantityArr_db[$arr_temp] !== null && $product_propertyvalueids_quantityArr_db[$arr_temp] !== "" && ($product_propertyvalueids_quantityArr_db[$arr_temp] - $quantity >= 0)) {
                            $query = "UPDATE " . $table_name15 . " SET quantity = ?, updatetimeutc = UTC_TIMESTAMP()  WHERE productid = ? AND propertyvalueids = ?";
                            $stmt = $wpdb->dbh->prepare($query);
                            $types = '';
                            $parameterArray = array('');
                            
                            $types .= 'i';
                            $newquantity = $product_propertyvalueids_quantityArr_db[$arr_temp] - $quantity;
                            $product_propertyvalueids_quantityArr_db[$arr_temp] = $newquantity;
                            $parameterArray[] = &$newquantity;

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

                            $types .= 's';
                            $parameterArray[] = &$productpropertyvalueids;    
                            
                            $parameterArray[0] = $types;
                            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                            $stmt->execute();
                            if($wpdb->dbh->errno > 0 || $stmt->errno > 0) {
                                $dragon_ecommerce_dbResult .= 'Error updating quantity in table ' . $table_name15 . ". ";
                                throw new Exception($dragon_ecommerce_dbResult);
                            }                                            
                            $stmt->close();                                                                                        
                        }                                                    
                    }                            
                    for($k=0; $k < count($discountArr); $k++) {
                        $discountArr_temp = json_decode($discountArr[$k], true);
                        $propertyvalueid = $discountArr_temp["propertyvalueid"];                                    
                        //insert into _order_propertyvalue table
                        $query = "INSERT INTO " . $table_name5 . " (`orderid`,`propertyvalueid`,`propertyvalueids`,`createtimeutc`) VALUES (?,?,?,UTC_TIMESTAMP())";
                        $stmt = $wpdb->dbh->prepare($query);
                        $types = '';
                        $parameterArray = array('');
                        
                        $types .= 'i';
                        $parameterArray[] = &$orderid;

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

                        $types .= 's';
                        $propertyvalueidstring = strval($propertyvalueid);
                        $parameterArray[] = &$propertyvalueidstring;
                        
                        $parameterArray[0] = $types;
                        call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                        $stmt->execute();
                        $myresult4 = $stmt->insert_id;
                        $stmt->close();                                    
                        if($myresult4 <= 0) {
                            $discountArr_temp = null;
                            $dragon_ecommerce_dbResult .= 'Error adding a reservation into table ' . $table_name5 . ", id: " . $braintreeid . ". ";
                            throw new Exception($dragon_ecommerce_dbResult);
                        }
                        $discountArr_temp = null;                        
                    }
                    for($k=0; $k < count($couponArr); $k++) {
                        $couponArr_temp = json_decode($couponArr[$k], true);
                        $propertyvalueid = $couponArr_temp["propertyvalueid"];                                    
                        //insert into _order_propertyvalue table
                        $query = "INSERT INTO " . $table_name5 . " (`orderid`,`propertyvalueid`,`propertyvalueids`,`createtimeutc`) VALUES (?,?,?,UTC_TIMESTAMP())";
                        $stmt = $wpdb->dbh->prepare($query);
                        $types = '';
                        $parameterArray = array('');
                        
                        $types .= 'i';
                        $parameterArray[] = &$orderid;

                        $types .= 'i';
                        $parameterArray[] = &$propertyvalueid;    
                        
                        $types .= 's';
                        $propertyvalueidstring = strval($propertyvalueid);
                        $parameterArray[] = &$propertyvalueidstring;
                        
                        $parameterArray[0] = $types;
                        call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                        $stmt->execute();
                        $myresult5 = $stmt->insert_id;                                
                        $stmt->close();                                    
                        if($myresult5 <= 0) {
                            $couponArr_temp = null;
                            $dragon_ecommerce_dbResult .= 'Error adding a reservation into table ' . $table_name5 . ", id: " . $braintreeid . ". ";
                            throw new Exception($dragon_ecommerce_dbResult);
                        }
                        $couponArr_temp = null;                        
                    }                            
                    $wpdb->dbh->commit();
                    
                    //send out confirm receipt email using own SMTP server, mailgun, mailchimp, sendgrid                                
                    if(trim($setting_email_method) === '') {
                        $dragon_ecommerce_dbResult .= "Email method is not set by website admin. Please contact website admin. ";
                        dragonecommercereservezyx987_saveToLogTable($dragon_ecommerce_dbResult, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', intval($current_user->data->ID));                            
                        throw new Exception($dragon_ecommerce_dbResult);
                    }                
                    if($setting_email_method === 'Mailgun') {                    
                        if($mailgun_api_key === '' || $mailgun_domain === '' || $mailgun_api_url === '') {            
                            $dragon_ecommerce_dbResult .= "Mailgun email settings are not set by website admin. Please contact website admin. ";
                            dragonecommercereservezyx987_saveToLogTable($dragon_ecommerce_dbResult, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', intval($current_user->data->ID));                            
                            throw new Exception($dragon_ecommerce_dbResult);
                        }
                        //if mailgun_api_url does not end with /, add /
                        if($mailgun_api_url !== null && $mailgun_api_url !== '' && substr($mailgun_api_url, -1, 1) !== '/') {
                            $mailgun_api_url = $mailgun_api_url . "/";
                        }                        
                    }                    
                    if($setting_email_method === 'Mailchimp') {                    
                        if($mailchimp_api_key === '' || $mailchimp_fromemail === '' || $mailchimp_api_url === '') {        
                            $dragon_ecommerce_dbResult .= "Mailchimp email settings are not set by website admin. Please contact website admin. ";
                            dragonecommercereservezyx987_saveToLogTable($dragon_ecommerce_dbResult, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', intval($current_user->data->ID));                                
                            throw new Exception($dragon_ecommerce_dbResult);
                        }        
                    }                    
                    if($setting_email_method === 'SendGrid') {                    
                        if($sendgrid_api_key === '' || $sendgrid_fromemail === '' || $sendgrid_api_url === '') {            
                            $dragon_ecommerce_dbResult .= "SendGrid email settings are not set by website admin. Please contact website admin. ";
                            dragonecommercereservezyx987_saveToLogTable($dragon_ecommerce_dbResult, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', intval($current_user->data->ID));                                
                            throw new Exception($dragon_ecommerce_dbResult);
                        }        
                    }                                
                    $email = $current_user->data->user_email;
                    $bccemail = get_option('admin_email');                            
                    $websiteurl = sanitize_text_field($_POST['pluginurl']);
                    $subject = $websiteurl . " reserve info";
                    $content = '';
                    for($i=0; $i < count($shoppingcartitemsArr); $i++) {
                        $currencysign = $shoppingcartitemsArr[$i]["currencysign"];
                        $productname = $shoppingcartitemsArr[$i]["name"];
                        $productdetails = stripslashes($shoppingcartitemsArr[$i]["details"]);                        
                        $price = $shoppingcartitemsArr[$i]["price"];
                        $quantity = $shoppingcartitemsArr[$i]["quantity"];                                
                        $content .= 'Name: ' . $productname . ($productdetails === '' ? '' : (", Details: ". $productdetails)) . ", Price: " . $currencysign . $price . ", Quantity: ". $quantity . '<br/><br/>';                                
                    }                            
                    $content .= 'Subtotal: '. $currencysign . number_format($subtotal, 2) . '<br/>';                            
                    for($k=0; $k < count($discountArr); $k++) {
                        $discountArr_temp = json_decode($discountArr[$k], true);
                        if($discountArr_temp["userate"] === 1) {
                            $content .= 'Discount (rate): ' . $discountArr_temp["rate"] . '<br/>';                                    
                        } elseif($discountArr_temp["usefee"] === 1) {
                            $content .= 'Discount (fee): ' . $currencysign . number_format($discountArr_temp["fee"], 2) . '<br/>';
                        }
                        $discountArr_temp = null;
                    }                            
                    for($k=0; $k < count($couponArr); $k++) {
                        $couponArr_temp = json_decode($couponArr[$k], true);
                        if($couponArr_temp["userate"] === 1) {
                            $content .= 'Coupon (rate): ' . $couponArr_temp["rate"] . '<br/>';                                    
                        } elseif($couponArr_temp["usefee"] === 1) {
                            $content .= 'Coupon (fee): ' . $currencysign . number_format($couponArr_temp["fee"], 2) . '<br/>';
                        }
                    }                            
                    //shipping and handling if any
                    if($_POST['shippingchargeenabled'] === '1') {
                        $content .= 'Shipping: '. $currencysign . number_format($shippingfee, 2) . '<br/>';                            
                    }
                    if($_POST['handlingchargeenabled'] === '1') {
                        $content .= 'Handling: '. $currencysign . number_format($handlingfee, 2) . '<br/>';                            
                    }                            
                    $content .= 'Tax: '. $currencysign . number_format($tax, 2) . '<br/>';
                    $content .= 'Total: '. $currencysign . number_format($totalfee, 2) . '<br/>';    
                    $msg = '<div id="dragonecommercezyx987"><title></title>'
                           .'<style type="text/css">@media screen and (max-width:449px) {#dragonecommercezyx987 .dragonecommercezyx987standalone-paragraph-huge-left .dragonecommercezyx987inner-nested {font-size:26px !important;line-height:30px !important;}}@media screen and (max-width:449px) {'
                           .'#dragonecommercezyx987 .dragonecommercezyx987standalone-paragraph-huge-center .dragonecommercezyx987inner-nested {font-size:26px !important;line-height:30px !important;}}@media screen and (min-width:5px) {#dragonecommercezyx987 body {}#dragonecommercezyx987 .dragonecommercezyx987outer, #dragonecommercezyx987 .dragonecommercezyx987webkit {width:100% !important;min-width:0 !important;max-width:580px !important;}'
                           .'#dragonecommercezyx987 .dragonecommercezyx987section-dark .dragonecommercezyx987inner-nested a {color:#FFFFFF !important;text-decoration:underline !important;}}@media screen and (max-width:449px) {#dragonecommercezyx987 .dragonecommercezyx987contents {font-size:15px !important;line-height:1.625em !important;}#dragonecommercezyx987 .dragonecommercezyx987column, #dragonecommercezyx987 .dragonecommercezyx987image img {max-width:99% !important;}'
                           .'#dragonecommercezyx987 .dragonecommercezyx987three-col .dragonecommercezyx987contents, #dragonecommercezyx987 .dragonecommercezyx987two-col .dragonecommercezyx987contents {font-size:13px !important;}#dragonecommercezyx987 .dragonecommercezyx987three-col .dragonecommercezyx987column img, #dragonecommercezyx987 .dragonecommercezyx987four-col .dragonecommercezyx987column img {max-width:100% !important;}'
                           .'#dragonecommercezyx987 .dragonecommercezyx987one-col .dragonecommercezyx987h6, #dragonecommercezyx987 .dragonecommercezyx987three-col .dragonecommercezyx987h6, #dragonecommercezyx987 .dragonecommercezyx987four-col .dragonecommercezyx987h6, #dragonecommercezyx987 .dragonecommercezyx987two-col .dragonecommercezyx987h6 {font-size:13px !important;margin-bottom:2px !important;}#dragonecommercezyx987 .dragonecommercezyx987h1 {font-size:26px !important;'
                           .'line-height:30px !important;}#dragonecommercezyx987 .dragonecommercezyx987h3 {font-size:26px !important;}}@media screen and (min-width:450px) and (max-width:600px) {#dragonecommercezyx987 .dragonecommercezyx987two-col .dragonecommercezyx987buffered, #dragonecommercezyx987 .dragonecommercezyx987four-col .dragonecommercezyx987buffered, #dragonecommercezyx987 .dragonecommercezyx987three-col .dragonecommercezyx987buffered {padding-left:6px !important;padding-right:6px !important;}'
                           .'#dragonecommercezyx987 .dragonecommercezyx987two-col .dragonecommercezyx987inner, #dragonecommercezyx987 .dragonecommercezyx987four-col .dragonecommercezyx987inner, #dragonecommercezyx987 .dragonecommercezyx987three-col .dragonecommercezyx987inner {}}@media screen and (max-width:449px) {#dragonecommercezyx987 .dragonecommercezyx987buffered {padding-left:0 !important;padding-right:0 !important;}}'
                           .'@media screen and (min-width:450px) and (max-width:655px) {#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987narrow {max-width:40% !important;}#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987wide {max-width:60% !important;}#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987image img {max-width:100% !important;}'
                           .'#dragonecommercezyx987 .dragonecommercezyx987left-round {text-align:left !important;}#dragonecommercezyx987 .dragonecommercezyx987right-round {text-align:right !important;}}@media screen and (max-width:600px) {#dragonecommercezyx987 .dragonecommercezyx987preheader {display:none !important;}#dragonecommercezyx987 .dragonecommercezyx987layout-preheader .dragonecommercezyx987inner {padding:10px !important;}#dragonecommercezyx987 .dragonecommercezyx987webversion {text-align:center !important;}'
                           .'#dragonecommercezyx987 .dragonecommercezyx987inner {padding-left:7% !important;padding-right:7% !important;}#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar p {font-size:13px !important;line-height:1.6em !important;}#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987h3 {font-size:21px !important;}#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987h5 {font-size:13px !important;}'
                           .'#dragonecommercezyx987 .dragonecommercezyx987mob-hide {display:none !important;}}@media screen and (min-width:5px) {#dragonecommercezyx987 img {height:auto !important;max-width:100% !important;}#dragonecommercezyx987 .dragonecommercezyx987hide {display:none !important;}}@media screen and (min-width:656px) {#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987narrow {max-width:31% !important;}'
                           .'#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987wide {max-width:69% !important;}}@media screen and ( _filtered_a )</style>'
                           .'<div><table class="dragonecommercezyx987hide" style="width:580px;min-width:580px;" cellspacing="0" cellpadding="0" border="0"><tbody><tr><td style="font-size:1px;line-height:1px;min-width:580px;" width="580"></td></tr></tbody></table>'
                           .'<div class="dragonecommercezyx987ios9"> &nbsp;<table class="dragonecommercezyx987wrapper dragonecommercezyx987section-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;table-layout:fixed;width:100%;border-collapse:separate;text-align:left;color:#303030;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#087197" align="center"><tbody><tr>'
                           .'<td align="center"><center><div class="dragonecommercezyx987webkit" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;">  <table class="dragonecommercezyx987outer" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                           .'<td> <table class="dragonecommercezyx987layout-preheader" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr class="dragonecommercezyx987one-col">'
                           .'<td class="dragonecommercezyx987inner dragonecommercezyx987contents" style="padding-left:20px;padding-right:20px;padding-bottom:18px;font-size:13px;line-height:14px;padding-top:18px;font-weight:500;color:#303030;">'
                           .'</td></tr></tbody></table></td></tr></tbody></table>'
                           .'</div></center></td></tr></tbody></table><table class="dragonecommercezyx987wrapper dragonecommercezyx987section-" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;table-layout:fixed;width:100%;border-collapse:separate;text-align:left;color:#303030;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF" align="center"><tbody><tr>'
                           .'<td align="center"> <center> <div class="dragonecommercezyx987webkit" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;">  <table class="dragonecommercezyx987outer dragonecommercezyx987boxed-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF"><tbody><tr>'
                           .'<td> <table class="dragonecommercezyx987layout-solologo dragonecommercezyx987boxed dragonecommercezyx987left" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr class="dragonecommercezyx987one-col">'
                           .'<td class="dragonecommercezyx987inner" style="padding-left:18px;padding-right:18px;padding-bottom:18px;padding-top:18px;"> <table width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                           .'<td class="dragonecommercezyx987inner-nested" style="padding-top:12px;padding-bottom:12px;padding-right:0px;padding-left:0px;"> <table class="dragonecommercezyx987contents" style="text-align:left;font-size:16px;line-height:22px;" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                           .'<td class="dragonecommercezyx987logo" style="font-weight:bold;font-size:18px;color:#087197;"><a rel="nofollow noopener noreferrer" target="_blank" href="%%%companyurl%%%" style="text-decoration:none;color:#087197;">%%%companyname%%%</a> </td> </tr></tbody></table>'
                           .'</td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table>'
                           .'</div></center></td></tr></tbody></table><table class="dragonecommercezyx987wrapper dragonecommercezyx987section-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;table-layout:fixed;width:100%;border-collapse:separate;text-align:left;color:#303030;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF" align="center"><tbody><tr>'
                           .'<td align="center"> <center> <div class="dragonecommercezyx987webkit" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;">  <table class="dragonecommercezyx987outer dragonecommercezyx987boxed-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF"><tbody><tr>'
                           .'<td> <table class="dragonecommercezyx987contents dragonecommercezyx987feature-callout-cta dragonecommercezyx987cta" style="color:#303030;" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr class="dragonecommercezyx987two-col">'
                           .'<td class="dragonecommercezyx987inner" style="padding-left:10px;padding-right:10px;"><table class="dragonecommercezyx987contents" style="font-size:16px;line-height:22px;color:#303030;" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                           .'<td class="dragonecommercezyx987feature-callout-bottom" style="padding-top:20px;padding-bottom:20px;padding-right:10px;padding-left:10px;" width="100%" valign="middle"> <table class="dragonecommercezyx987contents" style="font-size:16px;line-height:22px;color:#303030;" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                           .'<td class="dragonecommercezyx987inner-nested" style="padding-top:12px;padding-bottom:12px;padding-right:0px;padding-left:0;" valign="middle">'
                           .'<p class="dragonecommercezyx987h3" style="margin-top:0;margin-bottom:30px !important;font-weight:500;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;font-size:38px;line-height:36px;">%%%title%%%</p>'
                           .'<p>Hi %%%username%%%,</p><p>%%%header%%%</p><p>Shipping address:<br/>%%%shippingname%%%<br/>%%%shippingaddress%%%<br/>%%%shippingcity%%%<br/>%%%shippingprovincename%%%<br/>%%%shippingcountryname%%%<br/>%%%shippingpostalcode%%%</p><br/><p>%%%content%%%</p><p>If you have any questions, please do not hesitate to contact us. For more information, check out the <a rel="nofollow noopener noreferrer" target="_blank" href="%%%companyurl%%%">company website</a>.</p><p>Thanks,</p><p>%%%companyname%%%</p></td></tr></tbody></table>'
                           .'<table class="dragonecommercezyx987buttonwrapper dragonecommercezyx987cta-option-standard-tall" style="font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;background-color:#6ca12b;overflow:hidden;border-radius:5px;margin-top:30px;margin-bottom:40px;margin-right:auto;margin-left:0;font-size:16px;line-height:18px;font-weight:bold;" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                           .'<td class="dragonecommercezyx987button">'
                           .'</td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></div></center></td></tr></tbody></table>'
                           .'<table class="dragonecommercezyx987wrapper dragonecommercezyx987section-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;table-layout:fixed;width:100%;border-collapse:separate;text-align:left;color:#303030;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF" align="center"><tbody><tr>'
                           .'<td align="center"> <center> <div class="dragonecommercezyx987webkit" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;">  <table class="dragonecommercezyx987outer" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                           .'<td><div class="dragonecommercezyx987spacer" style="font-size:40px;line-height:40px;display:block;color:#ffffff;text-align:center;">&nbsp;</div> </td> </tr></tbody></table>'
                           .'</div> </center> </td> </tr></tbody></table><table class="dragonecommercezyx987wrapper dragonecommercezyx987section-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;table-layout:fixed;width:100%;border-collapse:separate;text-align:left;color:#303030;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF" align="center"><tbody><tr>'
                           .'<td align="center"> <center> <div class="dragonecommercezyx987webkit" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;">  <table class="dragonecommercezyx987outer dragonecommercezyx987boxed-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF"><tbody><tr>'
                           .'<td><table class="dragonecommercezyx987footer-container" width="100%" cellspacing="0" cellpadding="0" border="0" align="center">'
                           .'<tbody><tr class="dragonecommercezyx987one-col">'
                           .'<td class="dragonecommercezyx987inner dragonecommercezyx987footer-row-top" style="padding-left:20px;padding-right:20px;padding-bottom:0px;padding-top:20px;"> <table class="dragonecommercezyx987fluid" style="border-top-width:2px;border-top-style:solid;border-top-color:#ECECEE;border-bottom-width:2px;border-bottom-style:solid;border-bottom-color:#ECECEE;" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr>'
                           .'<td class="dragonecommercezyx987hh-force-col-center" style="text-align:center;padding-top:25px;padding-bottom:40px;padding-right:0;padding-left:0;" valign="top"> <a rel="nofollow noopener noreferrer" target="_blank" href="%%%companyurl%%%" style="text-decoration:none;color:#959597;">%%%companyname%%%</a> </td> </tr></tbody></table>'
                           .'</td></tr>'
                           .'<tr class="dragonecommercezyx987one-col"><td class="dragonecommercezyx987inner dragonecommercezyx987footer-row-bottom" style="padding-left:20px;padding-right:20px;padding-bottom:0px;padding-top:20px;"> <table class="dragonecommercezyx987fluid" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr>'
                           .'<td class="dragonecommercezyx987hh-force-col-center dragonecommercezyx987footer-text-left" style="text-align:left;padding-top:0px;padding-bottom:40px;padding-right:0;padding-left:0;" valign="top">'
                           .'<p style="display:none;"></p></td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></div></center></td></tr></tbody></table></div></div></div>';
                    $msg = str_replace("%%%companyname%%%", $websiteurl, $msg);                            
                    $msg = str_replace("%%%title%%%", $websiteurl, $msg);                            
                    $current_user = wp_get_current_user();
                    $current_username = $current_user->data->user_login;
                    $msg = str_replace("%%%username%%%", $current_username, $msg);
                    $msg = str_replace("%%%header%%%", 'Congratulations! You have reserved on %%%companyurl%%%', $msg);
                    $msg = str_replace("%%%shippingname%%%", $shippingname, $msg);
                    $msg = str_replace("%%%shippingaddress%%%", $shippingaddress1 . (trim($shippingaddress2) === '' ? '' : ('<br/>' . trim($shippingaddress2))), $msg);
                    $msg = str_replace("%%%shippingcity%%%", $shippingcity, $msg);
                    $msg = str_replace("%%%shippingprovincename%%%", $shippingprovincename, $msg);
                    $msg = str_replace("%%%shippingcountryname%%%", $shippingcountryname, $msg);
                    $msg = str_replace("%%%shippingpostalcode%%%", $shippingpostalcode, $msg);                    
                    $msg = str_replace("%%%content%%%", $content, $msg);
                    $msg = str_replace("%%%companyurl%%%", $websiteurl, $msg);                                                                                

                    $finalresult = "";
                    $emailsent = 1;                    
                    if($setting_email_method === 'WordPress Email') {
                        $headers = 'From: '. $bccemail . "\r\n" .
                            'Reply-To: ' . $email . "\r\n" .
                            'Bcc: ' . $bccemail . "\r\n";
                         
                        //Validation and send mail
                        add_filter('wp_mail_content_type', function($content_type) {
                            return 'text/html';
                        });
                        $sent = wp_mail($email, $subject, $msg, $headers);
                        if($sent) {
                        } else {//message wasn't sent
                            $finalresult .= "WordPress Email result: Order email was not sent to you. Please contact website admin. ";
                            $emailsent = 0;                            
                        }        
                    } elseif($setting_email_method === 'Mailgun') {
                        $data = array(
                            'from' => $mailgun_fromname . ' <mailgun@' . $mailgun_domain . '>',
                            'to' => $email,
                            'bcc' => $bccemail,
                            'subject' => $subject,
                            'html' => $msg,
                            'o:tracking' => false);
                        $auth = base64_encode('api:'.$mailgun_api_key);
                        $args = [
                            'headers' => ['Authorization' => "Basic $auth"],
                            'body' => $data
                        ];
                        $mailgun_result = wp_remote_post($mailgun_api_url . $mailgun_domain . '/messages', $args);    
                        if(is_wp_error($mailgun_result)) {
                            $finalresult .= 'Mailgun result: ' . json_encode($mailgun_result);  //$mailgun_result->get_error_message();
                            $emailsent = 0;
                        }
                    } elseif($setting_email_method === 'Mailchimp') {
                        $data = array(
                            "key"=> $mailchimp_api_key, 
                            "message"=> array(
                                "from_email"=> $mailchimp_fromemail,
                                "from_name"=> $mailchimp_fromname,
                                "subject"=> $subject, 
                                "html"=> $msg,
                                "to"=> array(array("email"=> $email, "name"=> "", "type"=>"to"), array("email"=> $bccemail, "name"=> "", "type"=>"bcc")),
                                "track_opens"=>true,
                                "track_clicks"=>true
                            )
                        );
                        $data2 = json_encode($data);
                        $auth = base64_encode('authorization: apikey '.$mailchimp_api_key);
                        $args = [
                            'headers' => ['Authorization' => "Basic $auth"],
                            'body' => $data2
                        ];
                        $response = wp_remote_post($mailchimp_api_url, $args);
                        if(is_wp_error($response)) {
                            $finalresult .= 'Mailchimp result: ' . $response->get_error_message();
                            $emailsent = 0;
                        }
                        //$response = json_decode($response0, true);
                        if($response !== null && is_array($response) && count($response) > 0 && isset($response[0]["status"]) && ($response[0]["status"] === 'rejected' || $response[0]["status"] === 'invalid')) {
                            $finalresult .= 'Mailchimp result: ' . json_encode($response);
                            $emailsent = 0;
                        }                                                
                        //error_log("at 13654, mailchimp send email response: " . $response[0]["status"] . ", error: " . $finalresult);                
                    } elseif($setting_email_method === 'SendGrid') {                    
                        $data = array(
                            "personalizations"=> array(
                                array(
                                    "to"=> array(array("email"=> $email)),
                                    "bcc"=> array(array("email"=> $bccemail))
                                )
                            ), 
                            "from"=>array(
                                "email"=> $sendgrid_fromemail,
                                "name"=> $sendgrid_fromname
                            ),
                            "subject"=>$subject,
                            "content"=>array(
                                array(
                                    "type"=> "text/html", 
                                    "value"=> $msg
                                )                            
                            )
                        );
                        $data2 = json_encode($data);
                        //$auth = base64_encode('api:'.$sendgrid_api_key);
                        $args = array(
                            'headers' => array("Authorization" => "Bearer " . $sendgrid_api_key, "Content-Type" => "application/json"),
                            'body' => $data2
                        );    
                        $response = wp_remote_post($sendgrid_api_url, $args);    
                        if(is_wp_error($response)) {
                            $finalresult .= 'SendGrid result: ' . $response->get_error_message();
                            $emailsent = 0;
                        }
                        //$response = json_decode($response0, true);
                        if($response !== null && $response !== '' && is_array($response) && count($response) > 0 && (!empty($response["body"]["errors"]))) {
                            $finalresult .= 'SendGrid result: ' . json_encode($response);
                            $emailsent = 0;
                        }
                        //error_log("at 13691, sendgrid send email response: " . $response0 . ", error: " . $finalresult);                        
                    }                    
                    if($finalresult !== "" && $emailsent === 0) {
                        dragonecommercereservezyx987_saveToLogTable($finalresult, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB . ", email user reservation details", 'error', $userid);                        
                    } 
                    //update _order table emailsent to true
                    $table_name = 'wp_dragonecommercereservezyx987_order';                
                    $result = $wpdb->query($wpdb->prepare("UPDATE $table_name SET emailsent = %d WHERE id = %d", array($emailsent, $orderid)));
                    if($result === FALSE) {                            
                        $dragon_ecommerce_dbResult .= 'Error updating emailsent of a row in table ' . $table_name . ", id: " . $orderid . ". ";
                        throw new Exception($dragon_ecommerce_dbResult);
                    }
                    setcookie('dragonecommercereservezyx987_orderitems', '', time() - 42000, '/', '', true, true);            
                    echo "Success. Please check your email for reservation details.";
                    exit();
                }
            } catch (Exception $e) {
                $wpdb->dbh->rollback();                        
                $message = 'Save reservation to DB: Exception Message: ' .$e->getMessage();
                dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', $userid);
                echo esc_html($message);                    
                exit();
            }                                
        }
    }
    $message = 'Save reservation to DB: Wrong data.';
    dragonecommercereservezyx987_saveToLogTable($message, DRAGONECOMMERCERESERVEF_ADD_ORDER_TO_DB, 'error', $userid);
    echo esc_html($message);
    exit();
}

add_action('wp_ajax_dragonecommercereservezyx987_accountactivation', 'dragonecommercereservezyx987_accountActivation');
add_action('wp_ajax_nopriv_dragonecommercereservezyx987_accountactivation', 'dragonecommercereservezyx987_accountActivation'); 
function dragonecommercereservezyx987_accountActivation() {
    check_ajax_referer('dragonecommercereservezyx987_accountactivation', 'dragonecommercereservezyx987_hidden_security_accountactivation');
    if((!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        global $wpdb;        
        $email = empty($_POST['email']) ? '' : sanitize_text_field($_POST['email']);
        $email = strip_tags($email);
        $email = stripslashes($email);            
        $validationerror = '';        
        // Check email address is present and valid  
        $email = $wpdb->escape($email);  
        if(empty($email)) {   
            $validationerror .= "Please enter an email address";  
        } elseif(!is_email($email)) {   
            $validationerror .= "Please enter a valid email address";  
        } elseif(!email_exists($email)) {  
            $validationerror .= "This email address is not in use";  
        }
        if($validationerror !== '') {echo esc_html($validationerror); exit();}
        $setting_email_method = ''; 
        $mailgun_api_key = "";
        $mailgun_api_url = "";
        $mailgun_domain = "";
        $mailgun_fromname = 'NO-REPLY';    
        $mailchimp_api_key = "";
        $mailchimp_api_url = "";
        $mailchimp_fromemail = "";
        $mailchimp_fromname = "";
        $sendgrid_api_key = "";
        $sendgrid_api_url = "";
        $sendgrid_fromemail = "";
        $sendgrid_fromname = "";        
        
        $table_name = 'wp_dragonecommercereservezyx987_emailmethod';
        $table_name2 = 'wp_dragonecommercereservezyx987_setting';
        $query = "SELECT a.name, b.name as 'settingname', b.value from $table_name a RIGHT JOIN $table_name2 b ON  CAST(b.value AS UNSIGNED) = a.id ";
        $query .= " WHERE b.name IN ('EMAIL_METHOD','MAILGUN_APIKEY','MAILGUN_DOMAIN','MAILGUN_API_URL','MAILGUN_FROMNAME',";
        $query .= " 'MAILCHIMP_APIKEY','MAILCHIMP_API_URL','MAILCHIMP_FROMEMAIL','MAILCHIMP_FROMNAME','SENDGRID_APIKEY','SENDGRID_API_URL','SENDGRID_FROMEMAIL','SENDGRID_FROMNAME') ";
        $result = $wpdb->get_results($query);                
        if(count($result) > 0) {
            for($i=0; $i<count($result); $i++) {
                if($result[$i]->settingname === 'EMAIL_METHOD') {
                   $setting_email_method = trim($result[$i]->name);
                } elseif($result[$i]->settingname === 'MAILGUN_APIKEY') {
                   $mailgun_api_key = $result[$i]->value;
                } elseif($result[$i]->settingname === 'MAILGUN_API_URL') {
                   $mailgun_api_url = $result[$i]->value;
                } elseif($result[$i]->settingname === 'MAILGUN_DOMAIN') {
                   $mailgun_domain = $result[$i]->value;
                } elseif($result[$i]->settingname === 'MAILGUN_FROMNAME') {
                   $mailgun_fromname = $result[$i]->value;
                } elseif($result[$i]->settingname === 'MAILCHIMP_APIKEY') {
                   $mailchimp_api_key = $result[$i]->value;
                } elseif($result[$i]->settingname === 'MAILCHIMP_API_URL') {
                   $mailchimp_api_url = $result[$i]->value;
                } elseif($result[$i]->settingname === 'MAILCHIMP_FROMEMAIL') {
                   $mailchimp_fromemail = $result[$i]->value;
                } elseif($result[$i]->settingname === 'MAILCHIMP_FROMNAME') {
                   $mailchimp_fromname = $result[$i]->value;
                } elseif($result[$i]->settingname === 'SENDGRID_APIKEY') {
                   $sendgrid_api_key = $result[$i]->value;
                } elseif($result[$i]->settingname === 'SENDGRID_API_URL') {
                   $sendgrid_api_url = $result[$i]->value;
                } elseif($result[$i]->settingname === 'SENDGRID_FROMEMAIL') {
                   $sendgrid_fromemail = $result[$i]->value;
                } elseif($result[$i]->settingname === 'SENDGRID_FROMNAME') {
                   $sendgrid_fromname = $result[$i]->value;
                }                                            
            }
        }
        $result = null;        
        if(trim($setting_email_method) === '') {
            $temp = "Email method is not set by website admin. Please contact website admin.";
            dragonecommercereservezyx987_saveToLogTable($temp, 'account activation', 'error');            
            echo esc_html($temp);
            exit();
        }
        if($setting_email_method === 'Mailgun') {                    
            if($mailgun_api_key === '' || $mailgun_domain === '' || $mailgun_api_url === '') {            
                $dragon_ecommerce_dbResult .= "Mailgun email settings are not set by website admin. Please contact website admin. ";
                dragonecommercereservezyx987_saveToLogTable($dragon_ecommerce_dbResult, 'account activation', 'error', intval($current_user->data->ID));                            
                throw new Exception($dragon_ecommerce_dbResult);
            }
            //if mailgun_api_url does not end with /, add /
            if($mailgun_api_url !== null && $mailgun_api_url !== '' && substr($mailgun_api_url, -1, 1) !== '/') {
                $mailgun_api_url = $mailgun_api_url . "/";
            }                        
        }                    
        if($setting_email_method === 'Mailchimp') {                    
            if($mailchimp_api_key === '' || $mailchimp_fromemail === '' || $mailchimp_api_url === '') {        
                $dragon_ecommerce_dbResult .= "Mailchimp email settings are not set by website admin. Please contact website admin. ";
                dragonecommercereservezyx987_saveToLogTable($dragon_ecommerce_dbResult, 'account activation', 'error', intval($current_user->data->ID));                                
                throw new Exception($dragon_ecommerce_dbResult);
            }        
        }                    
        if($setting_email_method === 'SendGrid') {                    
            if($sendgrid_api_key === '' || $sendgrid_fromemail === '' || $sendgrid_api_url === '') {            
                $dragon_ecommerce_dbResult .= "SendGrid email settings are not set by website admin. Please contact website admin. ";
                dragonecommercereservezyx987_saveToLogTable($dragon_ecommerce_dbResult, 'account activation', 'error', intval($current_user->data->ID));                                
                throw new Exception($dragon_ecommerce_dbResult);
            }        
        }                
        $table_name = $wpdb->prefix . 'users';
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $stmt = $wpdb->dbh->prepare("SELECT ID, user_login FROM $table_name WHERE user_email = ?");
            $stmt->bind_param("s", $email);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            
            if(count($result) === 1) {
                //send email
                $bccemail = get_option('admin_email');        
                $finalresult = '';        
                   $t = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!$@!abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                $randomtoken = str_shuffle($t);        
                $user_id = $result[0]["ID"];
                $username = $result[0]["user_login"];
                
                //add a record to _user_token table for this user_id with a new token
                $table_name = 'wp_dragonecommercereservezyx987_user_token';
                $result = $wpdb->query($wpdb->prepare("INSERT INTO $table_name (`userid`,`tokenpurpose`,`token`,`tokensentdatetimeutc`,`createtimeutc`) VALUES (%d, %s, %s, UTC_TIMESTAMP(), UTC_TIMESTAMP())", array($user_id, 'REGISTER_ACTIVATION', $randomtoken)));                
                if($result === FALSE || $result === 0) {
                    $finalresult .= "New user info was not added to user token table. Please contact website admin. ";
                    dragonecommercereservezyx987_saveToLogTable($finalresult, 'account activation', 'error');                    
                }                            
                $websiteurl = sanitize_text_field($_POST['pluginurl']);
                $activationlink = $websiteurl . '?action=activateaccount&id=' . $user_id . '&token=' . $randomtoken;
                $subject = $websiteurl . " registration activation";
                $msg = '<div id="dragonecommercezyx987"><title></title>'
                       .'<style type="text/css">@media screen and (max-width:449px) {#dragonecommercezyx987 .dragonecommercezyx987standalone-paragraph-huge-left .dragonecommercezyx987inner-nested {font-size:26px !important;line-height:30px !important;}}@media screen and (max-width:449px) {'
                       .'#dragonecommercezyx987 .dragonecommercezyx987standalone-paragraph-huge-center .dragonecommercezyx987inner-nested {font-size:26px !important;line-height:30px !important;}}@media screen and (min-width:5px) {#dragonecommercezyx987 body {}#dragonecommercezyx987 .dragonecommercezyx987outer, #dragonecommercezyx987 .dragonecommercezyx987webkit {width:100% !important;min-width:0 !important;max-width:580px !important;}'
                       .'#dragonecommercezyx987 .dragonecommercezyx987section-dark .dragonecommercezyx987inner-nested a {color:#FFFFFF !important;text-decoration:underline !important;}}@media screen and (max-width:449px) {#dragonecommercezyx987 .dragonecommercezyx987contents {font-size:15px !important;line-height:1.625em !important;}#dragonecommercezyx987 .dragonecommercezyx987column, #dragonecommercezyx987 .dragonecommercezyx987image img {max-width:99% !important;}'
                       .'#dragonecommercezyx987 .dragonecommercezyx987three-col .dragonecommercezyx987contents, #dragonecommercezyx987 .dragonecommercezyx987two-col .dragonecommercezyx987contents {font-size:13px !important;}#dragonecommercezyx987 .dragonecommercezyx987three-col .dragonecommercezyx987column img, #dragonecommercezyx987 .dragonecommercezyx987four-col .dragonecommercezyx987column img {max-width:100% !important;}'
                       .'#dragonecommercezyx987 .dragonecommercezyx987one-col .dragonecommercezyx987h6, #dragonecommercezyx987 .dragonecommercezyx987three-col .dragonecommercezyx987h6, #dragonecommercezyx987 .dragonecommercezyx987four-col .dragonecommercezyx987h6, #dragonecommercezyx987 .dragonecommercezyx987two-col .dragonecommercezyx987h6 {font-size:13px !important;margin-bottom:2px !important;}#dragonecommercezyx987 .dragonecommercezyx987h1 {font-size:26px !important;'
                       .'line-height:30px !important;}#dragonecommercezyx987 .dragonecommercezyx987h3 {font-size:26px !important;}}@media screen and (min-width:450px) and (max-width:600px) {#dragonecommercezyx987 .dragonecommercezyx987two-col .dragonecommercezyx987buffered, #dragonecommercezyx987 .dragonecommercezyx987four-col .dragonecommercezyx987buffered, #dragonecommercezyx987 .dragonecommercezyx987three-col .dragonecommercezyx987buffered {padding-left:6px !important;padding-right:6px !important;}'
                       .'#dragonecommercezyx987 .dragonecommercezyx987two-col .dragonecommercezyx987inner, #dragonecommercezyx987 .dragonecommercezyx987four-col .dragonecommercezyx987inner, #dragonecommercezyx987 .dragonecommercezyx987three-col .dragonecommercezyx987inner {}}@media screen and (max-width:449px) {#dragonecommercezyx987 .dragonecommercezyx987buffered {padding-left:0 !important;padding-right:0 !important;}}'
                       .'@media screen and (min-width:450px) and (max-width:655px) {#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987narrow {max-width:40% !important;}#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987wide {max-width:60% !important;}#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987image img {max-width:100% !important;}'
                       .'#dragonecommercezyx987 .dragonecommercezyx987left-round {text-align:left !important;}#dragonecommercezyx987 .dragonecommercezyx987right-round {text-align:right !important;}}@media screen and (max-width:600px) {#dragonecommercezyx987 .dragonecommercezyx987preheader {display:none !important;}#dragonecommercezyx987 .dragonecommercezyx987layout-preheader .dragonecommercezyx987inner {padding:10px !important;}#dragonecommercezyx987 .dragonecommercezyx987webversion {text-align:center !important;}'
                       .'#dragonecommercezyx987 .dragonecommercezyx987inner {padding-left:7% !important;padding-right:7% !important;}#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar p {font-size:13px !important;line-height:1.6em !important;}#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987h3 {font-size:21px !important;}#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987h5 {font-size:13px !important;}'
                       .'#dragonecommercezyx987 .dragonecommercezyx987mob-hide {display:none !important;}}@media screen and (min-width:5px) {#dragonecommercezyx987 img {height:auto !important;max-width:100% !important;}#dragonecommercezyx987 .dragonecommercezyx987hide {display:none !important;}}@media screen and (min-width:656px) {#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987narrow {max-width:31% !important;}'
                       .'#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987wide {max-width:69% !important;}}@media screen and ( _filtered_a )</style>'
                       .'<div><table class="dragonecommercezyx987hide" style="width:580px;min-width:580px;" cellspacing="0" cellpadding="0" border="0"><tbody><tr><td style="font-size:1px;line-height:1px;min-width:580px;" width="580"></td></tr></tbody></table>'
                       .'<div class="dragonecommercezyx987ios9"> &nbsp;<table class="dragonecommercezyx987wrapper dragonecommercezyx987section-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;table-layout:fixed;width:100%;border-collapse:separate;text-align:left;color:#303030;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#087197" align="center"><tbody><tr>'
                       .'<td align="center"><center><div class="dragonecommercezyx987webkit" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;">  <table class="dragonecommercezyx987outer" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                       .'<td> <table class="dragonecommercezyx987layout-preheader" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr class="dragonecommercezyx987one-col">'
                       .'<td class="dragonecommercezyx987inner dragonecommercezyx987contents" style="padding-left:20px;padding-right:20px;padding-bottom:18px;font-size:13px;line-height:14px;padding-top:18px;font-weight:500;color:#303030;">'
                       .'</td></tr></tbody></table></td></tr></tbody></table>'
                       .'</div></center></td></tr></tbody></table><table class="dragonecommercezyx987wrapper dragonecommercezyx987section-" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;table-layout:fixed;width:100%;border-collapse:separate;text-align:left;color:#303030;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF" align="center"><tbody><tr>'
                       .'<td align="center"> <center> <div class="dragonecommercezyx987webkit" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;">  <table class="dragonecommercezyx987outer dragonecommercezyx987boxed-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF"><tbody><tr>'
                       .'<td> <table class="dragonecommercezyx987layout-solologo dragonecommercezyx987boxed dragonecommercezyx987left" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr class="dragonecommercezyx987one-col">'
                       .'<td class="dragonecommercezyx987inner" style="padding-left:18px;padding-right:18px;padding-bottom:18px;padding-top:18px;"> <table width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                       .'<td class="dragonecommercezyx987inner-nested" style="padding-top:12px;padding-bottom:12px;padding-right:0px;padding-left:0px;"> <table class="dragonecommercezyx987contents" style="text-align:left;font-size:16px;line-height:22px;" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                       .'<td class="dragonecommercezyx987logo" style="font-weight:bold;font-size:18px;color:#087197;"><a rel="nofollow noopener noreferrer" target="_blank" href="%%%companyurl%%%" style="text-decoration:none;color:#087197;">%%%companyname%%%</a> </td> </tr></tbody></table>'
                       .'</td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table>'
                       .'</div></center></td></tr></tbody></table><table class="dragonecommercezyx987wrapper dragonecommercezyx987section-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;table-layout:fixed;width:100%;border-collapse:separate;text-align:left;color:#303030;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF" align="center"><tbody><tr>'
                       .'<td align="center"> <center> <div class="dragonecommercezyx987webkit" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;">  <table class="dragonecommercezyx987outer dragonecommercezyx987boxed-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF"><tbody><tr>'
                       .'<td> <table class="dragonecommercezyx987contents dragonecommercezyx987feature-callout-cta dragonecommercezyx987cta" style="color:#303030;" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr class="dragonecommercezyx987two-col">'
                       .'<td class="dragonecommercezyx987inner" style="padding-left:10px;padding-right:10px;"><table class="dragonecommercezyx987contents" style="font-size:16px;line-height:22px;color:#303030;" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                       .'<td class="dragonecommercezyx987feature-callout-bottom" style="padding-top:20px;padding-bottom:20px;padding-right:10px;padding-left:10px;" width="100%" valign="middle"> <table class="dragonecommercezyx987contents" style="font-size:16px;line-height:22px;color:#303030;" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                       .'<td class="dragonecommercezyx987inner-nested" style="padding-top:12px;padding-bottom:12px;padding-right:0px;padding-left:0;" valign="middle">'
                       .'<p class="dragonecommercezyx987h3" style="margin-top:0;margin-bottom:30px !important;font-weight:500;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;font-size:38px;line-height:36px;">%%%title%%%</p>'
                       .'<p>Hi %%%username%%%,</p><p>%%%header%%%</p><p>%%%content%%%</p><p>For more information, check out the <a rel="nofollow noopener noreferrer" target="_blank" href="%%%companyurl%%%">company website</a>.</p><p>Thanks,</p><p>%%%companyname%%%</p></td></tr></tbody></table>'
                       .'<table class="dragonecommercezyx987buttonwrapper dragonecommercezyx987cta-option-standard-tall" style="font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;background-color:#6ca12b;overflow:hidden;border-radius:5px;margin-top:30px;margin-bottom:40px;margin-right:auto;margin-left:0;font-size:16px;line-height:18px;font-weight:bold;" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                       .'<td class="dragonecommercezyx987button">'
                       .'</td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></div></center></td></tr></tbody></table>'
                       .'<table class="dragonecommercezyx987wrapper dragonecommercezyx987section-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;table-layout:fixed;width:100%;border-collapse:separate;text-align:left;color:#303030;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF" align="center"><tbody><tr>'
                       .'<td align="center"> <center> <div class="dragonecommercezyx987webkit" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;">  <table class="dragonecommercezyx987outer" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                       .'<td><div class="dragonecommercezyx987spacer" style="font-size:40px;line-height:40px;display:block;color:#ffffff;text-align:center;">&nbsp;</div> </td> </tr></tbody></table>'
                       .'</div> </center> </td> </tr></tbody></table><table class="dragonecommercezyx987wrapper dragonecommercezyx987section-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;table-layout:fixed;width:100%;border-collapse:separate;text-align:left;color:#303030;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF" align="center"><tbody><tr>'
                       .'<td align="center"> <center> <div class="dragonecommercezyx987webkit" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;">  <table class="dragonecommercezyx987outer dragonecommercezyx987boxed-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF"><tbody><tr>'
                       .'<td><table class="dragonecommercezyx987footer-container" width="100%" cellspacing="0" cellpadding="0" border="0" align="center">'
                       .'<tbody><tr class="dragonecommercezyx987one-col">'
                       .'<td class="dragonecommercezyx987inner dragonecommercezyx987footer-row-top" style="padding-left:20px;padding-right:20px;padding-bottom:0px;padding-top:20px;"> <table class="dragonecommercezyx987fluid" style="border-top-width:2px;border-top-style:solid;border-top-color:#ECECEE;border-bottom-width:2px;border-bottom-style:solid;border-bottom-color:#ECECEE;" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr>'
                       .'<td class="dragonecommercezyx987hh-force-col-center" style="text-align:center;padding-top:25px;padding-bottom:40px;padding-right:0;padding-left:0;" valign="top"> <a rel="nofollow noopener noreferrer" target="_blank" href="%%%companyurl%%%" style="text-decoration:none;color:#959597;">%%%companyname%%%</a> </td> </tr></tbody></table>'
                       .'</td></tr>'
                       .'<tr class="dragonecommercezyx987one-col"><td class="dragonecommercezyx987inner dragonecommercezyx987footer-row-bottom" style="padding-left:20px;padding-right:20px;padding-bottom:0px;padding-top:20px;"> <table class="dragonecommercezyx987fluid" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr>'
                       .'<td class="dragonecommercezyx987hh-force-col-center dragonecommercezyx987footer-text-left" style="text-align:left;padding-top:0px;padding-bottom:40px;padding-right:0;padding-left:0;" valign="top">'
                       .'<p style="display:none;"></p></td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></div></center></td></tr></tbody></table></div></div></div>';
                $msg = str_replace("%%%companyname%%%", $websiteurl, $msg);                            
                $msg = str_replace("%%%title%%%", $websiteurl, $msg);
                
                $content = 'If that person is you, you need to click this link to activate your account within 24 hours:<br/><br/> <a href="' . $activationlink . '">' . $activationlink . '</a>';
                $msg = str_replace("%%%username%%%", $username, $msg);
                $msg = str_replace("%%%header%%%", 'Congratulations! Someone requested to resend account activation email to this email address on %%%companyurl%%%', $msg);
                $msg = str_replace("%%%content%%%", $content, $msg);
                $msg = str_replace("%%%companyurl%%%", $websiteurl, $msg);                                                                                    
                $msg = str_replace("%%%address1%%%", '', $msg);                                                                                    
                $msg = str_replace("%%%address2%%%", '', $msg);
                            
                if($setting_email_method === 'WordPress Email') {
                    $headers = 'From: '. $bccemail . "\r\n" .
                        'Reply-To: ' . $email . "\r\n" .
                        'Bcc: ' . $bccemail . "\r\n";
                     
                    //Here put your Validation and send mail
                    add_filter('wp_mail_content_type', function($content_type) {
                                return 'text/html';
                    });
                    $sent = wp_mail($email, $subject, $msg, $headers);
                    if($sent) {
                    } else {//message wasn't sent
                        $finalresult .= "Registration email was not sent to you. Please contact website admin. ";
                        dragonecommercereservezyx987_saveToLogTable($finalresult, 'account activation', 'error');                        
                    }        
                } elseif($setting_email_method === 'Mailgun') {
                    $data = array(
                        'from' => $mailgun_fromname . ' <mailgun@' . $mailgun_domain . '>',
                        'to' => $email,
                        'bcc' => $bccemail,
                        'subject' => $subject,
                        'html' => $msg,
                        'o:tracking' => false);
                    $auth = base64_encode('api:'.$mailgun_api_key);
                    $args = [
                        'headers' => ['Authorization' => "Basic $auth"],
                        'body' => $data
                    ];
                    $mailgun_result = wp_remote_post($mailgun_api_url . $mailgun_domain . '/messages', $args);    
                    if(is_wp_error($mailgun_result)) {
                        $finalresult .= 'Mailgun result: ' . json_encode($mailgun_result);  //$mailgun_result->get_error_message();
                        $emailsent = 0;
                    }
                } elseif($setting_email_method === 'Mailchimp') {
                    $data = array(
                        "key"=> $mailchimp_api_key, 
                        "message"=> array(
                            "from_email"=> $mailchimp_fromemail,
                            "from_name"=> $mailchimp_fromname,
                            "subject"=> $subject, 
                            "html"=> $msg,
                            "to"=> array(array("email"=> $email, "name"=> "", "type"=>"to"), array("email"=> $bccemail, "name"=> "", "type"=>"bcc")),
                            "track_opens"=>true,
                            "track_clicks"=>true
                        )
                    );
                    $data2 = json_encode($data);
                    $auth = base64_encode('authorization: apikey '.$mailchimp_api_key);
                    $args = [
                        'headers' => ['Authorization' => "Basic $auth"],
                        'body' => $data2
                    ];
                    $response = wp_remote_post($mailchimp_api_url, $args);
                    if(is_wp_error($response)) {
                        $finalresult .= 'Mailchimp result: ' . $response->get_error_message();
                        $emailsent = 0;
                    }
                    //$response = json_decode($response0, true);
                    if($response !== null && is_array($response) && count($response) > 0 && isset($response[0]["status"]) && ($response[0]["status"] === 'rejected' || $response[0]["status"] === 'invalid')) {
                        $finalresult .= 'Mailchimp result: ' . json_encode($response);
                        $emailsent = 0;
                    }
                    //error_log("at 13979, mailchimp send email response: " . $response[0]["status"] . ", error: " . $finalresult);                
                } elseif($setting_email_method === 'SendGrid') {
                    $data = array(
                        "personalizations"=> array(
                            array(
                                "to"=> array(array("email"=> $email)),
                                "bcc"=> array(array("email"=> $bccemail))
                            )
                        ), 
                        "from"=>array(
                            "email"=> $sendgrid_fromemail,
                            "name"=> $sendgrid_fromname
                        ),
                        "subject"=>$subject,
                        "content"=>array(
                            array(
                                "type"=> "text/html", 
                                "value"=> $msg
                            )                            
                        )
                    );
                    $data2 = json_encode($data);
                    //$auth = base64_encode('api:'.$sendgrid_api_key);
                    $args = array(
                        'headers' => array("Authorization" => "Bearer " . $sendgrid_api_key, "Content-Type" => "application/json"),
                        'body' => $data2
                    );    
                    $response = wp_remote_post($sendgrid_api_url, $args);    
                    if(is_wp_error($response)) {
                        $finalresult .= 'SendGrid result: ' . $response->get_error_message();
                        $emailsent = 0;
                    }
                    //$response = json_decode($response0, true);
                    if($response !== null && $response !== '' && is_array($response) && count($response) > 0 && (!empty($response["body"]["errors"]))) {
                        $finalresult .= 'SendGrid result: ' . json_encode($response);
                        $emailsent = 0;
                    }
                    //error_log("at 14016, sendgrid send email response: " . $response0 . ", error: " . $finalresult);                        
                }    
                if($finalresult === '') {                
                    $finalresult .= "Success. Please check your email to activate your account.";
                }
                echo esc_html($finalresult);
                exit();                                                
            } else {
                echo "We found " . count($result) . " user(s) for this email address. Please contact website admin.";
                exit();                
            }
        } else {
            echo 'This website can not use mysqli. Please contact website admin.';
            exit();
        }    
    }
    echo "Invalid details.";
    exit();    
}

add_action('wp_ajax_dragonecommercereservezyx987_resetpassword', 'dragonecommercereservezyx987_resetPassword');
add_action('wp_ajax_nopriv_dragonecommercereservezyx987_resetpassword', 'dragonecommercereservezyx987_resetPassword'); 
function dragonecommercereservezyx987_resetPassword() {
    check_ajax_referer('dragonecommercereservezyx987_resetpassword', 'dragonecommercereservezyx987_hidden_security_resetpassword');
    if((!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        global $wpdb;        
        $email = empty($_POST['email']) ? '' : sanitize_text_field($_POST['email']);
        $email = stripslashes(strip_tags($email));    
        $validationerror = '';        
        // Check email address is present and valid  
        $email = $wpdb->escape($email);  
        if(empty($email)) {   
            $validationerror .= "Please enter an email address";  
        } elseif(!is_email($email)) {   
            $validationerror .= "Please enter a valid email address";  
        } elseif(!email_exists($email)) {  
            $validationerror .= "This email address is not in use";  
        }
        if($validationerror !== '') {echo esc_html($validationerror); exit();}
        $setting_email_method = ''; 
        $mailgun_api_key = "";
        $mailgun_api_url = "";
        $mailgun_domain = "";
        $mailgun_fromname = 'NO-REPLY';    
        $mailchimp_api_key = "";
        $mailchimp_api_url = "";
        $mailchimp_fromemail = "";
        $mailchimp_fromname = "";
        $sendgrid_api_key = "";
        $sendgrid_api_url = "";
        $sendgrid_fromemail = "";
        $sendgrid_fromname = "";
        
        $table_name = 'wp_dragonecommercereservezyx987_emailmethod';
        $table_name2 = 'wp_dragonecommercereservezyx987_setting';
        $query = "SELECT a.name, b.name as 'settingname', b.value from $table_name a RIGHT JOIN $table_name2 b ON  CAST(b.value AS UNSIGNED) = a.id ";
        $query .= " WHERE b.name IN ('EMAIL_METHOD','MAILGUN_APIKEY','MAILGUN_DOMAIN','MAILGUN_API_URL','MAILGUN_FROMNAME',";
        $query .= " 'MAILCHIMP_APIKEY','MAILCHIMP_API_URL','MAILCHIMP_FROMEMAIL','MAILCHIMP_FROMNAME','SENDGRID_APIKEY','SENDGRID_API_URL','SENDGRID_FROMEMAIL','SENDGRID_FROMNAME') ";
        $result = $wpdb->get_results($query);                
        if(count($result) > 0) {
            for($i=0; $i<count($result); $i++) {
                if($result[$i]->settingname === 'EMAIL_METHOD') {
                   $setting_email_method = trim($result[$i]->name);
                } elseif($result[$i]->settingname === 'MAILGUN_APIKEY') {
                   $mailgun_api_key = $result[$i]->value;
                } elseif($result[$i]->settingname === 'MAILGUN_API_URL') {
                   $mailgun_api_url = $result[$i]->value;
                } elseif($result[$i]->settingname === 'MAILGUN_DOMAIN') {
                   $mailgun_domain = $result[$i]->value;
                } elseif($result[$i]->settingname === 'MAILGUN_FROMNAME') {
                   $mailgun_fromname = $result[$i]->value;
                } elseif($result[$i]->settingname === 'MAILCHIMP_APIKEY') {
                   $mailchimp_api_key = $result[$i]->value;
                } elseif($result[$i]->settingname === 'MAILCHIMP_API_URL') {
                   $mailchimp_api_url = $result[$i]->value;
                } elseif($result[$i]->settingname === 'MAILCHIMP_FROMEMAIL') {
                   $mailchimp_fromemail = $result[$i]->value;
                } elseif($result[$i]->settingname === 'MAILCHIMP_FROMNAME') {
                   $mailchimp_fromname = $result[$i]->value;
                } elseif($result[$i]->settingname === 'SENDGRID_APIKEY') {
                   $sendgrid_api_key = $result[$i]->value;
                } elseif($result[$i]->settingname === 'SENDGRID_API_URL') {
                   $sendgrid_api_url = $result[$i]->value;
                } elseif($result[$i]->settingname === 'SENDGRID_FROMEMAIL') {
                   $sendgrid_fromemail = $result[$i]->value;
                } elseif($result[$i]->settingname === 'SENDGRID_FROMNAME') {
                   $sendgrid_fromname = $result[$i]->value;
                }                                            
            }
        }
        $result = null;        
        if(trim($setting_email_method) === '') {
            $temp = "Email method is not set by website admin. Please contact website admin.";
            dragonecommercereservezyx987_saveToLogTable($temp, 'reset password', 'error');            
            echo esc_html($temp);
            exit();
        }
        if($setting_email_method === 'Mailgun') {                    
            if($mailgun_api_key === '' || $mailgun_domain === '' || $mailgun_api_url === '') {            
                $dragon_ecommerce_dbResult .= "Mailgun email settings are not set by website admin. Please contact website admin. ";
                dragonecommercereservezyx987_saveToLogTable($dragon_ecommerce_dbResult, 'reset password', 'error', intval($current_user->data->ID));                            
                throw new Exception($dragon_ecommerce_dbResult);
            }
            //if mailgun_api_url does not end with /, add /
            if($mailgun_api_url !== null && $mailgun_api_url !== '' && substr($mailgun_api_url, -1, 1) !== '/') {
                $mailgun_api_url = $mailgun_api_url . "/";
            }                        
        }                    
        if($setting_email_method === 'Mailchimp') {                    
            if($mailchimp_api_key === '' || $mailchimp_fromemail === '' || $mailchimp_api_url === '') {        
                $dragon_ecommerce_dbResult .= "Mailchimp email settings are not set by website admin. Please contact website admin. ";
                dragonecommercereservezyx987_saveToLogTable($dragon_ecommerce_dbResult, 'reset password', 'error', intval($current_user->data->ID));                                
                throw new Exception($dragon_ecommerce_dbResult);
            }        
        }                    
        if($setting_email_method === 'SendGrid') {                    
            if($sendgrid_api_key === '' || $sendgrid_fromemail === '' || $sendgrid_api_url === '') {            
                $dragon_ecommerce_dbResult .= "SendGrid email settings are not set by website admin. Please contact website admin. ";
                dragonecommercereservezyx987_saveToLogTable($dragon_ecommerce_dbResult, 'reset password', 'error', intval($current_user->data->ID));                                
                throw new Exception($dragon_ecommerce_dbResult);
            }        
        }        
        $table_name = $wpdb->prefix . 'users';
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $stmt = $wpdb->dbh->prepare("SELECT ID, user_login FROM $table_name WHERE user_email = ?");
            $stmt->bind_param("s", $email); 
            $stmt->execute();
            $myresult = $stmt->get_result();
            $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            
            if(count($result) === 1) {
                //send email
                $bccemail = get_option('admin_email');        
                $finalresult = '';        
                   $t = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!$@!abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                $randomtoken = str_shuffle($t);        
                $user_id = $result[0]["ID"];
                $username = $result[0]["user_login"];
                
                //add a record to _user_token table for this user_id with a new token
                $table_name = 'wp_dragonecommercereservezyx987_user_token';         
                $result = $wpdb->query($wpdb->prepare("INSERT INTO $table_name (`userid`,`tokenpurpose`,`token`,`tokensentdatetimeutc`,`createtimeutc`) VALUES (%d, %s, %s, UTC_TIMESTAMP(), UTC_TIMESTAMP())", array($user_id, 'RESET_PASSWORD', $randomtoken)));
                
                if($result === FALSE || $result === 0) {
                    $finalresult .= "User info was not added to user token table. Please contact website admin. ";
                    dragonecommercereservezyx987_saveToLogTable($finalresult, 'reset password', 'error');                        
                }                            
                $websiteurl = sanitize_text_field($_POST['pluginurl']);
                $subject = $websiteurl . " reset password";
                $msg = '<div id="dragonecommercezyx987"><title></title>'
                       .'<style type="text/css">@media screen and (max-width:449px) {#dragonecommercezyx987 .dragonecommercezyx987standalone-paragraph-huge-left .dragonecommercezyx987inner-nested {font-size:26px !important;line-height:30px !important;}}@media screen and (max-width:449px) {'
                       .'#dragonecommercezyx987 .dragonecommercezyx987standalone-paragraph-huge-center .dragonecommercezyx987inner-nested {font-size:26px !important;line-height:30px !important;}}@media screen and (min-width:5px) {#dragonecommercezyx987 body {}#dragonecommercezyx987 .dragonecommercezyx987outer, #dragonecommercezyx987 .dragonecommercezyx987webkit {width:100% !important;min-width:0 !important;max-width:580px !important;}'
                       .'#dragonecommercezyx987 .dragonecommercezyx987section-dark .dragonecommercezyx987inner-nested a {color:#FFFFFF !important;text-decoration:underline !important;}}@media screen and (max-width:449px) {#dragonecommercezyx987 .dragonecommercezyx987contents {font-size:15px !important;line-height:1.625em !important;}#dragonecommercezyx987 .dragonecommercezyx987column, #dragonecommercezyx987 .dragonecommercezyx987image img {max-width:99% !important;}'
                       .'#dragonecommercezyx987 .dragonecommercezyx987three-col .dragonecommercezyx987contents, #dragonecommercezyx987 .dragonecommercezyx987two-col .dragonecommercezyx987contents {font-size:13px !important;}#dragonecommercezyx987 .dragonecommercezyx987three-col .dragonecommercezyx987column img, #dragonecommercezyx987 .dragonecommercezyx987four-col .dragonecommercezyx987column img {max-width:100% !important;}'
                       .'#dragonecommercezyx987 .dragonecommercezyx987one-col .dragonecommercezyx987h6, #dragonecommercezyx987 .dragonecommercezyx987three-col .dragonecommercezyx987h6, #dragonecommercezyx987 .dragonecommercezyx987four-col .dragonecommercezyx987h6, #dragonecommercezyx987 .dragonecommercezyx987two-col .dragonecommercezyx987h6 {font-size:13px !important;margin-bottom:2px !important;}#dragonecommercezyx987 .dragonecommercezyx987h1 {font-size:26px !important;'
                       .'line-height:30px !important;}#dragonecommercezyx987 .dragonecommercezyx987h3 {font-size:26px !important;}}@media screen and (min-width:450px) and (max-width:600px) {#dragonecommercezyx987 .dragonecommercezyx987two-col .dragonecommercezyx987buffered, #dragonecommercezyx987 .dragonecommercezyx987four-col .dragonecommercezyx987buffered, #dragonecommercezyx987 .dragonecommercezyx987three-col .dragonecommercezyx987buffered {padding-left:6px !important;padding-right:6px !important;}'
                       .'#dragonecommercezyx987 .dragonecommercezyx987two-col .dragonecommercezyx987inner, #dragonecommercezyx987 .dragonecommercezyx987four-col .dragonecommercezyx987inner, #dragonecommercezyx987 .dragonecommercezyx987three-col .dragonecommercezyx987inner {}}@media screen and (max-width:449px) {#dragonecommercezyx987 .dragonecommercezyx987buffered {padding-left:0 !important;padding-right:0 !important;}}'
                       .'@media screen and (min-width:450px) and (max-width:655px) {#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987narrow {max-width:40% !important;}#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987wide {max-width:60% !important;}#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987image img {max-width:100% !important;}'
                       .'#dragonecommercezyx987 .dragonecommercezyx987left-round {text-align:left !important;}#dragonecommercezyx987 .dragonecommercezyx987right-round {text-align:right !important;}}@media screen and (max-width:600px) {#dragonecommercezyx987 .dragonecommercezyx987preheader {display:none !important;}#dragonecommercezyx987 .dragonecommercezyx987layout-preheader .dragonecommercezyx987inner {padding:10px !important;}#dragonecommercezyx987 .dragonecommercezyx987webversion {text-align:center !important;}'
                       .'#dragonecommercezyx987 .dragonecommercezyx987inner {padding-left:7% !important;padding-right:7% !important;}#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar p {font-size:13px !important;line-height:1.6em !important;}#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987h3 {font-size:21px !important;}#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987h5 {font-size:13px !important;}'
                       .'#dragonecommercezyx987 .dragonecommercezyx987mob-hide {display:none !important;}}@media screen and (min-width:5px) {#dragonecommercezyx987 img {height:auto !important;max-width:100% !important;}#dragonecommercezyx987 .dragonecommercezyx987hide {display:none !important;}}@media screen and (min-width:656px) {#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987narrow {max-width:31% !important;}'
                       .'#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987wide {max-width:69% !important;}}@media screen and ( _filtered_a )</style>'
                       .'<div><table class="dragonecommercezyx987hide" style="width:580px;min-width:580px;" cellspacing="0" cellpadding="0" border="0"><tbody><tr><td style="font-size:1px;line-height:1px;min-width:580px;" width="580"></td></tr></tbody></table>'
                       .'<div class="dragonecommercezyx987ios9"> &nbsp;<table class="dragonecommercezyx987wrapper dragonecommercezyx987section-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;table-layout:fixed;width:100%;border-collapse:separate;text-align:left;color:#303030;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#087197" align="center"><tbody><tr>'
                       .'<td align="center"><center><div class="dragonecommercezyx987webkit" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;">  <table class="dragonecommercezyx987outer" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                       .'<td> <table class="dragonecommercezyx987layout-preheader" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr class="dragonecommercezyx987one-col">'
                       .'<td class="dragonecommercezyx987inner dragonecommercezyx987contents" style="padding-left:20px;padding-right:20px;padding-bottom:18px;font-size:13px;line-height:14px;padding-top:18px;font-weight:500;color:#303030;">'
                       .'</td></tr></tbody></table></td></tr></tbody></table>'
                       .'</div></center></td></tr></tbody></table><table class="dragonecommercezyx987wrapper dragonecommercezyx987section-" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;table-layout:fixed;width:100%;border-collapse:separate;text-align:left;color:#303030;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF" align="center"><tbody><tr>'
                       .'<td align="center"> <center> <div class="dragonecommercezyx987webkit" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;">  <table class="dragonecommercezyx987outer dragonecommercezyx987boxed-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF"><tbody><tr>'
                       .'<td> <table class="dragonecommercezyx987layout-solologo dragonecommercezyx987boxed dragonecommercezyx987left" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr class="dragonecommercezyx987one-col">'
                       .'<td class="dragonecommercezyx987inner" style="padding-left:18px;padding-right:18px;padding-bottom:18px;padding-top:18px;"> <table width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                       .'<td class="dragonecommercezyx987inner-nested" style="padding-top:12px;padding-bottom:12px;padding-right:0px;padding-left:0px;"> <table class="dragonecommercezyx987contents" style="text-align:left;font-size:16px;line-height:22px;" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                       .'<td class="dragonecommercezyx987logo" style="font-weight:bold;font-size:18px;color:#087197;"><a rel="nofollow noopener noreferrer" target="_blank" href="%%%companyurl%%%" style="text-decoration:none;color:#087197;">%%%companyname%%%</a> </td> </tr></tbody></table>'
                       .'</td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table>'
                       .'</div></center></td></tr></tbody></table><table class="dragonecommercezyx987wrapper dragonecommercezyx987section-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;table-layout:fixed;width:100%;border-collapse:separate;text-align:left;color:#303030;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF" align="center"><tbody><tr>'
                       .'<td align="center"> <center> <div class="dragonecommercezyx987webkit" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;">  <table class="dragonecommercezyx987outer dragonecommercezyx987boxed-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF"><tbody><tr>'
                       .'<td> <table class="dragonecommercezyx987contents dragonecommercezyx987feature-callout-cta dragonecommercezyx987cta" style="color:#303030;" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr class="dragonecommercezyx987two-col">'
                       .'<td class="dragonecommercezyx987inner" style="padding-left:10px;padding-right:10px;"><table class="dragonecommercezyx987contents" style="font-size:16px;line-height:22px;color:#303030;" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                       .'<td class="dragonecommercezyx987feature-callout-bottom" style="padding-top:20px;padding-bottom:20px;padding-right:10px;padding-left:10px;" width="100%" valign="middle"> <table class="dragonecommercezyx987contents" style="font-size:16px;line-height:22px;color:#303030;" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                       .'<td class="dragonecommercezyx987inner-nested" style="padding-top:12px;padding-bottom:12px;padding-right:0px;padding-left:0;" valign="middle">'
                       .'<p class="dragonecommercezyx987h3" style="margin-top:0;margin-bottom:30px !important;font-weight:500;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;font-size:38px;line-height:36px;">%%%title%%%</p>'
                       .'<p>Hi %%%username%%%,</p><p>%%%header%%%</p><p>%%%content%%%</p><p>For more information, check out the <a rel="nofollow noopener noreferrer" target="_blank" href="%%%companyurl%%%">company website</a>.</p><p>Thanks,</p><p>%%%companyname%%%</p></td></tr></tbody></table>'
                       .'<table class="dragonecommercezyx987buttonwrapper dragonecommercezyx987cta-option-standard-tall" style="font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;background-color:#6ca12b;overflow:hidden;border-radius:5px;margin-top:30px;margin-bottom:40px;margin-right:auto;margin-left:0;font-size:16px;line-height:18px;font-weight:bold;" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                       .'<td class="dragonecommercezyx987button">'
                       .'</td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></div></center></td></tr></tbody></table>'
                       .'<table class="dragonecommercezyx987wrapper dragonecommercezyx987section-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;table-layout:fixed;width:100%;border-collapse:separate;text-align:left;color:#303030;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF" align="center"><tbody><tr>'
                       .'<td align="center"> <center> <div class="dragonecommercezyx987webkit" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;">  <table class="dragonecommercezyx987outer" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                       .'<td><div class="dragonecommercezyx987spacer" style="font-size:40px;line-height:40px;display:block;color:#ffffff;text-align:center;">&nbsp;</div> </td> </tr></tbody></table>'
                       .'</div> </center> </td> </tr></tbody></table><table class="dragonecommercezyx987wrapper dragonecommercezyx987section-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;table-layout:fixed;width:100%;border-collapse:separate;text-align:left;color:#303030;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF" align="center"><tbody><tr>'
                       .'<td align="center"> <center> <div class="dragonecommercezyx987webkit" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;">  <table class="dragonecommercezyx987outer dragonecommercezyx987boxed-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF"><tbody><tr>'
                       .'<td><table class="dragonecommercezyx987footer-container" width="100%" cellspacing="0" cellpadding="0" border="0" align="center">'
                       .'<tbody><tr class="dragonecommercezyx987one-col">'
                       .'<td class="dragonecommercezyx987inner dragonecommercezyx987footer-row-top" style="padding-left:20px;padding-right:20px;padding-bottom:0px;padding-top:20px;"> <table class="dragonecommercezyx987fluid" style="border-top-width:2px;border-top-style:solid;border-top-color:#ECECEE;border-bottom-width:2px;border-bottom-style:solid;border-bottom-color:#ECECEE;" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr>'
                       .'<td class="dragonecommercezyx987hh-force-col-center" style="text-align:center;padding-top:25px;padding-bottom:40px;padding-right:0;padding-left:0;" valign="top"> <a rel="nofollow noopener noreferrer" target="_blank" href="%%%companyurl%%%" style="text-decoration:none;color:#959597;">%%%companyname%%%</a> </td> </tr></tbody></table>'
                       .'</td></tr>'
                       .'<tr class="dragonecommercezyx987one-col"><td class="dragonecommercezyx987inner dragonecommercezyx987footer-row-bottom" style="padding-left:20px;padding-right:20px;padding-bottom:0px;padding-top:20px;"> <table class="dragonecommercezyx987fluid" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr>'
                       .'<td class="dragonecommercezyx987hh-force-col-center dragonecommercezyx987footer-text-left" style="text-align:left;padding-top:0px;padding-bottom:40px;padding-right:0;padding-left:0;" valign="top">'
                       .'<p style="display:none;"></p></td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></div></center></td></tr></tbody></table></div></div></div>';
                $msg = str_replace("%%%companyname%%%", $websiteurl, $msg);                            
                $msg = str_replace("%%%title%%%", $websiteurl, $msg);                
                $content = 'If that person is NOT you, please IGNORE this email.<br/><br/>If that person is you, you need to go to the website to reset your password using your token within 24 hours:<br/> <a href="' . $websiteurl . '">' . $websiteurl . '</a>' . '<br/><br/>Here is your token: <br/>' . $randomtoken;
                $msg = str_replace("%%%username%%%", $username, $msg);
                $msg = str_replace("%%%header%%%", 'Someone requested to reset password on %%%companyurl%%%', $msg);
                $msg = str_replace("%%%content%%%", $content, $msg);
                $msg = str_replace("%%%companyurl%%%", $websiteurl, $msg);                                                                                    
                $msg = str_replace("%%%address1%%%", '', $msg);                                                                                    
                $msg = str_replace("%%%address2%%%", '', $msg);
                            
                if($setting_email_method === 'WordPress Email') {
                    $headers = 'From: '. $bccemail . "\r\n" .
                        'Reply-To: ' . $email . "\r\n" .
                        'Bcc: ' . $bccemail . "\r\n";
                     
                    //Here put your Validation and send mail
                    add_filter('wp_mail_content_type', function($content_type) {
                                return 'text/html';
                    });
                    $sent = wp_mail($email, $subject, $msg, $headers);
                    if($sent) {
                    } else {//message wasn't sent
                        $finalresult .= "Reset email was not sent to you. Please contact website admin. ";
                        dragonecommercereservezyx987_saveToLogTable($finalresult, 'reset password', 'error');                            
                    }                        
                } elseif($setting_email_method === 'Mailgun') {
                    $data = array(
                        'from' => $mailgun_fromname . ' <mailgun@' . $mailgun_domain . '>',
                        'to' => $email,
                        'bcc' => $bccemail,
                        'subject' => $subject,
                        'html' => $msg,
                        'o:tracking' => false);
                    $auth = base64_encode('api:'.$mailgun_api_key);
                    $args = [
                        'headers' => ['Authorization' => "Basic $auth"],
                        'body' => $data
                    ];
                    $mailgun_result = wp_remote_post($mailgun_api_url . $mailgun_domain . '/messages', $args);    
                    if(is_wp_error($mailgun_result)) {
                        $finalresult .= 'Mailgun result: ' . json_encode($mailgun_result);  //$mailgun_result->get_error_message();
                        $emailsent = 0;
                    }
                } elseif($setting_email_method === 'Mailchimp') {
                    $data = array(
                        "key"=> $mailchimp_api_key, 
                        "message"=> array(
                            "from_email"=> $mailchimp_fromemail,
                            "from_name"=> $mailchimp_fromname,
                            "subject"=> $subject, 
                            "html"=> $msg,
                            "to"=> array(array("email"=> $email, "name"=> "", "type"=>"to"), array("email"=> $bccemail, "name"=> "", "type"=>"bcc")),
                            "track_opens"=>true,
                            "track_clicks"=>true
                        )
                    );
                    $data2 = json_encode($data);
                    $auth = base64_encode('authorization: apikey '.$mailchimp_api_key);
                    $args = [
                        'headers' => ['Authorization' => "Basic $auth"],
                        'body' => $data2
                    ];
                    $response = wp_remote_post($mailchimp_api_url, $args);
                    if(is_wp_error($response)) {
                        $finalresult .= 'Mailchimp result: ' . $response->get_error_message();
                        $emailsent = 0;
                    }
                    //$response = json_decode($response0, true);
                    if($response !== null && is_array($response) && count($response) > 0 && isset($response[0]["status"]) && ($response[0]["status"] === 'rejected' || $response[0]["status"] === 'invalid')) {
                        $finalresult .= 'Mailchimp result: ' . json_encode($response);
                        $emailsent = 0;
                    }
                    //error_log("at 14291, mailchimp send email response: " . $response[0]["status"] . ", error: " . $finalresult);                
                } elseif($setting_email_method === 'SendGrid') {
                    $data = array(
                        "personalizations"=> array(
                            array(
                                "to"=> array(array("email"=> $email)),
                                "bcc"=> array(array("email"=> $bccemail))
                            )
                        ), 
                        "from"=>array(
                            "email"=> $sendgrid_fromemail,
                            "name"=> $sendgrid_fromname
                        ),
                        "subject"=>$subject,
                        "content"=>array(
                            array(
                                "type"=> "text/html", 
                                "value"=> $msg
                            )                            
                        )
                    );
                    $data2 = json_encode($data);
                    //$auth = base64_encode('api:'.$sendgrid_api_key);
                    $args = array(
                        'headers' => array("Authorization" => "Bearer " . $sendgrid_api_key, "Content-Type" => "application/json"),
                        'body' => $data2
                    );    
                    $response = wp_remote_post($sendgrid_api_url, $args);    
                    if(is_wp_error($response)) {
                        $finalresult .= 'SendGrid result: ' . $response->get_error_message();
                        $emailsent = 0;
                    }
                    //$response = json_decode($response0, true);
                    if($response !== null && $response !== '' && is_array($response) && count($response) > 0 && (!empty($response["body"]["errors"]))) {
                        $finalresult .= 'SendGrid result: ' . json_encode($response);
                        $emailsent = 0;
                    }
                    //error_log("at 14328, sendgrid send email response: " . $response0 . ", error: " . $finalresult);                        
                }    
                if($finalresult === '') {
                    $finalresult = "Success. Please check your email to get your token and reset your password.";
                }
                echo esc_html($finalresult);
                exit();                                
            } else {
                echo "We found " . count($result) . " user(s) for this email address. Please contact website admin.";
                exit();                
            }
        } else {
            echo 'This website can not use mysqli. Please contact website admin.';
            exit();
        }    
    }
    echo "Invalid details.";
    exit();    
}

add_action('wp_ajax_dragonecommercereservezyx987_resetpasswordusingtoken', 'dragonecommercereservezyx987_resetPasswordUsingToken');
add_action('wp_ajax_nopriv_dragonecommercereservezyx987_resetpasswordusingtoken', 'dragonecommercereservezyx987_resetPasswordUsingToken'); 
function dragonecommercereservezyx987_resetPasswordUsingToken() {
    check_ajax_referer('dragonecommercereservezyx987_resetpasswordusingtoken', 'dragonecommercereservezyx987_hidden_security_resetpasswordusingtoken');
    if((!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        global $wpdb;
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }            
            $username = empty($_POST['username']) ? '' : sanitize_text_field($_POST['username']);
            $username = strip_tags($username);
            
            $password = empty($_POST['password']) ? '' : sanitize_text_field($_POST['password']);
            $password = strip_tags($password);

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

            $validatoinerror = '';

            // Check password is valid  
            if(0 === preg_match("/.{8,}/", $password)) {  
               $validatoinerror .= "Password must be at least eight characters. ";  
            }  
            
            //password should only contain 0-9, a-z, A-Z, at least one of special characters such as !@#*()$%^&. No ' " < > and other characters are allowed
            if(0 === preg_match("/^[0-9a-zA-Z!@#*()$%^&]+$/", $password)) {  
               $validatoinerror .= "Password should only contain 0-9, a-z, A-Z, special characters (such as !@#*()$%^&). ";  
            }            

            //password should only at least one of special characters such as %?#!&$. No ' " and other characters are allowed
            if(1 === preg_match("/^[0-9a-zA-Z]+$/", $password)) {  
               $validatoinerror .= "Password should contain at least one of special characters (such as !@#*()$%^&). ";  
            } 
            
            // Check password confirmation_matches  
            if(0 !== strcmp($password, $password2)) {  
               $validatoinerror .= "Passwords do not match. ";  
            }  
            
            $password = trim($password); 
            if(empty($password)) {   
                 $validatoinerror .= "Please enter a password. ";  
            }
                        
            if($validatoinerror !== '') {echo esc_html($validatoinerror); exit();}
                
            $token = empty($_POST['resettoken']) ? '' : strip_tags($_POST['resettoken']);

            $table_name = 'wp_dragonecommercereservezyx987_user_status';    
            $table_name2 = 'wp_dragonecommercereservezyx987_user_token';
            $table_name3 = $wpdb->prefix . 'users';
            
            $query = "SELECT c.ID 'userid', c.user_pass 'password', a.id 'userstatutableid', b.id 'usertokentableid',b.token, b.tokensentdatetimeutc,b.tokenverified from $table_name a JOIN $table_name2 b ON a.userid = b.userid and a.status = 1 and a.user_status = 1 and b.tokenpurpose = 'RESET_PASSWORD' and b.token = ? and b.status = 1 AND b.tokenverified = 0 JOIN $table_name3 c ON c.user_login = ? AND c.ID = a.userid";
            $stmt = $wpdb->dbh->prepare($query);
            $stmt->bind_param("ss", $token, $username);
            $stmt->execute();
            $myresult = $stmt->get_result();
            $result = $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            $usertokenrecordfound = false;
            $userstatustableid = 0;
            $usertokentableid = 0;
            $userid = 0;
            $userhashedpassword = '';
            $matchcounter = 0;
            $error = '';
            $finalresult = '';
            if(count($result) > 0) {
                foreach($result as $temp) {
                    $datestring24hourago = gmdate("Y-m-d H:i:s", strtotime('-24 hours', time()));                        
                    if($temp["tokensentdatetimeutc"] >= $datestring24hourago) {
                        if($temp["token"] === $token) {
                            $usertokenrecordfound = true;
                            $userstatustableid = $temp["userstatutableid"];
                            $usertokentableid = $temp["usertokentableid"];
                            $userid = $temp["userid"];
                            $userhashedpassword = $temp["password"];
                            $matchcounter++;
                        }
                    } else {
                        $error .= 'Token expired. ';                    
                    }
                }
                if($matchcounter !== 1) {
                    $finalresult .= 'Error. Found ' . $matchcounter . ' match(es) to your username and token. ';
                } else {
                    if(wp_check_password($password, $userhashedpassword, $userid)) {
                        echo "Please use a password different from old password."; exit();
                    }
                    //update user password
                    if($userid > 0 && $error === '' && $finalresult === '') {                        
                        $query = "UPDATE $table_name3 SET user_pass = ? WHERE ID = ?";
                        $stmt = $wpdb->dbh->prepare($query);
                        $stmt->bind_param("si", wp_hash_password($password), $userid);
                        $stmt->execute();
                        if($wpdb->dbh->errno > 0 || $stmt->errno > 0) {
                            $finalresult .= 'Update password failed. ';
                        }
                        $stmt->close();                                                            
                    }                    
                    if($usertokentableid > 0 && $error === '' && $finalresult === '') {
                        $myresult2 = $wpdb->query($wpdb->prepare("UPDATE $table_name2 SET tokenverified = 1, tokenverifiedtimeutc = UTC_TIMESTAMP() WHERE id = %d ", array($usertokentableid)));                            
                        if($myresult2 === FALSE || $myresult2 === 0) {
                            $finalresult .= 'Error. The user token table is not updated. ';
                        }            
                    }
                }
                echo $finalresult === '' ? 'Success.' : esc_html($error . $finalresult);
                exit();
            } else {
                echo 'User or token is not found or token already verified.';
                exit();    
            }        
        } else {
            echo "This website can not use mysqli. Please contact website admin.";
            exit();    
        }                                
    }
    echo "Invalid details.";
    exit();    
}

add_action('wp_ajax_dragonecommercereservezyx987_registernewuser', 'dragonecommercereservezyx987_registerNewUser');
add_action('wp_ajax_nopriv_dragonecommercereservezyx987_registernewuser', 'dragonecommercereservezyx987_registerNewUser'); 
function dragonecommercereservezyx987_registerNewUser() {
    check_ajax_referer('dragonecommercereservezyx987_registernewuser', 'dragonecommercereservezyx987_hidden_security_registernewuser');
    if((!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        global $wpdb, $user_ID;
        if($user_ID) 
        {  
            echo "Already logged in.";
            exit();
        } else {           
            $errors = array();               
            if($_SERVER['REQUEST_METHOD'] == 'POST') {                 
                // Check username is present and not already in use  
                $username = sanitize_text_field($_POST['username']);  
                if(strpos($username, ' ') !== false) {   
                    $errors['username'] = "Sorry, no spaces allowed in username";  
                }  
                if(empty($username)) {   
                    $errors['username'] = "Please enter a username";  
                } elseif(username_exists($username)) 
                {  
                    $errors['username'] = "Username already exists, please try another";  
                }               
                // Check email address is present and valid  
                $email = sanitize_email($_POST['email']);  
                if(empty($email)) {   
                    $errors['email'] = "Please enter an email address";  
                } elseif(!is_email($email)) {   
                    $errors['email'] = "Please enter a valid email address";  
                } elseif(email_exists($email)) {  
                    $errors['email'] = "This email address is already in use";  
                } 

                $terms = sanitize_text_field($_POST['terms']); 
                if($terms !== '1') {   
                    $errors['terms'] = "You must agree with the terms and conditions to get registered";
                }                    
           
                // Check password is valid  
                if(0 === preg_match("/.{8,}/", $_POST['password'])) {  
                  $errors['password'] = "Password must be at least eight characters";  
                }  
                
                //password should only contain 0-9, a-z, A-Z, at least one of special characters such as !@#*()$%^&. No ' " < > and other characters are allowed
                if(0 === preg_match("/^[*0-9a-zA-Z!@#*()$%^&]+$/", $_POST['password'])) {  
                  $errors['password'] = "Password should only contain 0-9, a-z, A-Z, special characters (such as !@#*()$%^&)";  
                }            

                //password should only at least one of special characters such as %?#!&$. No ' " and other characters are allowed
                if(1 === preg_match("/^[0-9a-zA-Z]+$/", $_POST['password'])) {  
                  $errors['password'] = "Password should contain at least one of special characters (such as !@#*()$%^&)";  
                } 
                
                // Check password confirmation_matches  
                if(0 !== strcmp($_POST['password'], $_POST['password_confirmation'])) {  
                  $errors['password_confirmation'] = "Passwords do not match";  
                }  
                
                $password = trim($_POST['password']); 
                if(empty($password)) {   
                    $errors['password'] = "Please enter a password";  
                }               
           
                if(0 === count($errors)) {            
                    $t = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!$@!abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                    $randomtoken = str_shuffle($t);
                       
                    $userdata = array(
                        'user_pass'             => $password,   //(string) The plain-text user password.
                        'user_login'            => $username,   //(string) The user's login username.
                        'user_nicename'         => '',   //(string) The URL-friendly user name.
                        'user_url'              => '',   //(string) The user URL.
                        'user_email'            => $email,   //(string) The user email address.
                        'display_name'          => $email,   //(string) The user's display name. Default is the user's username.
                        'nickname'              => $email,   //(string) The user's nickname. Default is the user's username.
                        'first_name'            => '',   //(string) The user's first name. For new users, will be used to build the first part of the user's display name if $display_name is not specified.
                        'last_name'             => '',   //(string) The user's last name. For new users, will be used to build the second part of the user's display name if $display_name is not specified.
                        'description'           => 'Dragonecommerce customer',   //(string) The user's biographical description.
                        'rich_editing'          => '',   //(string|bool) Whether to enable the rich-editor for the user. False if not empty.
                        'syntax_highlighting'   => '',   //(string|bool) Whether to enable the rich code editor for the user. False if not empty.
                        'comment_shortcuts'     => '',   //(string|bool) Whether to enable comment moderation keyboard shortcuts for the user. Default false.
                        'admin_color'           => 'fresh',   //(string) Admin color scheme for the user. Default 'fresh'.
                        'use_ssl'               => true,   //(bool) Whether the user should always access the admin over https. Default false.
                        'user_registered'       => date("Y-m-d H:i:s"),   //(string) Date the user registered. Format is 'Y-m-d H:i:s'.
                        'show_admin_bar_front'  => true,   //(string|bool) Whether to display the Admin Bar for the user on the site's front end. Default true.
                        'role'                  => 'dragonecommercereservecustomer',   //(string) User's role.
                        'locale'                => '',   //(string) User's locale. Default empty.                         
                    );                        
                    $user_id = wp_insert_user($userdata);
  
                    if(!is_wp_error($user_id) && $user_id > 0) {
                        $finalresult = '';                            
                        //1. add a record to _user_status table for this user id
                        $table_name = 'wp_dragonecommercereservezyx987_user_status';
                        //first, remove old status record if any
                        $result0 = $wpdb->query($wpdb->prepare("DELETE FROM $table_name where `userid`=%d", array($user_id)));                        
                        $result = $wpdb->query($wpdb->prepare("INSERT INTO $table_name (`userid`,`createtimeutc`) VALUES (%d, UTC_TIMESTAMP())", array($user_id)));                            
                        if($result === FALSE) {
                            $finalresult .= "New user info was not added to user status table. Please contact website admin. ";
                            dragonecommercereservezyx987_saveToLogTable($finalresult, 'register new user', 'error', $user_id);                            
                        }
                        
                        //2. add a record to _user_token table for this user_id with a new token
                        $table_name = 'wp_dragonecommercereservezyx987_user_token';
                        $result = $wpdb->query($wpdb->prepare("INSERT INTO $table_name (`userid`,`tokenpurpose`,`token`,`tokensentdatetimeutc`,`createtimeutc`) VALUES (%d, %s, %s, UTC_TIMESTAMP(), UTC_TIMESTAMP())", array($user_id, 'REGISTER_ACTIVATION', $randomtoken)));                        
                        if($result === FALSE || $result === 0) {
                            $finalresult .= "New user info was not added to user token table. Please contact website admin. ";
                            dragonecommercereservezyx987_saveToLogTable($finalresult, 'register new user', 'error', $user_id);                            
                        }                            

                        //send email to activate account and send error to admin if any
                        //1. get setting table: EMAIL_METHOD
                        $setting_email_method = ''; 
                        $mailgun_api_key = "";
                        $mailgun_api_url = "";
                        $mailgun_domain = "";
                        $mailgun_fromname = 'NO-REPLY';    
                        $mailchimp_api_key = "";
                        $mailchimp_api_url = "";
                        $mailchimp_fromemail = "";
                        $mailchimp_fromname = "";
                        $sendgrid_api_key = "";
                        $sendgrid_api_url = "";
                        $sendgrid_fromemail = "";
                        $sendgrid_fromname = "";
                        
                        $table_name = 'wp_dragonecommercereservezyx987_emailmethod';
                        $table_name2 = 'wp_dragonecommercereservezyx987_setting';
                        $query = "SELECT a.name, b.name as 'settingname', b.value from $table_name a RIGHT JOIN $table_name2 b ON  CAST(b.value AS UNSIGNED) = a.id ";
                        $query .= " WHERE b.name IN ('EMAIL_METHOD','MAILGUN_APIKEY','MAILGUN_DOMAIN','MAILGUN_API_URL','MAILGUN_FROMNAME',";
                        $query .= " 'MAILCHIMP_APIKEY','MAILCHIMP_API_URL','MAILCHIMP_FROMEMAIL','MAILCHIMP_FROMNAME','SENDGRID_APIKEY','SENDGRID_API_URL','SENDGRID_FROMEMAIL','SENDGRID_FROMNAME') ";
                        $result = $wpdb->get_results($query);                
                        if(count($result) > 0) {
                            for($i=0; $i<count($result); $i++) {
                                if($result[$i]->settingname === 'EMAIL_METHOD') {
                                   $setting_email_method = trim($result[$i]->name);
                                } elseif($result[$i]->settingname === 'MAILGUN_APIKEY') {
                                   $mailgun_api_key = $result[$i]->value;
                                } elseif($result[$i]->settingname === 'MAILGUN_API_URL') {
                                   $mailgun_api_url = $result[$i]->value;
                                } elseif($result[$i]->settingname === 'MAILGUN_DOMAIN') {
                                   $mailgun_domain = $result[$i]->value;
                                } elseif($result[$i]->settingname === 'MAILGUN_FROMNAME') {
                                   $mailgun_fromname = $result[$i]->value;
                                } elseif($result[$i]->settingname === 'MAILCHIMP_APIKEY') {
                                   $mailchimp_api_key = $result[$i]->value;
                                } elseif($result[$i]->settingname === 'MAILCHIMP_API_URL') {
                                   $mailchimp_api_url = $result[$i]->value;
                                } elseif($result[$i]->settingname === 'MAILCHIMP_FROMEMAIL') {
                                   $mailchimp_fromemail = $result[$i]->value;
                                } elseif($result[$i]->settingname === 'MAILCHIMP_FROMNAME') {
                                   $mailchimp_fromname = $result[$i]->value;
                                } elseif($result[$i]->settingname === 'SENDGRID_APIKEY') {
                                   $sendgrid_api_key = $result[$i]->value;
                                } elseif($result[$i]->settingname === 'SENDGRID_API_URL') {
                                   $sendgrid_api_url = $result[$i]->value;
                                } elseif($result[$i]->settingname === 'SENDGRID_FROMEMAIL') {
                                   $sendgrid_fromemail = $result[$i]->value;
                                } elseif($result[$i]->settingname === 'SENDGRID_FROMNAME') {
                                   $sendgrid_fromname = $result[$i]->value;
                                }                                            
                            }
                        }
                        $result = null;                                                                                        
                        if(trim($setting_email_method) === '') {                                
                            $finalresult .= "Registered. But email method is not set by website admin. Please contact website admin. ";
                            dragonecommercereservezyx987_saveToLogTable($finalresult, 'register new user', 'error', $user_id);                            
                            echo esc_html($finalresult);
                            exit();
                        }    
                        if($setting_email_method === 'Mailgun') {                    
                            if($mailgun_api_key === '' || $mailgun_domain === '' || $mailgun_api_url === '') {            
                                $dragon_ecommerce_dbResult .= "Mailgun email settings are not set by website admin. Please contact website admin. ";
                                dragonecommercereservezyx987_saveToLogTable($dragon_ecommerce_dbResult, 'register new user', 'error', intval($current_user->data->ID));                            
                                throw new Exception($dragon_ecommerce_dbResult);
                            }
                            //if mailgun_api_url does not end with /, add /
                            if($mailgun_api_url !== null && $mailgun_api_url !== '' && substr($mailgun_api_url, -1, 1) !== '/') {
                                $mailgun_api_url = $mailgun_api_url . "/";
                            }                        
                        }                    
                        if($setting_email_method === 'Mailchimp') {                    
                            if($mailchimp_api_key === '' || $mailchimp_fromemail === '' || $mailchimp_api_url === '') {        
                                $dragon_ecommerce_dbResult .= "Mailchimp email settings are not set by website admin. Please contact website admin. ";
                                dragonecommercereservezyx987_saveToLogTable($dragon_ecommerce_dbResult, 'register new user', 'error', intval($current_user->data->ID));                                
                                throw new Exception($dragon_ecommerce_dbResult);
                            }        
                        }                    
                        if($setting_email_method === 'SendGrid') {                    
                            if($sendgrid_api_key === '' || $sendgrid_fromemail === '' || $sendgrid_api_url === '') {            
                                $dragon_ecommerce_dbResult .= "SendGrid email settings are not set by website admin. Please contact website admin. ";
                                dragonecommercereservezyx987_saveToLogTable($dragon_ecommerce_dbResult, 'register new user', 'error', intval($current_user->data->ID));                                
                                throw new Exception($dragon_ecommerce_dbResult);
                            }        
                        }
                        
                        $bccemail = get_option('admin_email');
                        $websiteurl = sanitize_text_field($_POST['pluginurl']);
                        $activationlink = $websiteurl . '?action=activateaccount&id=' . $user_id . '&token=' . $randomtoken;
                        $subject = $websiteurl . " registration activation";
                        $msg = '<div id="dragonecommercezyx987"><title></title>'
                               .'<style type="text/css">@media screen and (max-width:449px) {#dragonecommercezyx987 .dragonecommercezyx987standalone-paragraph-huge-left .dragonecommercezyx987inner-nested {font-size:26px !important;line-height:30px !important;}}@media screen and (max-width:449px) {'
                               .'#dragonecommercezyx987 .dragonecommercezyx987standalone-paragraph-huge-center .dragonecommercezyx987inner-nested {font-size:26px !important;line-height:30px !important;}}@media screen and (min-width:5px) {#dragonecommercezyx987 body {}#dragonecommercezyx987 .dragonecommercezyx987outer, #dragonecommercezyx987 .dragonecommercezyx987webkit {width:100% !important;min-width:0 !important;max-width:580px !important;}'
                               .'#dragonecommercezyx987 .dragonecommercezyx987section-dark .dragonecommercezyx987inner-nested a {color:#FFFFFF !important;text-decoration:underline !important;}}@media screen and (max-width:449px) {#dragonecommercezyx987 .dragonecommercezyx987contents {font-size:15px !important;line-height:1.625em !important;}#dragonecommercezyx987 .dragonecommercezyx987column, #dragonecommercezyx987 .dragonecommercezyx987image img {max-width:99% !important;}'
                               .'#dragonecommercezyx987 .dragonecommercezyx987three-col .dragonecommercezyx987contents, #dragonecommercezyx987 .dragonecommercezyx987two-col .dragonecommercezyx987contents {font-size:13px !important;}#dragonecommercezyx987 .dragonecommercezyx987three-col .dragonecommercezyx987column img, #dragonecommercezyx987 .dragonecommercezyx987four-col .dragonecommercezyx987column img {max-width:100% !important;}'
                               .'#dragonecommercezyx987 .dragonecommercezyx987one-col .dragonecommercezyx987h6, #dragonecommercezyx987 .dragonecommercezyx987three-col .dragonecommercezyx987h6, #dragonecommercezyx987 .dragonecommercezyx987four-col .dragonecommercezyx987h6, #dragonecommercezyx987 .dragonecommercezyx987two-col .dragonecommercezyx987h6 {font-size:13px !important;margin-bottom:2px !important;}#dragonecommercezyx987 .dragonecommercezyx987h1 {font-size:26px !important;'
                               .'line-height:30px !important;}#dragonecommercezyx987 .dragonecommercezyx987h3 {font-size:26px !important;}}@media screen and (min-width:450px) and (max-width:600px) {#dragonecommercezyx987 .dragonecommercezyx987two-col .dragonecommercezyx987buffered, #dragonecommercezyx987 .dragonecommercezyx987four-col .dragonecommercezyx987buffered, #dragonecommercezyx987 .dragonecommercezyx987three-col .dragonecommercezyx987buffered {padding-left:6px !important;padding-right:6px !important;}'
                               .'#dragonecommercezyx987 .dragonecommercezyx987two-col .dragonecommercezyx987inner, #dragonecommercezyx987 .dragonecommercezyx987four-col .dragonecommercezyx987inner, #dragonecommercezyx987 .dragonecommercezyx987three-col .dragonecommercezyx987inner {}}@media screen and (max-width:449px) {#dragonecommercezyx987 .dragonecommercezyx987buffered {padding-left:0 !important;padding-right:0 !important;}}'
                               .'@media screen and (min-width:450px) and (max-width:655px) {#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987narrow {max-width:40% !important;}#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987wide {max-width:60% !important;}#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987image img {max-width:100% !important;}'
                               .'#dragonecommercezyx987 .dragonecommercezyx987left-round {text-align:left !important;}#dragonecommercezyx987 .dragonecommercezyx987right-round {text-align:right !important;}}@media screen and (max-width:600px) {#dragonecommercezyx987 .dragonecommercezyx987preheader {display:none !important;}#dragonecommercezyx987 .dragonecommercezyx987layout-preheader .dragonecommercezyx987inner {padding:10px !important;}#dragonecommercezyx987 .dragonecommercezyx987webversion {text-align:center !important;}'
                               .'#dragonecommercezyx987 .dragonecommercezyx987inner {padding-left:7% !important;padding-right:7% !important;}#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar p {font-size:13px !important;line-height:1.6em !important;}#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987h3 {font-size:21px !important;}#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987h5 {font-size:13px !important;}'
                               .'#dragonecommercezyx987 .dragonecommercezyx987mob-hide {display:none !important;}}@media screen and (min-width:5px) {#dragonecommercezyx987 img {height:auto !important;max-width:100% !important;}#dragonecommercezyx987 .dragonecommercezyx987hide {display:none !important;}}@media screen and (min-width:656px) {#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987narrow {max-width:31% !important;}'
                               .'#dragonecommercezyx987 .dragonecommercezyx987two-col-sidebar .dragonecommercezyx987wide {max-width:69% !important;}}@media screen and ( _filtered_a )</style>'
                               .'<div><table class="dragonecommercezyx987hide" style="width:580px;min-width:580px;" cellspacing="0" cellpadding="0" border="0"><tbody><tr><td style="font-size:1px;line-height:1px;min-width:580px;" width="580"></td></tr></tbody></table>'
                               .'<div class="dragonecommercezyx987ios9"> &nbsp;<table class="dragonecommercezyx987wrapper dragonecommercezyx987section-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;table-layout:fixed;width:100%;border-collapse:separate;text-align:left;color:#303030;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#087197" align="center"><tbody><tr>'
                               .'<td align="center"><center><div class="dragonecommercezyx987webkit" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;">  <table class="dragonecommercezyx987outer" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                               .'<td> <table class="dragonecommercezyx987layout-preheader" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr class="dragonecommercezyx987one-col">'
                               .'<td class="dragonecommercezyx987inner dragonecommercezyx987contents" style="padding-left:20px;padding-right:20px;padding-bottom:18px;font-size:13px;line-height:14px;padding-top:18px;font-weight:500;color:#303030;">'
                               .'</td></tr></tbody></table></td></tr></tbody></table>'
                               .'</div></center></td></tr></tbody></table><table class="dragonecommercezyx987wrapper dragonecommercezyx987section-" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;table-layout:fixed;width:100%;border-collapse:separate;text-align:left;color:#303030;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF" align="center"><tbody><tr>'
                               .'<td align="center"> <center> <div class="dragonecommercezyx987webkit" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;">  <table class="dragonecommercezyx987outer dragonecommercezyx987boxed-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF"><tbody><tr>'
                               .'<td> <table class="dragonecommercezyx987layout-solologo dragonecommercezyx987boxed dragonecommercezyx987left" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr class="dragonecommercezyx987one-col">'
                               .'<td class="dragonecommercezyx987inner" style="padding-left:18px;padding-right:18px;padding-bottom:18px;padding-top:18px;"> <table width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                               .'<td class="dragonecommercezyx987inner-nested" style="padding-top:12px;padding-bottom:12px;padding-right:0px;padding-left:0px;"> <table class="dragonecommercezyx987contents" style="text-align:left;font-size:16px;line-height:22px;" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                               .'<td class="dragonecommercezyx987logo" style="font-weight:bold;font-size:18px;color:#087197;"><a rel="nofollow noopener noreferrer" target="_blank" href="%%%companyurl%%%" style="text-decoration:none;color:#087197;">%%%companyname%%%</a> </td> </tr></tbody></table>'
                               .'</td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table>'
                               .'</div></center></td></tr></tbody></table><table class="dragonecommercezyx987wrapper dragonecommercezyx987section-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;table-layout:fixed;width:100%;border-collapse:separate;text-align:left;color:#303030;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF" align="center"><tbody><tr>'
                               .'<td align="center"> <center> <div class="dragonecommercezyx987webkit" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;">  <table class="dragonecommercezyx987outer dragonecommercezyx987boxed-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF"><tbody><tr>'
                               .'<td> <table class="dragonecommercezyx987contents dragonecommercezyx987feature-callout-cta dragonecommercezyx987cta" style="color:#303030;" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr class="dragonecommercezyx987two-col">'
                               .'<td class="dragonecommercezyx987inner" style="padding-left:10px;padding-right:10px;"><table class="dragonecommercezyx987contents" style="font-size:16px;line-height:22px;color:#303030;" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                               .'<td class="dragonecommercezyx987feature-callout-bottom" style="padding-top:20px;padding-bottom:20px;padding-right:10px;padding-left:10px;" width="100%" valign="middle"> <table class="dragonecommercezyx987contents" style="font-size:16px;line-height:22px;color:#303030;" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                               .'<td class="dragonecommercezyx987inner-nested" style="padding-top:12px;padding-bottom:12px;padding-right:0px;padding-left:0;" valign="middle">'
                               .'<p class="dragonecommercezyx987h3" style="margin-top:0;margin-bottom:30px !important;font-weight:500;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;font-size:38px;line-height:36px;">%%%title%%%</p>'
                               .'<p>Hi %%%username%%%,</p><p>%%%header%%%</p><p>%%%content%%%</p><p>For more information, check out the <a rel="nofollow noopener noreferrer" target="_blank" href="%%%companyurl%%%">company website</a>.</p><p>Thanks,</p><p>%%%companyname%%%</p></td></tr></tbody></table>'
                               .'<table class="dragonecommercezyx987buttonwrapper dragonecommercezyx987cta-option-standard-tall" style="font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;background-color:#6ca12b;overflow:hidden;border-radius:5px;margin-top:30px;margin-bottom:40px;margin-right:auto;margin-left:0;font-size:16px;line-height:18px;font-weight:bold;" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                               .'<td class="dragonecommercezyx987button">'
                               .'</td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></div></center></td></tr></tbody></table>'
                               .'<table class="dragonecommercezyx987wrapper dragonecommercezyx987section-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;table-layout:fixed;width:100%;border-collapse:separate;text-align:left;color:#303030;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF" align="center"><tbody><tr>'
                               .'<td align="center"> <center> <div class="dragonecommercezyx987webkit" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;">  <table class="dragonecommercezyx987outer" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'
                               .'<td><div class="dragonecommercezyx987spacer" style="font-size:40px;line-height:40px;display:block;color:#ffffff;text-align:center;">&nbsp;</div> </td> </tr></tbody></table>'
                               .'</div> </center> </td> </tr></tbody></table><table class="dragonecommercezyx987wrapper dragonecommercezyx987section-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;table-layout:fixed;width:100%;border-collapse:separate;text-align:left;color:#303030;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF" align="center"><tbody><tr>'
                               .'<td align="center"> <center> <div class="dragonecommercezyx987webkit" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;">  <table class="dragonecommercezyx987outer dragonecommercezyx987boxed-light" style="margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;width:580px;min-width:580px;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF"><tbody><tr>'
                               .'<td><table class="dragonecommercezyx987footer-container" width="100%" cellspacing="0" cellpadding="0" border="0" align="center">'
                               .'<tbody><tr class="dragonecommercezyx987one-col">'
                               .'<td class="dragonecommercezyx987inner dragonecommercezyx987footer-row-top" style="padding-left:20px;padding-right:20px;padding-bottom:0px;padding-top:20px;"> <table class="dragonecommercezyx987fluid" style="border-top-width:2px;border-top-style:solid;border-top-color:#ECECEE;border-bottom-width:2px;border-bottom-style:solid;border-bottom-color:#ECECEE;" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr>'
                               .'<td class="dragonecommercezyx987hh-force-col-center" style="text-align:center;padding-top:25px;padding-bottom:40px;padding-right:0;padding-left:0;" valign="top"> <a rel="nofollow noopener noreferrer" target="_blank" href="%%%companyurl%%%" style="text-decoration:none;color:#959597;">%%%companyname%%%</a> </td> </tr></tbody></table>'
                               .'</td></tr>'
                               .'<tr class="dragonecommercezyx987one-col"><td class="dragonecommercezyx987inner dragonecommercezyx987footer-row-bottom" style="padding-left:20px;padding-right:20px;padding-bottom:0px;padding-top:20px;"> <table class="dragonecommercezyx987fluid" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr>'
                               .'<td class="dragonecommercezyx987hh-force-col-center dragonecommercezyx987footer-text-left" style="text-align:left;padding-top:0px;padding-bottom:40px;padding-right:0;padding-left:0;" valign="top">'
                               .'<p style="display:none;"></p></td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></div></center></td></tr></tbody></table></div></div></div>';
                        $msg = str_replace("%%%companyname%%%", $websiteurl, $msg);                            
                        $msg = str_replace("%%%title%%%", $websiteurl, $msg);
                        
                        $content = 'You need to click this link to activate your account within 24 hours:<br/><br/> <a href="' . $activationlink . '">' . $activationlink . '</a>';
                        $msg = str_replace("%%%username%%%", $username, $msg);
                        $msg = str_replace("%%%header%%%", 'Congratulations! You registered on %%%companyurl%%%', $msg);
                        $msg = str_replace("%%%content%%%", $content, $msg);
                        $msg = str_replace("%%%companyurl%%%", $websiteurl, $msg);                                                                                    
                        $msg = str_replace("%%%address1%%%", '', $msg);                                                                                    
                        $msg = str_replace("%%%address2%%%", '', $msg);

                        if($setting_email_method === 'WordPress Email') {
                            $headers = 'From: '. $bccemail . "\r\n" .
                                'Reply-To: ' . $email . "\r\n" .
                                'Bcc: ' . $bccemail . "\r\n";
                             
                            //Here put your Validation and send mail
                            add_filter('wp_mail_content_type', function($content_type) {
                                        return 'text/html';
                            });
                            $sent = wp_mail($email, $subject, $msg, $headers);
                            if($sent) {
                            } else {//message wasn't sent
                                $finalresult .= "Registration email was not sent to you. Please contact website admin. ";        
                                dragonecommercereservezyx987_saveToLogTable($finalresult, 'register new user', 'error', $user_id);                                
                            }        
                        } elseif($setting_email_method === 'Mailgun') {
                            $data = array(
                                'from' => $mailgun_fromname . ' <mailgun@' . $mailgun_domain . '>',
                                'to' => $email,
                                'bcc' => $bccemail,
                                'subject' => $subject,
                                'html' => $msg,
                                'o:tracking' => false);
                            $auth = base64_encode('api:'.$mailgun_api_key);
                            $args = [
                                'headers' => ['Authorization' => "Basic $auth"],
                                'body' => $data
                            ];
                            $mailgun_result = wp_remote_post($mailgun_api_url . $mailgun_domain . '/messages', $args);    
                            if(is_wp_error($mailgun_result)) {
                                $finalresult .= 'Mailgun result: ' . json_encode($mailgun_result);  //$mailgun_result->get_error_message();
                                $emailsent = 0;
                            }
                        } elseif($setting_email_method === 'Mailchimp') {
                            $data = array(
                                "key"=> $mailchimp_api_key, 
                                "message"=> array(
                                    "from_email"=> $mailchimp_fromemail,
                                    "from_name"=> $mailchimp_fromname,
                                    "subject"=> $subject, 
                                    "html"=> $msg,
                                    "to"=> array(array("email"=> $email, "name"=> "", "type"=>"to"), array("email"=> $bccemail, "name"=> "", "type"=>"bcc")),
                                    "track_opens"=>true,
                                    "track_clicks"=>true
                                )
                            );
                            $data2 = json_encode($data);
                            $auth = base64_encode('authorization: apikey '.$mailchimp_api_key);
                            $args = [
                                'headers' => ['Authorization' => "Basic $auth"],
                                'body' => $data2
                            ];
                            $response = wp_remote_post($mailchimp_api_url, $args);
                            if(is_wp_error($response)) {
                                $finalresult .= 'Mailchimp result: ' . $response->get_error_message();
                                $emailsent = 0;
                            }
                            //$response = json_decode($response0, true);
                            if($response !== null && is_array($response) && count($response) > 0 && isset($response[0]["status"]) && ($response[0]["status"] === 'rejected' || $response[0]["status"] === 'invalid')) {
                                $finalresult .= 'Mailchimp result: ' . json_encode($response);
                                $emailsent = 0;
                            }
                            //error_log("at 14796, mailchimp send email response: " . $response[0]["status"] . ", error: " . $finalresult);                
                        } elseif($setting_email_method === 'SendGrid') {
                            $data = array(
                                "personalizations"=> array(
                                    array(
                                        "to"=> array(array("email"=> $email)),
                                        "bcc"=> array(array("email"=> $bccemail))
                                    )
                                ), 
                                "from"=>array(
                                    "email"=> $sendgrid_fromemail,
                                    "name"=> $sendgrid_fromname
                                ),
                                "subject"=>$subject,
                                "content"=>array(
                                    array(
                                        "type"=> "text/html", 
                                        "value"=> $msg
                                    )                            
                                )
                            );
                            $data2 = json_encode($data);
                            //$auth = base64_encode('api:'.$sendgrid_api_key);
                            $args = array(
                                'headers' => array("Authorization" => "Bearer " . $sendgrid_api_key, "Content-Type" => "application/json"),
                                'body' => $data2
                            );    
                            $response = wp_remote_post($sendgrid_api_url, $args);    
                            if(is_wp_error($response)) {
                                $finalresult .= 'SendGrid result: ' . $response->get_error_message();
                                $emailsent = 0;
                            }
                            //$response = json_decode($response0, true);
                            if($response !== null && $response !== '' && is_array($response) && count($response) > 0 && (!empty($response["body"]["errors"]))) {
                                $finalresult .= 'SendGrid result: ' . json_encode($response);
                                $emailsent = 0;
                            }
                            //error_log("at 14833, sendgrid send email response: " . $response0 . ", error: " . $finalresult);                        
                        }    
                        if($finalresult === '') {                        
                            $finalresult .= "Registered. Please check your email to activate your account.";
                        }
                        echo esc_html($finalresult);
                        exit();
                    } else {
                        echo "Fail.";
                        exit();                        
                    }               
                } else {
                    echo esc_html(implode(". ", array_values($errors)) . ".");
                    exit();                        
                }               
            } else {
                echo "Request method is not POST.";
                exit();                
            }
        }
    }
    echo "Invalid register details.";
    exit();    
}

function dragonecommercereservezyx987_activateAccount() {
    global $wpdb;    
    $userid = empty($_GET['id']) ? '' : sanitize_text_field($_GET['id']);
    $userid = strip_tags($userid);    
    $token = empty($_GET['token']) ? '' : strip_tags($_GET['token']);
    $table_name = 'wp_dragonecommercereservezyx987_user_status';    
    $table_name2 = 'wp_dragonecommercereservezyx987_user_token';
    $query = "SELECT a.user_status, a.id 'userstatutableid', b.id 'usertokentableid',b.token, b.tokensentdatetimeutc,b.tokenverified from $table_name a JOIN $table_name2 b ON a.userid = b.userid and a.userid = $userid and a.status = 1 and b.tokenpurpose = 'REGISTER_ACTIVATION' and b.status = 1";
    $result = $wpdb->get_results($query);
    $usertokenrecordfound = false;
    $userstatustableid = 0;
    $usertokentableid = 0;
    $matchcounter = 0;
    $error = '';
    $finalresult = '';
    if(count($result) > 0) {
        foreach($result as $temp) {
            $datestring24hourago = gmdate("Y-m-d H:i:s", strtotime('-24 hours', time()));
            if($temp->user_status === "1") {
                return 'User is already activated. ';
            } else {
                if($temp->tokensentdatetimeutc >= $datestring24hourago) {
                    if($temp->token === $token) {
                        $usertokenrecordfound = true;
                        $userstatustableid = $temp->userstatutableid;
                        $usertokentableid = $temp->usertokentableid;
                        $matchcounter++;
                    }
                } else {
                    $error .= 'Token expired. ';                    
                }
            }
        }
        if($matchcounter !== 1) {
            $finalresult = 'Error. Found ' . $matchcounter . ' match(es) to your id and token. result: ' . json_encode($result) . ", token: " . $token;
        } else {
            if($userstatustableid > 0 && $error === '' && $finalresult === '') {
                $myresult = $wpdb->query($wpdb->prepare("UPDATE $table_name SET user_status = 1, updatetimeutc = UTC_TIMESTAMP() WHERE id = %d ", array($userstatustableid)));                            
                if($myresult === FALSE || $myresult === 0) {    
                    $finalresult .= 'Error. The user status table is not updated. ';
                }
            }            
            if($usertokentableid > 0 && $error === '' && $finalresult === '') {
                $myresult2 = $wpdb->query($wpdb->prepare("UPDATE $table_name2 SET tokenverified = 1, tokenverifiedtimeutc = UTC_TIMESTAMP() WHERE id = %d ", array($usertokentableid)));                            
                if($myresult2 === FALSE || $myresult2 === 0) {
                    $finalresult .= 'Error. The user token table is not updated. ';
                }            
            }
        }
        return $finalresult === '' ? 'success' : ($error . $finalresult);
    } else {
        return 'User or token is not found';        
    }    
}

function dragonecommercereservezyx987_setCookie_not_by_ajax() {
    check_ajax_referer('dragonecommercereservezyx987_createcookie', 'dragonecommercereservezyx987_hidden_security_createcookie');
    if((!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {        
        $value = empty($_POST['dragonecommercereservezyx987_orderitems']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_orderitems']);
        $value = strip_tags($value);
        $value = stripslashes($value); 
        //if(empty($value)) {   
        //    return "Cookie is empty. Cookie is not set.";
        //}    
        $dragonecommercereservezyx987_orderitems = empty($_POST['dragonecommercereservezyx987_orderitems']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_orderitems']);
        $_SESSION['dragonecommercereservezyx987_orderitems'] = $dragonecommercereservezyx987_orderitems;
        $setcookieresult = setcookie('dragonecommercereservezyx987_orderitems', stripslashes($dragonecommercereservezyx987_orderitems), 0, '/', '', true, true);
        if($setcookieresult) {
            return "success";    
        } else {
            return "Set cookie failed.";
        }            
    }
    return "Invalid details. Cookie is not set.";
}

function dragonecommercereservezyx987_loginUser_not_by_ajax() {
    if(!wp_verify_nonce($_POST['dragonecommercereservezyx987_hidden_security_loginuser'], 'dragonecommercereservezyx987_loginuser') ) { return 'invalid data';}
    if((!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        global $wpdb, $user_ID;
        $newuser;
        $_SESSION['dragonecommercereservezyx987_orderitems'] = empty($_POST['dragonecommercereservezyx987_orderitems']) ? array() : json_decode($_POST['dragonecommercereservezyx987_orderitems']);
        
        //Check whether the user is already logged in  
        if($user_ID) {
            return "success";
        } else { 
            $errors = array();               
            if($_SERVER['REQUEST_METHOD'] == 'POST') {               
                // Check username is present and not already in use  
                $username = sanitize_text_field($_POST['loginusername']);  
                if(strpos($username, ' ') !== false) {   
                    $errors['username'] = "Sorry, no spaces allowed in username";  
                }  
                if(empty($username)) {   
                    $errors['username'] = "Please enter a username";  
                }           
                // Check password is valid  
                if(0 === preg_match("/.{8,}/", $_POST['loginpassword'])) {  
                  $errors['password'] = "Password must be at least eight characters";  
                }                
                //password should only contain 0-9, a-z, A-Z, at least one of special characters such as !@#*()$%^&. No ' " < > and other characters are allowed
                if(0 === preg_match("/^[*0-9a-zA-Z!@#*()$%^&]+$/", $_POST['loginpassword'])) {  
                  $errors['password'] = "Password should only contain 0-9, a-z, A-Z, special characters (such as !@#*()$%^&)";  
                }
                //password should only at least one of special characters such as %?#!&$. No ' " and other characters are allowed
                if(1 === preg_match("/^[0-9a-zA-Z]+$/", $_POST['loginpassword'])) {  
                  $errors['password'] = "Password should contain at least one of special characters (such as !@#*()$%^&)";  
                }       
                if(0 === count($errors)) {               
                    $password = sanitize_text_field($_POST['loginpassword']);
                    $login_data = array();  
                    $login_data['user_login'] = $username;  
                    $login_data['user_password'] = $password;
                    $secure_cookie = '';
                    $customize_login = isset($_REQUEST['customize-login']);
                    if($customize_login) {
                        wp_enqueue_script('customize-base');
                    }
                    // If the user wants SSL but the session is not SSL, force a secure cookie.
                    if(!empty($_POST['log']) && !force_ssl_admin()) {
                        $user_name = sanitize_user(wp_unslash($_POST['log']));
                        $user = get_user_by('login', $user_name);
                        if(!$user && strpos($user_name, '@')) {
                            $user = get_user_by('email', $user_name);
                        }
                        if($user) {
                            if(get_user_option('use_ssl', $user->ID)) {
                                $secure_cookie = true;
                                force_ssl_admin(true);
                            }
                        }
                    }
                    if($wpdb->use_mysqli) {
                        if($wpdb->dbh->connect_error) {
                            die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
                        }
                        $table_name = 'wp_dragonecommercereservezyx987_user_status';
                        $table_name2 = $wpdb->prefix . 'users';
                        $table_name3 = 'wp_dragonecommercereservezyx987_setting';
                        $query = "SELECT a.user_status, a.admin_approved from $table_name a JOIN $table_name2 b on a.userid = b.ID and a.status = 1 and b.user_login = ?";
                        $stmt = $wpdb->dbh->prepare($query);
                        $stmt->bind_param("s", $username);
                        $stmt->execute();
                        $myresult = $stmt->get_result();
                        $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
                        $stmt->close();                            
                        $result_msg = "";                    
                        if(count($result) === 1) {
                            if($result[0]["user_status"] === 1) {                            
                            } else {                            
                                $result_msg .= "Your account is not activated. Please check your email for activation link or reset password.";
                            }
                            $RESERVE_NEED_ADMIN_APPROVE = $wpdb->get_var("SELECT value FROM $table_name3 WHERE name = 'RESERVE_NEED_ADMIN_APPROVE'");
                            if($RESERVE_NEED_ADMIN_APPROVE === '1') {                            
                                if($result[0]["admin_approved"] === 1) {                            
                                } else {                            
                                    $result_msg .= "Your account is not approved by admin. Please check your email for admin approval.";
                                }
                            }
                        } else {                        
                            $result_msg .= "Invalid login details. We found " . count($result) . " record(s) matching your username. Please contact website admin.";
                        }                            
                        if($result_msg !== "") {
                            return $result_msg;
                        }            
                    }                
                    $user_verify = wp_signon($login_data, $secure_cookie);
                    if(empty($_COOKIE[LOGGED_IN_COOKIE])) {
                        if(headers_sent()) {
                            $user_verify = new WP_Error(
                                'test_cookie',
                                sprintf(
                                    /* translators: 1: Browser cookie documentation URL, 2: Support forums URL. */
                                    __('<strong>Error</strong>: Cookies are blocked due to unexpected output. For help, please see <a href="%1$s">this documentation</a> or try the <a href="%2$s">support forums</a>.'),
                                    __('https://wordpress.org/support/article/cookies/'),
                                    __('https://wordpress.org/support/forums/')
                                )
                            );
                        } elseif(isset($_POST['testcookie']) && empty($_COOKIE[TEST_COOKIE])) {
                            // If cookies are disabled, we can't log in even with a valid user and password.
                            $user_verify = new WP_Error(
                                'test_cookie',
                                sprintf(
                                    /* translators: %s: Browser cookie documentation URL. */
                                    __('<strong>Error</strong>: Cookies are blocked or not supported by your browser. You must <a href="%s">enable cookies</a> to use WordPress.'),
                                    __('https://wordpress.org/support/article/cookies/#enable-cookies-in-your-browser')
                                )
                            );
                        }
                    }

                    if(is_wp_error($user_verify)) {
                        return "Invalid login details";  
                       // Note, I have created a page called "Error" that is a child of the login page to handle errors. This can be anything, but it seemed a good way to me to handle errors.  
                    } else {                            
                        $newuser = get_user_by('login', $username);
                        if($newuser->roles !== null && (!in_array('dragonecommercereservecustomer', (array) $newuser->roles))) {
                            return "You do not have the right to reserve on this ecommerce website.";
                        }                            
                        
                        if(session_id() == '' || !isset($_SESSION)) {
                            session_set_cookie_params(30*60);  // 30 minutes
                            session_destroy();
                            ini_set('session.cookie_httponly', 1);
                            ini_set('session.cookie_secure', 1);
                            session_start();
                            session_regenerate_id(TRUE);
                            setcookie(session_name(), session_id(), 0, '/', '', true, true);
                            $_SESSION["dragonecommercereservezyx987_user"] = json_encode((array)$newuser);
                        } else {
                            $oldsession = $_SESSION;
                            $_SESSION = array();
                            if(ini_get("session.use_cookies")) {
                                $params = session_get_cookie_params();
                                setcookie(session_name(), '', time() - 42000,
                                    $params["path"], $params["domain"],
                                    $params["secure"], $params["httponly"]
                                );
                            }
                            session_destroy();
                            ini_set('session.cookie_httponly', 1);
                            ini_set('session.cookie_secure', 1);
                            session_start();
                            session_regenerate_id(TRUE);
                            $_SESSION = array();
                            setcookie(session_name(), session_id(), 0, '/', '', true, true);
                            $_SESSION["dragonecommercereservezyx987_user"] = json_encode((array)$newuser);            
                        }                            
                        $dragonecommercereservezyx987_orderitems = empty($_POST['dragonecommercereservezyx987_orderitems']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_orderitems']);
                        $_SESSION['dragonecommercereservezyx987_orderitems'] = $dragonecommercereservezyx987_orderitems;
                        $setcookieresult = setcookie('dragonecommercereservezyx987_orderitems', stripslashes($dragonecommercereservezyx987_orderitems), 0, '/', '', true, true);
                        $value = wp_cache_get('dragonecommercereservezyx987_orderitems');
                        if(false === $value) {
                            // not found, set the default value
                            wp_cache_set('dragonecommercereservezyx987_orderitems', sanitize_text_field($_SESSION['dragonecommercereservezyx987_orderitems']));
                        }
                        if($setcookieresult) {
                            return "success";
                        } else {
                            return "Set cookie failed";
                        }                            
                    }               
                } else {
                    return implode(". ", array_values($errors)) . ".";                
                }               
            } else {
                return "Request method is not POST";            
            }
        }
    }
    return "Invalid login details";    
}

function dragonecommercereservezyx987_logoutUser_not_by_ajax() {
    if(!wp_verify_nonce($_POST['dragonecommercereservezyx987_hidden_security_logoutuser'], 'dragonecommercereservezyx987_logoutuser') ) { return 'invalid data';}    
    if((!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        wp_logout();
        setcookie('dragonecommercereservezyx987_orderitems', '', time() - 42000, '/', '', true, true);
        global $wpdb, $user_ID;
        if(!$user_ID) {       
            // They're already logged out, so we bounce them back to the homepage.
            if(session_id() == '' || !isset($_SESSION)) {    
            } else {
                $_SESSION = array();
                if(ini_get("session.use_cookies")) {
                    $params = session_get_cookie_params();
                    setcookie(session_name(), '', time() - 42000,
                        $params["path"], $params["domain"],
                        $params["secure"], $params["httponly"]
                    );
                }
                session_destroy();
                ini_set('session.cookie_httponly', 1);
                ini_set('session.cookie_secure', 1);                            
                session_start();
                session_regenerate_id(TRUE);
                $_SESSION = array();
                setcookie(session_name(), session_id(), 0, '/', '', true, true);
            }
            return "success";  //Already logged out";
        } else {           
            if($_SERVER['REQUEST_METHOD'] == 'POST') {                     
                if(session_id() == '' || !isset($_SESSION)) {    
                } else {
                    $_SESSION = array();
                    if(ini_get("session.use_cookies")) {
                        $params = session_get_cookie_params();
                        setcookie(session_name(), '', time() - 42000,
                            $params["path"], $params["domain"],
                            $params["secure"], $params["httponly"]
                        );
                    }
                    session_destroy();
                    ini_set('session.cookie_httponly', 1);
                    ini_set('session.cookie_secure', 1);                            
                    session_start();
                    session_regenerate_id(TRUE);
                    $_SESSION = array();
                    setcookie(session_name(), session_id(), 0, '/', '', true, true);
                }
                return "success";
            } else {
                return "Request method is not POST";                
            }
        }
    }
    return "Invalid logout";
}

//only for AJAX placing order
function dragonecommercereservezyx987_sessionAndCookieCompareUserid() {
    $isequal = '';
    $session_userid = intval($_POST['other']);
    if(get_current_user_id() <= 0) {
        $isequal = 'Not logged in';
    } else {
        if($session_userid > 0) {                
            if(get_current_user_id() === $session_userid) {
                $isequal = 'Logged in, equal';
            } else {            
                $isequal = 'Logged in, not equal';
            }
        } else {
            $isequal = "Logged in but SESSION not set";
        }
    }
    return $isequal;
}

add_action('wp_ajax_dragonecommercereservezyx987_loginuser', 'dragonecommercereservezyx987_loginUser');
add_action('wp_ajax_nopriv_dragonecommercereservezyx987_loginuser', 'dragonecommercereservezyx987_loginUser'); 
function dragonecommercereservezyx987_loginUser() {
    check_ajax_referer('dragonecommercereservezyx987_loginuser', 'dragonecommercereservezyx987_hidden_security_loginuser');
    if((!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        global $wpdb, $user_ID;        
        $_SESSION ['dragonecommercereservezyx987_orderitems'] = empty($_POST['dragonecommercereservezyx987_orderitems']) ? array() : json_decode($_POST['dragonecommercereservezyx987_orderitems']);
            if($user_ID) 
            {             
                //They're already logged in, so we bounce them back to the homepage.               
                echo "Already logged in.";
                exit();
            } else {           
                $errors = array();               
                if($_SERVER['REQUEST_METHOD'] == 'POST') {           
                    //Check email is present and not already in use  
                    $email = sanitize_text_field($_POST['email']);  
                    if(strpos($email, ' ') !== false) {   
                        $errors['email'] = "Sorry, no spaces allowed in email address";  
                    }  
                    if(empty($email)) {   
                        $errors['email'] = "Please enter an email address";  
                    }               
                    //Check email address is present and valid  
                    if(!is_email($email)) {   
                        $errors['email'] = "Please enter a valid email";  
                    }               
                    //Check password is valid  
                    if(0 === preg_match("/.{8,}/", $_POST['password'])) {  
                      $errors['password'] = "Password must be at least eight characters";  
                    }                    
                    //password should only contain 0-9, a-z, A-Z, at least one of special characters such as !@#*()$%^&. No ' " and other characters are allowed
                    if(0 === preg_match("/^[0-9a-zA-Z!@#*()$%^&]+$/", $_POST['password'])) {  
                      $errors['password'] = "Password should only contain 0-9, a-z, A-Z, special characters (such as !@#*()$%^&)";  
                    }
                    //password should only at least one of special characters such as !@#*()$%^&. No ' " and other characters are allowed
                    if(1 === preg_match("/^[0-9a-zA-Z]+$/", $_POST['password'])) {  
                      $errors['password'] = "Password should contain at least one of special characters (such as !@#*()$%^&)";  
                    }               
                    if(0 === count($errors)) {               
                        $password = $wpdb->escape($_POST['password']);  

                        $login_data = array();  
                        $login_data['user_login'] = $email;  
                        $login_data['user_password'] = $password; 
                       
                        $user_verify = wp_signon($login_data, false);                       
                        if(is_wp_error($user_verify))   
                        {  
                            echo "Invalid login details."; 
                         } else {
                            ini_set('session.cookie_httponly', 1);
                            ini_set('session.cookie_secure', 1);
                            if(session_id() == '' || !isset($_SESSION)) {
                                session_set_cookie_params(30*60);  // 30 minutes
                                session_start();
                                setcookie(session_name(), session_id(), 0, '/', '', true, true);
                            } else {
                                $_SESSION = array();
                                if(ini_get("session.use_cookies")) {
                                    $params = session_get_cookie_params();
                                    setcookie(session_name(), '', time() - 42000,
                                        $params["path"], $params["domain"],
                                        $params["secure"], $params["httponly"]
                                    );
                                }
                                session_destroy();
                                session_start();
                                $_SESSION = array();
                                setcookie(session_name(), session_id(), 0, '/', '', true, true);            
                            }                            
                            $_SESSION["dragonecommercereservezyx987_userid"] = get_current_user_id();
                            $_SESSION['dragonecommercereservezyx987_orderitems'] = empty($_POST['dragonecommercereservezyx987_orderitems']) ? array() : json_decode($_POST['dragonecommercereservezyx987_orderitems']);
                            echo "Success";
                            exit();  
                        }           
                    } else {
                        $myerrors = implode(". ", array_values($errors)) . ".";
                        $username = $_POST['loginusername'] === null ? "NULL" : $_POST['loginusername'];
                        echo esc_html($myerrors . " username: " . $username);
                        exit();                    
                    }               
                } else {
                    echo "Request method is not POST. username: " . ($_POST['loginusername'] === null ? "NULL" : esc_html($_POST['loginusername']));
                    exit();                
                }
            }
    }
    echo "Invalid login details. username: " . ($_POST['loginusername'] === null ? "NULL" : esc_html($_POST['loginusername']));
    exit();    
}

add_action('wp_ajax_dragonecommercereservezyx987_logoutuser', 'dragonecommercereservezyx987_logoutUser');
add_action('wp_ajax_nopriv_dragonecommercereservezyx987_logoutuser', 'dragonecommercereservezyx987_logoutUser'); 
function dragonecommercereservezyx987_logoutUser() {
    check_ajax_referer('dragonecommercereservezyx987_logoutuser', 'dragonecommercereservezyx987_hidden_security_logoutuser');
    if((!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        wp_logout();
        global $wpdb, $user_ID;        
        //Check whether the user is already logged in  
        if(!$user_ID) 
        {
            echo "Already logged out.";
            exit();
        } else {           
            if($_SERVER['REQUEST_METHOD'] == 'POST') {                     
                        if(session_id() == '' || !isset($_SESSION)) {
                        } else {
                            $_SESSION = array();
                            if(ini_get("session.use_cookies")) {
                                $params = session_get_cookie_params();
                                setcookie(session_name(), '', time() - 42000,
                                    $params["path"], $params["domain"],
                                    $params["secure"], $params["httponly"]
                                );
                            }
                            session_destroy();                
                        }
                        echo "Success";
                        exit();
            } else {
                echo "Request method is not POST.";
                exit();                
            }
        }
    }
    echo "Invalid logout.";
    exit();    
}

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

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

function dragonecommercereservezyx987_addCountry() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_addCountry') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_country';         
        $name = sanitize_text_field($_POST['dragonecommercereservezyx987_addcountryname']);
        $name = stripslashes($name);
        $abbreviation = sanitize_text_field($_POST['dragonecommercereservezyx987_addcountryabbreviation']);
        $description = sanitize_text_field($_POST['dragonecommercereservezyx987_addcountrydescription']);
        $description = stripslashes($description);
        if($name === '' || $abbreviation === '') {$dragon_ecommerce_dbResult .= 'Create a new country: country name and abbreviation 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 = ? or abbreviation = ?");
            $stmt->bind_param("ss", $name, $abbreviation);
            $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 country: country name: \"" . $name . "\" and/or abbreviation: \"" . $abbreviation . "\" already exist(s) in the country table. Not saved. ";return;}
            } else {
                $dragon_ecommerce_dbResult .= "Create a new country: country name \"" . $name . "\" query has error. Not saved. ";return;
            }
            
            $query = "INSERT INTO " . $table_name . " (`name`,`abbreviation`,`description`,`createtimeutc`) VALUES (?,?,?,UTC_TIMESTAMP())";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

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

            $types .= 's';
            $parameterArray[] = &$abbreviation;
            
            $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 country 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 dragonecommercereservezyx987_getCountries($onlyActive = true) {    
    global $wpdb; global $dragon_ecommerce_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_dragonecommercereservezyx987_country';
    if($onlyActive) {
        $results1 = $wpdb->get_results("SELECT id,name,abbreviation,status from $table_name WHERE name in ('USA', 'Canada') and status = 1 order by id");
        $results2 = $wpdb->get_results("SELECT id,name,abbreviation,status from $table_name WHERE name NOT in ('USA', 'Canada') and status = 1 order by name");
        $results = array_merge($results1, $results2);
    } else {
        $results1 = $wpdb->get_results("SELECT id,name,abbreviation,status from $table_name WHERE name in ('USA', 'Canada') order by id");
        $results2 = $wpdb->get_results("SELECT id,name,abbreviation,status from $table_name WHERE name NOT in ('USA', 'Canada')order by name");    
        $results = array_merge($results1, $results2);        
    }    
    foreach($results as $result) {
        foreach($result as $key => $value) {
            $result->$key = deslash($value);
        }
    }
    return $results;    
}

function dragonecommercereservezyx987_addProvince() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_addProvince') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_province';         
        $name = sanitize_text_field($_POST['dragonecommercereservezyx987_addprovincename']);
        $name = stripslashes($name);
        $description = sanitize_text_field($_POST['dragonecommercereservezyx987_addprovincedescription']);
        $description = stripslashes($description);
        $countryid = intval(sanitize_text_field($_POST['dragonecommercereservezyx987_addprovincecountry']));        
        if($name === '' || $countryid < 1) {$dragon_ecommerce_dbResult .= 'Create a new province: country and province 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 countryid = ?");
            $stmt->bind_param("si", $name, $countryid);
            $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 province: province name \"" . $name . "\" already exists for that country in the province table. Not saved. ";return;}
            } else {
                $dragon_ecommerce_dbResult .= "Create a new province: province name \"" . $name . "\" query has error. Not saved. ";return;
            }            
            $query = "INSERT INTO " . $table_name . " (`countryid`,`name`,`description`,`createtimeutc`) VALUES (?,?,?,UTC_TIMESTAMP())";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 'i';
            $parameterArray[] = &$countryid;
            
            $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_ecommerce_dbResult .= 'Error adding a province 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 dragonecommercereservezyx987_getAllProvinces($onlyActive = true) {
    global $wpdb; global $dragon_ecommerce_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_dragonecommercereservezyx987_province';
    $table_name2 = 'wp_dragonecommercereservezyx987_country';            
    if($onlyActive) {    
        $results = $wpdb->get_results("SELECT a.id,a.name,a.countryid,b.abbreviation,a.status from $table_name a JOIN $table_name2 b on a.countryid = b.id WHERE a.status = 1 order by a.name");
    } else {
        $results = $wpdb->get_results("SELECT a.id,a.name,a.countryid,b.abbreviation,a.status from $table_name a JOIN $table_name2 b on a.countryid = b.id order by a.name");        
    }        
    foreach($results as $result) {
        foreach($result as $key => $value) {
            $result->$key = deslash($value);
        }
    }
    return $results;    
}

function dragonecommercereservezyx987_getProvinces($countryid, $onlyActive = true) {
    global $wpdb; global $dragon_ecommerce_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_dragonecommercereservezyx987_province';
    $table_name2 = 'wp_dragonecommercereservezyx987_country';            
    if($onlyActive) {    
        $results = $wpdb->get_results("SELECT a.id,a.name,a.countryid,a.status from $table_name a JOIN $table_name2 b on a.countryid = b.id WHERE a.countryid = " . $countryid . " AND a.status = 1 order by a.name");
    } else {
        $results = $wpdb->get_results("SELECT a.id,a.name,a.countryid,a.status from $table_name a JOIN $table_name2 b on a.countryid = b.id WHERE a.countryid = " . $countryid . " order by a.name");        
    }        
    foreach($results as $result) {
        foreach($result as $key => $value) {
            $result->$key = deslash($value);
        }
    }
    return $results;    
}

function dragonecommercereservezyx987_addCity() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : strip_tags($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = sanitize_text_field($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_addCity') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_city';         
        $name = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addcityname']));
        $name = stripslashes($name);
        $description = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addcitydescription']));
        $description = stripslashes($description);
        $provinceid = intval(sanitize_text_field($_POST['dragonecommercereservezyx987_addcityprovince']));
        $countryid = intval(sanitize_text_field($_POST['dragonecommercereservezyx987_addcitycountry']));        
        if($name === '' || $provinceid <= 0 || $countryid <= 0) {$dragon_ecommerce_dbResult .= 'Create a new city: country, province and city 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 provinceid = ?");
            $stmt->bind_param("si", $name, $provinceid);
            $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 city: city name \"" . $name . "\" already exists for the province in the city table. Not saved. ";return;}
            } else {
                $dragon_ecommerce_dbResult .= "Create a new city: city name \"" . $name . "\" query has error. Not saved. ";return;
            }
            $stmt = null;
            $query = "INSERT INTO " . $table_name . " (`provinceid`,`name`,`description`,`createtimeutc`) VALUES (?,?,?,UTC_TIMESTAMP())";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

            $types .= 'i';
            $parameterArray[] = &$provinceid;
            
            $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_ecommerce_dbResult .= 'Error adding a city 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 dragonecommercereservezyx987_getAllCities($onlyActive = true) {
    global $wpdb; global $dragon_ecommerce_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');            
    $table_name = 'wp_dragonecommercereservezyx987_city';
    $table_name2 = 'wp_dragonecommercereservezyx987_province';
    $table_name3 = 'wp_dragonecommercereservezyx987_country';    
    if($onlyActive) {    
        $results = $wpdb->get_results("SELECT a.id,a.name,a.provinceid,a.status from $table_name a JOIN $table_name2 b on a.provinceid = b.id JOIN $table_name3 c on b.countryid = c.id WHERE a.status = 1 order by a.name");
    } else {
        $results = $wpdb->get_results("SELECT a.id,a.name,a.provinceid,a.status from $table_name a JOIN $table_name2 b on a.provinceid = b.id JOIN $table_name3 c on b.countryid = c.id order by a.name");        
    }
    foreach($results as $result) {
        foreach($result as $key => $value) {
            $result->$key = deslash($value);
        }
    }
    return $results;    
}

function dragonecommercereservezyx987_getCities($countryid, $provinceid, $onlyActive = true) {
    global $wpdb; global $dragon_ecommerce_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_dragonecommercereservezyx987_city';
    $table_name2 = 'wp_dragonecommercereservezyx987_province';
    $table_name3 = 'wp_dragonecommercereservezyx987_country';    
    if($onlyActive) {    
        $results = $wpdb->get_results("SELECT a.id,a.name,a.provinceid,a.status from $table_name a JOIN $table_name2 b on a.provinceid = b.id JOIN $table_name3 c on a.countryid = c.id WHERE a.provinceid = " . $provinceid . " and a.countryid = " . $countryid . " AND a.status = 1 order by a.name");
    } else {
        $results = $wpdb->get_results("SELECT a.id,a.name,a.provinceid,a.status from $table_name a JOIN $table_name2 b on a.provinceid = b.id JOIN $table_name3 c on a.countryid = c.id WHERE a.provinceid = " . $provinceid . " and a.countryid = " . $countryid . " order by a.name");        
    }
    foreach($results as $result) {
        foreach($result as $key => $value) {
            $result->$key = deslash($value);
        }
    }
    return $results;    
}

function dragonecommercereservezyx987_addDepartment() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_addDepartment') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_department';         
        $name = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_adddepartmentname']));
        $description = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_adddepartmentdescription']));
        
        if($name === '') {$dragon_ecommerce_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_ecommerce_dbResult .= "Create a new department: department name \"" . $name . "\" already exists in the department table. Not saved. ";return;}
            } else {
                $dragon_ecommerce_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_ecommerce_dbResult .= 'Error adding a department 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 dragonecommercereservezyx987_getAllDepartments($onlyActive = false) {
    global $wpdb; global $dragon_ecommerce_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_dragonecommercereservezyx987_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 dragonecommercereservezyx987_getAllChargetypes($onlyActive = false) {
    global $wpdb; global $dragon_ecommerce_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_dragonecommercereservezyx987_chargetype';
    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 dragonecommercereservezyx987_getAllEmailMethods($onlyActive = false) {
    global $wpdb; global $dragon_ecommerce_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_dragonecommercereservezyx987_emailmethod';
    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 dragonecommercereservezyx987_getAllPropertyvalues($onlyActive = false) {
    global $wpdb; global $dragon_ecommerce_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_dragonecommercereservezyx987_propertyvalue';
    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 dragonecommercereservezyx987_getAllPropertyvalueshownnameandids($onlyActive = false) {
    global $wpdb; global $dragon_ecommerce_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_dragonecommercereservezyx987_propertyvalue';
    if($onlyActive) {
        $results = $wpdb->get_results("SELECT *, concat(shownname, '(',id,')') 'shownnameid'  from $table_name WHERE status = 1 order by name");
    } else {
        $results = $wpdb->get_results("SELECT *, concat(shownname, '(',id,')') 'shownnameid'  from $table_name order by name");        
    }
    foreach($results as $result) {
        foreach($result as $key => $value) {
            $result->$key = deslash($value);
        }
    }
    return $results;    
}

function dragonecommercereservezyx987_addGroupcategory() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_addGroupcategory') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_groupcategory';         
        $name = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addgroupcategoryname']));
        $description = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addgroupcategorydescription']));
        $priority = intval(sanitize_text_field($_POST['dragonecommercereservezyx987_addgroupcategorypriority']));        
        if($name === '') {$dragon_ecommerce_dbResult .= 'Create a new group category: Group 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_ecommerce_dbResult .= "Create a new group category: group category name \"" . $name . "\" already exists in the group category table. Not saved. ";return;}
            } else {
                $dragon_ecommerce_dbResult .= "Create a new group category: group category name \"" . $name . "\" query has error. Not saved. ";return;
            }            
            $myresult = 0;
            if($priority < 0) {
                $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();
            } else {
                $query = "INSERT INTO " . $table_name . " (`name`,`description`,`priority`,`createtimeutc`) VALUES (?,?,?,UTC_TIMESTAMP())";
                $stmt = $wpdb->dbh->prepare($query);
                $types = '';
                $parameterArray = array('');
                
                $types .= 's';
                $parameterArray[] = &$name;
                
                $types .= 's';
                $parameterArray[] = &$description;
                
                $types .= 'i';
                $parameterArray[] = &$priority;
                
                $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 group category 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 dragonecommercereservezyx987_getAllGroupcategories($onlyActive = false) {
    global $wpdb; global $dragon_ecommerce_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_dragonecommercereservezyx987_groupcategory';
    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 dragonecommercereservezyx987_addGroup() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_addGroup') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_group';
        $table_name2 = 'wp_dragonecommercereservezyx987_setting';
        $groupcategoryid =     intval(sanitize_text_field($_POST['dragonecommercereservezyx987_addgroupgroupcategory']));
        $name = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addgroupname']));
        $description = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addgroupdescription']));
        $priority = intval(sanitize_text_field($_POST['dragonecommercereservezyx987_addgrouppriority']));        
        if($groupcategoryid <= 0 || $name === '') {$dragon_ecommerce_dbResult .= 'Create a new group: Group category and group name are required. Not saved. ';return;}
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            //first, check there should be only one record for tax
            $TAX_GROUP_CATEGORY_ID_TEMP = $wpdb->get_var("SELECT value FROM $table_name2 WHERE name = 'GROUP_CATEGORY_ID_FOR_ORDER_TAX_DETAILS'");    
            $TAX_GROUP_CATEGORY_ID = $TAX_GROUP_CATEGORY_ID_TEMP === null ? 0 : intval($TAX_GROUP_CATEGORY_ID_TEMP);           
            $query  = "SELECT count(*) FROM $table_name where status = 1 AND groupcategoryid = ( ";
            $query .= "SELECT CAST(value AS UNSIGNED) from $table_name2 WHERE name = 'GROUP_CATEGORY_ID_FOR_ORDER_TAX_DETAILS')";        
            $dbcount_temp = $wpdb->get_var($query);
            $dbcount = intval($dbcount_temp);    
            if($dbcount > 1) {$dragon_ecommerce_dbResult .= "There are more then one records for tax. You should keep ONLY ONE active record for tax. Please set some tax records as inactive or remove them directly from database . Not saved. ";exit();}
            if($groupcategoryid === $TAX_GROUP_CATEGORY_ID) {    
                if($dbcount === 1) {$dragon_ecommerce_dbResult .= "There is already one active record for tax. Not saved. ";exit();}
            }
            $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 group: group name \"" . $name . "\" already exists in the group table. Not saved. ";return;}
            } else {
                $dragon_ecommerce_dbResult .= "Create a new group: group name \"" . $name . "\" query has error. Not saved. ";return;
            }            
            $myresult = 0;
            if($priority < 0) {
                $query = "INSERT INTO " . $table_name . " (`groupcategoryid`,`name`,`description`,`createtimeutc`) VALUES (?,?,?,UTC_TIMESTAMP())";
                $stmt = $wpdb->dbh->prepare($query);
                $types = '';
                $parameterArray = array('');
                
                $types .= 'i';
                $parameterArray[] = &$groupcategoryid;            

                $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();
            } else {
                $query = "INSERT INTO " . $table_name . " (`groupcategoryid`,`name`,`description`,`priority`,`createtimeutc`) VALUES (?,?,?,?,UTC_TIMESTAMP())";
                $stmt = $wpdb->dbh->prepare($query);
                $types = '';
                $parameterArray = array('');
                
                $types .= 'i';
                $parameterArray[] = &$groupcategoryid;    
                
                $types .= 's';
                $parameterArray[] = &$name;
                
                $types .= 's';
                $parameterArray[] = &$description;
                
                $types .= 'i';
                $parameterArray[] = &$priority;
                
                $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 group 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 dragonecommercereservezyx987_getAllGroups($onlyActive = false) {
    global $wpdb; global $dragon_ecommerce_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_dragonecommercereservezyx987_group';
    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 dragonecommercereservezyx987_getAllProducts($onlyActive = false) {
    global $wpdb; global $dragon_ecommerce_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_dragonecommercereservezyx987_product';
    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 dragonecommercereservezyx987_addCurrency() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_currency';         
        $name = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addcurrencyname']));
        $sign = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addcurrencysign']));
        $isocurrencycode = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addcurrencyisocurrencycode']));
        $description = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addcurrencydescription']));        
        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));
            }
            $stmt = $wpdb->dbh->prepare("SELECT COUNT(*) countresult FROM $table_name WHERE name = ? or sign = ? or isocurrencycode = ?");
            $stmt->bind_param("sss", $name, $sign, $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 sign: \"" . $sign . "\"  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 dragonecommercereservezyx987_getAllCurrencies($onlyActive = false) {
    global $wpdb; global $dragon_ecommerce_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_dragonecommercereservezyx987_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;    
}

function dragonecommercereservezyx987_uploadSlide_dir( $dir ) {
    return array(
        'path'   => $dir['basedir'] . '/dragonecommercereserve/images/slideshow',
        'url'    => $dir['baseurl'] . '/dragonecommercereserve/images/slideshow',
        'subdir' => '/dragonecommercereserve/images/slideshow',
    ) + $dir;
}

function dragonecommercereservezyx987_addSlide() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_addSlideshow') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_slideshow';         
        $name = sanitize_text_field($_POST['dragonecommercereservezyx987_addslidename']);
        $description = sanitize_text_field($_POST['dragonecommercereservezyx987_addslidedescription']);
        $target_dir = dragonecommercereservezyx987_upload_folder() . "/images/slideshow/";        
        //$target_dir = ABSPATH . "wp-content/plugins/dragonecommercereserve/images/slideshow/";        
        $imagefilename = '';
        if(basename($_FILES["dragonecommercereservezyx987_addslideuploadslidefile"]["name"]) !== '') {
            try{
            if(!file_exists($target_dir)) {
                mkdir($target_dir, 0755, true);
            } else {        
                chmod($target_dir, 0777);
            }            
            $target_file = $target_dir . basename($_FILES["dragonecommercereservezyx987_addslideuploadslidefile"]["name"]);
            $uploadOk = 1;
            $fileType = strtolower(pathinfo($_FILES["dragonecommercereservezyx987_addslideuploadslidefile"]["name"], PATHINFO_EXTENSION));

            // Check if file already exists
            if(file_exists($target_file)) {
                $dragon_ecommerce_dbResult .= "Sorry, file already exists. Change the filename and upload again. ";
                $uploadOk = 0;
            }

            // Check file size smaller than 20MB
            if($_FILES["dragonecommercereservezyx987_addslideuploadslidefile"]["size"] > 20000000) {
                $dragon_ecommerce_dbResult .= "Sorry, your file is bigger than 20MB.";
                $uploadOk = 0;
            }

            if($fileType !== "jpg" && $fileType !== "jpeg" && $fileType !== "png") {
                $dragon_ecommerce_dbResult .= "Sorry, only jpg, jpeg, and png files are allowed. ";
                $uploadOk = 0;
            }        

            if($uploadOk == 0) {
                $dragon_ecommerce_dbResult .= "Sorry, your file was not uploaded. ";return;
            } else {                
                add_filter( 'upload_dir', 'dragonecommercereservezyx987_uploadSlide_dir' );
                $upload_result = wp_handle_upload($_FILES["dragonecommercereservezyx987_addslideuploadslidefile"]);
                remove_filter( 'upload_dir', 'dragonecommercereservezyx987_uploadSlide_dir' );
                if($upload_result) {
                    $imagefilename = basename($_FILES["dragonecommercereservezyx987_addslideuploadslidefile"]["name"]);
                } else {
                    $dragon_ecommerce_dbResult .= 'Can not upload file to slideshow folder. Try to upload a smaller size file.';
                }
            }
            }catch(Exception $e) {
                $dragon_ecommerce_dbResult .= 'Slideshow slide file upload exception: ' .$e->getMessage() . ". ";
            }
            chmod($target_dir, 0755);
        }        
        if($imagefilename === '') {$dragon_ecommerce_dbResult .= 'Create a new slide: image file is required. Not saved. ';return;}
        $dbmaxsequencenumber = $wpdb->get_var("SELECT max(sequencenumber) FROM $table_name WHERE id > 0");
        $nextsequencenumber = 1;
        if($dbmaxsequencenumber === null) {
            $nextsequencenumber = 1;
        } else {
            $nextsequencenumber = intval($dbmaxsequencenumber) + 1;
        }        
        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 filename = ?");
            $stmt->bind_param("s", $imagefilename);
            $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 slide: image file name \"" . $name . "\" already exists in the slideshow table. Not saved. ";return;}
            } else {
                $dragon_ecommerce_dbResult .= "Create a new slide: image file name \"" . $name . "\" query has error. Not saved. ";return;
            }            
            $query = "INSERT INTO " . $table_name . " (`name`,`filename`,`sequencenumber`,`description`,`createtimeutc`) VALUES (?,?,?,?,UTC_TIMESTAMP())";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');
            
            $types .= 's';
            $parameterArray[] = &$name;
            
            $types .= 's';
            $parameterArray[] = &$imagefilename;
            
            $types .= 'i';
            $parameterArray[] = &$nextsequencenumber;
            
            $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 slide 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 dragonecommercereservezyx987_addProduct() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_addProduct') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_product';
        $table_name2 = 'wp_dragonecommercereservezyx987_product_group';
        $name = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addproductname']));
        $name = stripslashes($name);
        $price = floatval(sanitize_text_field($_POST['dragonecommercereservezyx987_addproductprice']));    
        $departmentid = intval(sanitize_text_field($_POST['dragonecommercereservezyx987_addproductdepartment']));
        $quantity_temp = sanitize_text_field($_POST['dragonecommercereservezyx987_addproductquantity']);
        $quantity_temp = $quantity_temp === '' ? '-1' : $quantity_temp;
        $quantity = intval($quantity_temp);
        $description = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addproductdescription']));
        $description = stripslashes($description);        
        $addproductweightlb_temp = sanitize_text_field($_POST['dragonecommercereservezyx987_addproductweightlb']);
        $addproductweightlb_temp = $addproductweightlb_temp === '' ? '-1' : $addproductweightlb_temp;
        $addproductweightlb = floatval($addproductweightlb_temp);
        $addproductbarcode = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addproductbarcode']));
        $addproductbarcode = stripslashes($addproductbarcode);        
        $addproductuuid = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addproductuuid']));
        $addproductshipfromnearestbranch = 0;    
        $mygroupid = 0;
        $groupsArr = [];
        //if(isset($_POST['dragonecommercereservezyx987_addproductgroups'])){
          //if(is_array($_POST['dragonecommercereservezyx987_addproductgroups'])) {
            //foreach($_POST['dragonecommercereservezyx987_addproductgroups'] as $value){
            //    if(intval(sanitize_text_field($value)) > 0) {
            //        $groupsArr[] = intval(sanitize_text_field($value));
            //    }
            //}
          //} else {
            $dragonecommercereservezyx987_addproductgroup = sanitize_text_field($_POST['dragonecommercereservezyx987_addproductgroup']);
            //if($dragonecommercereservezyx987_addproductgroup !== '-1') {
                $mygroupid = intval($dragonecommercereservezyx987_addproductgroup);
            //}
          //}
        //}
        if($mygroupid <= 0 && $mygroupid !== -1) {
            $dragon_ecommerce_dbResult .= 'Invalid group id: ' . $mygroupid . '. Not saved.';return;;
        }
        $result = '';$result2 = [];
        if($name === '' || $price < 0 || $departmentid <= 0) {$dragon_ecommerce_dbResult .= 'Create a new ecommerce product: Name, price and department are all 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_ecommerce_dbResult .= "Create a new product: product name " . $name . " already exists in the product table. Not saved. ";return;}
            } else {
                $dragon_ecommerce_dbResult .= "Create a new product: product name " . $name . " query has error. Not saved. ";return;
            }
            $myresult = 0;
            $types = '';
            $parameterArray = array('');                            
            $text1 = '';
            $text2 = '';
            
            $types .= 's';
            $parameterArray[] = &$name;
            $text1 .= '`name`,';
            $text2 .= '?,';            
            $types .= 'd';
            $parameterArray[] = &$price;
            $text1 .= '`price`,';
            $text2 .= '?,';
            $types .= 'i';
            $parameterArray[] = &$departmentid;    
            $text1 .= '`departmentid`,';
            $text2 .= '?,';
            if($quantity >= 0) {
                $types .= 'i';
                $parameterArray[] = &$quantity;
                $text1 .= '`quantity`,';
                $text2 .= '?,';                                    

                $types .= 'i';
                $parameterArray[] = &$quantity;     
                $text1 .= '`originalquantity`,';
                $text2 .= '?,';                                    
            }
            if($addproductweightlb >= 0) {
                $types .= 'd';
                $parameterArray[] = &$addproductweightlb;
                $text1 .= '`weightlb`,';
                $text2 .= '?,';                                    
            }    
            if($addproductbarcode !== '') {
                $types .= 's';
                $parameterArray[] = &$addproductbarcode;
                $text1 .= '`barcode`,';
                $text2 .= '?,';                            
            }
            if($addproductuuid !== '') {
                $types .= 's';
                $parameterArray[] = &$addproductuuid;    
                $text1 .= '`uuid`,';
                $text2 .= '?,';                                    
            }            
            if($description !== '') {
                $types .= 's';
                $parameterArray[] = &$description;
                $text1 .= '`description`,';
                $text2 .= '?,';
            }
            if($text1 !== '' && $text2 !== '') {
                $query = "INSERT INTO " . $table_name . " ($text1 `createtimeutc`) VALUES ($text2 UTC_TIMESTAMP())";
                $stmt = $wpdb->dbh->prepare($query);                                
            
                $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 new ecommerce product into table ' . $table_name . ". ";return;
                }
                if($mygroupid > 0) {
                    $result2[] = $wpdb->query($wpdb->prepare("INSERT INTO $table_name2 (`productid`,`groupid`,`createtimeutc`) VALUES (%d,%d,UTC_TIMESTAMP())", array($myresult, $mygroupid)));            
                }
            }                
            $dragon_ecommerce_dbResult_temp = '';
            foreach($result2 as $temp) {
                if($temp === FALSE) {
                    $dragon_ecommerce_dbResult_temp .= 'Error inserting into table ' . $table_name2 . ". ";
                }
            }
            if(count($result2) > 0) {
                $dragon_ecommerce_dbResult .= $dragon_ecommerce_dbResult_temp;return;
            }    
        } else {
            $dragon_ecommerce_dbResult .= 'Mysqli is not supported by your system. ';return;
        }
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }    
}

function dragonecommercereservezyx987_uploadProductImage_dir($dir) {
    $product_id_temp = sanitize_text_field($_POST['dragonecommercereservezyx987_editproductid']) === '' ? 0 : intval(sanitize_text_field($_POST['dragonecommercereservezyx987_editproductid']));
    return array(
        'path'   => $dir['basedir'] . "/dragonecommercereserve/images/product/" . $product_id_temp,
        'url'    => $dir['baseurl'] . "/dragonecommercereserve/images/product/" . $product_id_temp,
        'subdir' => "/dragonecommercereserve/images/product/" . $product_id_temp,
    ) + $dir;
}

function dragonecommercereservezyx987_editProduct() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_editProduct') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        try{
            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
            $table_name = 'wp_dragonecommercereservezyx987_product';
            $table_name2 = 'wp_dragonecommercereservezyx987_product_group';
            $table_name3 = 'wp_dragonecommercereservezyx987_setting';            
            $product_id = sanitize_text_field($_POST['dragonecommercereservezyx987_editproductid']) === '' ? 0 : intval(sanitize_text_field($_POST['dragonecommercereservezyx987_editproductid']));
            $name = sanitize_text_field($_POST['dragonecommercereservezyx987_editproductname']);
            $name = deslash($name);
            $price = floatval(sanitize_text_field($_POST['dragonecommercereservezyx987_editproductprice']));
            $saleprice = floatval(sanitize_text_field($_POST['dragonecommercereservezyx987_editproductsaleprice']));
            $saleprice_isempty = false;
            if(isset($_POST['dragonecommercereservezyx987_editproductsaleprice']) && trim($_POST['dragonecommercereservezyx987_editproductsaleprice']) === '') {
                $saleprice_isempty = true;
            }            
            $isonsale_temp = (!isset($_POST['dragonecommercereservezyx987_editproductisonsale'])) ? '0' : sanitize_text_field($_POST['dragonecommercereservezyx987_editproductisonsale']);
            $isonsale_temp = strip_tags($isonsale_temp);
            $isonsale = intval($isonsale_temp);
            $isonsale = $isonsale < 0 ? 0 : $isonsale;
            $isonsale = ($isonsale !== 0 && $isonsale !== 1) ? 0 : $isonsale;
            
            $istaxfree_temp = (!isset($_POST['dragonecommercereservezyx987_editproductistaxfree'])) ? '0' : sanitize_text_field($_POST['dragonecommercereservezyx987_editproductistaxfree']);
            $istaxfree_temp = strip_tags($istaxfree_temp);
            $istaxfree = intval($istaxfree_temp);
            $istaxfree = $istaxfree < 0 ? 0 : $istaxfree;
            $istaxfree = ($istaxfree !== 0 && $istaxfree !== 1) ? 0 : $istaxfree;
            
            $onsalestartdateutc = sanitize_text_field($_POST['dragonecommercereservezyx987_editproductonsalestartdateutc']);
            $onsalestartdateutc = deslash($onsalestartdateutc);
            if($onsalestartdateutc === '' || dragonecommercereservezyx987_validateDate($onsalestartdateutc)) {
            } else {
                $dragon_ecommerce_dbResult .= 'On sale start date does not have a correct time format. ';return;
            }            
            
            $onsaleenddateutc = sanitize_text_field($_POST['dragonecommercereservezyx987_editproductonsaleenddateutc']);
            $onsaleenddateutc = deslash($onsaleenddateutc);
            if($onsaleenddateutc === '' || dragonecommercereservezyx987_validateDate($onsaleenddateutc)) {
            } else {
                $dragon_ecommerce_dbResult .= 'On sale end date does not have a correct time format. ';return;
            }
            
            $quantity = (trim($_POST['dragonecommercereservezyx987_editproductquantity']) === "" || $_POST['dragonecommercereservezyx987_editproductquantity'] === "null") ? -1 : intval(sanitize_text_field($_POST['dragonecommercereservezyx987_editproductquantity']));
            $originalquantity = (trim($_POST['dragonecommercereservezyx987_editproductoriginalquantity']) === "" || $_POST['dragonecommercereservezyx987_editproductoriginalquantity'] === "null") ? -1 : intval(sanitize_text_field($_POST['dragonecommercereservezyx987_editproductoriginalquantity']));
            
            $departmentid = intval(sanitize_text_field($_POST['dragonecommercereservezyx987_editproductdepartment']));
            $description = sanitize_text_field($_POST['dragonecommercereservezyx987_editproductdescription']);
            $description = deslash($description);
            $editproductweightlb = floatval(sanitize_text_field($_POST['dragonecommercereservezyx987_editproductweightlb']));
            $editproductbarcode = sanitize_text_field($_POST['dragonecommercereservezyx987_editproductbarcode']);
            $editproductbarcode = deslash($editproductbarcode);
            $removeimages_temp = (!isset($_POST['dragonecommercereservezyx987_editproductremoveimages'])) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_editproductremoveimages']);
            $removeimages_temp = strip_tags($removeimages_temp);
            $removeimages = ($removeimages_temp === 'removeimages') ? true : false;
            $mygroupid = 0;
            //$groupsArr = [];
            //if(isset($_POST['dragonecommercereservezyx987_editproductgroup'])){
              //if(is_array($_POST['dragonecommercereservezyx987_editproductgroups'])) {
              //    foreach($_POST['dragonecommercereservezyx987_editproductgroups'] as $value){
                //    if(intval(sanitize_text_field($value)) > 0) {
                //        $groupsArr[] = intval(sanitize_text_field($value));
                //    }
                //}
              //} else {
                $dragonecommercereservezyx987_editproductgroup = sanitize_text_field($_POST['dragonecommercereservezyx987_editproductgroup']);
                //if($dragonecommercereservezyx987_editproductgroup !== '-1') {
                    $mygroupid = intval($dragonecommercereservezyx987_editproductgroup);
                //}
              //}
            //}
            if($mygroupid <= 0 && $mygroupid !== -1) {
                $dragon_ecommerce_dbResult .= 'Group id is not valid: ' .$mygroupid . '. Not saved.';return;
            }
            $result = '';$result2 = [];
            if($name === '' || $price <= 0 || $product_id <= 0) {$dragon_ecommerce_dbResult .= 'Edit an ecommerce product: Name, price, currency and department are all required. Not saved. ';return;}
            if($isonsale === 1 && $saleprice <= 0) {$dragon_ecommerce_dbResult .= 'Edit an ecommerce product: If item is on sale, a sale price is needed. Not saved. ';return;}
            
            //check if this product name exists in product table
            $dbcount = 0;
            $product_image_size = 800;
            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", $name, $product_id);
                $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 .= "Edit a product: product name \"" . $name . "\" already exists in the product table. Not saved. ";return;}
                } else {
                    $dragon_ecommerce_dbResult .= "Edit a product: product name \"" . $name . "\" query has error. Not saved. ";return;
                }    
            } else {
                $dragon_ecommerce_dbResult .= 'Mysqli is not supported by your system. ';return;
            }    
            //get product image size from setting table.
            $product_image_size_temp = $wpdb->get_var("SELECT value FROM $table_name3 WHERE name = 'PRODUCT_IMAGE_SIZE'");
            $product_image_size_temp2 = ($product_image_size_temp === null || $product_image_size_temp === 'null') ? '800' : intval($product_image_size_temp);
            if($product_image_size_temp2 <= 0) {
                $dragon_ecommerce_dbResult .= "Edit a product: PRODUCT_IMAGE_SIZE value is less than 0 in setting table. Not saved. ";return;
            } else {
                $product_image_size = $product_image_size_temp2;
            }            
            $target_dir = dragonecommercereservezyx987_upload_folder() . "/images/product/" . $product_id  . "/";
            $target_dir_preview = dragonecommercereservezyx987_upload_folder() . "/images/product/" . $product_id  . "/preview/";
            $target_dir_thumbnail = dragonecommercereservezyx987_upload_folder() . "/images/product/" . $product_id  . "/thumbnail/";
            $imagefilenames = '';
            if(basename($_FILES["dragonecommercereservezyx987_editproductuploadproductimages"]["name"]) !== '') {
                try{
                    if(!file_exists($target_dir)) {
                        mkdir($target_dir, 0755, true);
                    } else {        
                        chmod($target_dir, 0777);
                        $files = glob($target_dir . '*');
                        foreach($files as $file){
                          if(is_file($file))
                            unlink($file);
                        }
                    }                
                    if(!file_exists($target_dir_preview)) {
                        mkdir($target_dir_preview, 0755, true);
                    } else {        
                        chmod($target_dir_preview, 0777);
                        $files = glob($target_dir_preview . '*');
                        foreach($files as $file){
                          if(is_file($file))
                            unlink($file);
                        }
                    }                
                    if(!file_exists($target_dir_thumbnail)) {
                        mkdir($target_dir_thumbnail, 0755, true);
                    } else {        
                        chmod($target_dir_thumbnail, 0777);
                        $files = glob($target_dir_thumbnail . '*');
                        foreach($files as $file){
                          if(is_file($file))
                            unlink($file);
                        }
                    }                
                    $target_file = $target_dir . basename($_FILES["dragonecommercereservezyx987_editproductuploadproductimages"]["name"]);
                    $uploadOk = 1;
                    $fileType = strtolower(pathinfo($_FILES["dragonecommercereservezyx987_editproductuploadproductimages"]["name"], PATHINFO_EXTENSION));

                    // Check if file already exists
                    if(file_exists($target_file)) {
                      $dragon_ecommerce_dbResult .= "Sorry, file already exists. Change the filename and upload again. ";
                      $uploadOk = 0;
                    }

                    // Check file size smaller than 50MB
                    if($_FILES["dragonecommercereservezyx987_editproductuploadproductimages"]["size"] > 50000000) {
                      $dragon_ecommerce_dbResult .= "Sorry, your file is bigger than 50MB. Split into separate files and upload one by one. ";
                      $uploadOk = 0;
                    }

                    if($fileType !== "zip") {
                      $dragon_ecommerce_dbResult .= "Sorry, only zip files are allowed. ";
                      $uploadOk = 0;
                    }

                    if($uploadOk == 0) {
                      $dragon_ecommerce_dbResult .= "Sorry, your file was not uploaded. ";return;
                    } else {
                        add_filter( 'upload_dir', 'dragonecommercereservezyx987_uploadProductImage_dir' );
                        $upload_result = wp_handle_upload($_FILES["dragonecommercereservezyx987_editproductuploadproductimages"], array('test_form' => false));
                        remove_filter( 'upload_dir', 'dragonecommercereservezyx987_uploadProductImage_dir' );                                        
                        if($upload_result) {
                            //unzip files
                            $zip = new ZipArchive;
                            $res = $zip->open($target_file);
                            if($res === TRUE) {
                                $zip->extractTo($target_dir);
                                $zip->close();        
                            } else {
                                $dragon_ecommerce_dbResult .= 'Can NOT open product image zip file. ';
                            }

                            if(!unlink($target_file)) {
                                $dragon_ecommerce_dbResult .= 'Can NOT delete uploaded product image zip file. File path: ' . $target_file . ". ";
                            } else {                
                                $files = glob($target_dir . '*');
                                foreach($files as $file){
                                    if(is_file($file)) {
                                        $target_file2 = $target_dir . basename($file);
                                        $target_file4 = $target_dir . 'preview/' . basename($file);
                                        copy($file, $target_file2);
                                        $img2 = dragonecommercereservezyx987_resize_image_keep_ratio($target_file2, $product_image_size);
                                        $fileType = strtolower(pathinfo($file, PATHINFO_EXTENSION));
                                        if($fileType === 'jpeg' || $fileType === 'jpg') {
                                            imagejpeg($img2, $target_file4);
                                        } elseif($fileType === 'png') {
                                            imagepng($img2, $target_file4);
                                        }

                                        $target_file3 = $target_dir . basename($file);
                                        $target_file5 = $target_dir . 'thumbnail/' . basename($file);
                                        copy($file, $target_file3);
                                        $img3 = dragonecommercereservezyx987_resize_image_keep_ratio($target_file3, 100);
                                        if($fileType === 'jpeg' || $fileType === 'jpg') {
                                            imagejpeg($img3, $target_file5);
                                        } elseif($fileType === 'png') {
                                            imagepng($img3, $target_file5);
                                        }
                                        $imagefilenames .=    '|' . basename($file);                
                                    }
                                }                
                            }
                        } else {
                            $dragon_ecommerce_dbResult .= 'Can not upload file to product image folder. Try to upload a smaller size file. Product id: ' . $product_id . ", name: " . $name . ". ";
                        }
                    }    
                } catch(Exception $e) {
                    $dragon_ecommerce_dbResult .= 'Image file upload exception: ' .$e->getMessage() . ". ";
                }            
            }
            if($imagefilenames !== '') {$imagefilenames = substr($imagefilenames, 1);}

            if($wpdb->use_mysqli) {
                if($wpdb->dbh->connect_error) {
                    die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
                }                
                $stmt=null;
                $sqlColumnsArray = array();        
                $sqlColumnsArray['isonsale|i'] = $isonsale;    
                $sqlColumnsArray['istaxfree|i'] = $istaxfree;
                $sqlColumnsArray['onsalestartdateutc|s'] = $onsalestartdateutc;
                $sqlColumnsArray['onsaleenddateutc|s'] = $onsaleenddateutc;                
                $sqlColumnsArray['name|s'] = $name;
                $sqlColumnsArray['price|d'] = $price;
                $sqlColumnsArray['saleprice|d'] = $saleprice;                
                $sqlColumnsArray['description|s'] = $description;
                $sqlColumnsArray['departmentid|i'] = $departmentid;
                $sqlColumnsArray['quantity|i'] = $quantity;
                $sqlColumnsArray['originalquantity|i'] = $originalquantity;
                $sqlColumnsArray['weightlb|d'] = $editproductweightlb;
                $sqlColumnsArray['barcode|s'] = $editproductbarcode;            
                if($imagefilenames !== '' || ($imagefilenames === '' && $removeimages)) {
                    $sqlColumnsArray['imagefilenames|s'] = $imagefilenames;    
                }
                if(count($sqlColumnsArray) > 0) {
                    $query = "UPDATE $table_name SET ";
                    $types = '';
                    $parameterArray = array('');                
                    foreach($sqlColumnsArray as $key => $value) {
                        $temp = explode('|', $key, 2);
                        if($temp[0] === 'quantity' && $quantity <= 0) {
                            $query .= ' ' . $temp[0] . ' = null, ';                    
                        } elseif($temp[0] === 'originalquantity' && $originalquantity <= 0) {
                            $query .= ' ' . $temp[0] . ' = null, ';                    
                        } elseif($temp[0] === 'departmentid' && $departmentid <= 0) {
                            $query .= ' ' . $temp[0] . ' = null, ';                    
                        } elseif($temp[0] === 'weightlb' && $editproductweightlb <= 0) {
                            $query .= ' ' . $temp[0] . ' = null, ';                    
                        } elseif($temp[0] === 'saleprice' && $saleprice_isempty === true) {
                            $query .= ' ' . $temp[0] . ' = null, ';                    
                        } elseif($temp[0] === 'description' && $description === '') {
                            $query .= ' ' . $temp[0] . ' = null, ';                    
                        } elseif($temp[0] === 'imagefilenames' && $imagefilenames === '' && $removeimages) {
                            $query .= ' ' . $temp[0] . ' = null, ';                    
                        } elseif($temp[0] === 'barcode' && $editproductbarcode === '') {
                            $query .= ' ' . $temp[0] . ' = null, ';                    
                        } elseif($temp[0] === 'onsalestartdateutc' && $onsalestartdateutc === '') {
                            $query .= ' ' . $temp[0] . ' = null, ';                    
                        } elseif($temp[0] === 'onsaleenddateutc' && $onsaleenddateutc === '') {
                            $query .= ' ' . $temp[0] . ' = null, ';                    
                        } else {
                            $types .= $temp[1];
                            $query .= ' ' . $temp[0] . ' = ?, ';
                        }
                        
                        if($temp[0] === 'isonsale') {
                            $parameterArray[] = &$isonsale;
                        } elseif($temp[0] === 'istaxfree') {
                            $parameterArray[] = &$istaxfree;
                        } elseif($temp[0] === 'name') {
                            $parameterArray[] = &$name;
                        } elseif($temp[0] === 'price') {
                            $parameterArray[] = &$price;
                        } elseif($temp[0] === 'saleprice') {
                            if($saleprice_isempty === false) {
                                $parameterArray[] = &$saleprice;
                            }
                        } elseif($temp[0] === 'description') {
                            if($description !== '') {
                                $parameterArray[] = &$description;
                            }
                        } elseif($temp[0] === 'departmentid') {
                            if($departmentid > 0) {
                                $parameterArray[] = &$departmentid;
                            }
                        } elseif($temp[0] === 'quantity') {
                            if($quantity > 0) {
                                $parameterArray[] = &$quantity;
                            }
                        } elseif($temp[0] === 'originalquantity') {
                            if($originalquantity > 0) {
                                $parameterArray[] = &$originalquantity;
                            }
                        } elseif($temp[0] === 'weightlb') {
                            if($editproductweightlb > 0) {
                                $parameterArray[] = &$editproductweightlb;
                            }
                        } elseif($temp[0] === 'barcode') {
                            if($editproductbarcode !== '') {
                                $parameterArray[] = &$editproductbarcode;
                            }
                        } elseif($temp[0] === 'imagefilenames') {
                            if($imagefilenames !== '') {
                                $parameterArray[] = &$imagefilenames;
                            }
                        } elseif($temp[0] === 'onsalestartdateutc') {
                            if($onsalestartdateutc !== '') {
                                $parameterArray[] = &$onsalestartdateutc;
                            }
                        } elseif($temp[0] === 'onsaleenddateutc') {
                            if($onsaleenddateutc !== '') {
                                $parameterArray[] = &$onsaleenddateutc;
                            }
                        }                    
                    }
                    $query .= " updatetimeutc = UTC_TIMESTAMP() WHERE id = ? ";    
                    $types .= 'i';
                    $parameterArray[] = &$product_id;                
                    $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) {
                        $dragon_ecommerce_dbResult .= 'Edit product failed';
                    }
                    $stmt->close();
                    $result2[] = $wpdb->query($wpdb->prepare("DELETE FROM $table_name2 where `productid`=%d", array($product_id)));    
                    //foreach($groupsArr as $mygroupid) {
                    if($mygroupid > 0) {
                        $result2[] = $wpdb->query($wpdb->prepare("INSERT INTO $table_name2 (`productid`,`groupid`,`createtimeutc`) VALUES (%d,%d,UTC_TIMESTAMP())", array($product_id, $mygroupid)));            
                    }                    
                } else {
                    $dragon_ecommerce_dbResult .= 'Nothing is updated. ';
                }            
            } else {
                $dragon_ecommerce_dbResult .= 'Mysqli is not supported by your system. ';
            }
            foreach($result2 as $temp) {
                if($temp === FALSE) {
                    $dragon_ecommerce_dbResult .= 'Error deleting from or inserting into table ' . $table_name2 . ". ";
                }
            }
        } catch (Exception $e) {
            $dragon_ecommerce_dbResult .= $e->getMessage();
        } finally {
        }
        if($dragon_ecommerce_dbResult === '') {$dragon_ecommerce_dbResult .= 'Success.';}
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }    
}

function dragonecommercereservezyx987_resize_image_keep_ratio($file, $w, $crop=FALSE) {
    list($width, $height) = getimagesize($file);
    $newwidth;$newheight;$h;    
    if($height > 0) {
        $r = $width / $height;
        $h = ($w / $width) * $height;
        if($crop) {
            if($width > $height) {
                $width = ceil($width-($width*abs($r-$w/$h)));
            } else {
                $height = ceil($height-($height*abs($r-$w/$h)));
            }
            $newwidth = $w;
            $newheight = $h;
        } else {
            if($w/$h > $r) {
                $newwidth = $h*$r;
                $newheight = $h;
            } else {
                $newheight = $w/$r;
                $newwidth = $w;
            }
        }
        $fileType = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        $src = ($fileType === 'jpeg' || $fileType === 'jpg') ? imagecreatefromjpeg($file) : ($fileType === 'png' ? imagecreatefrompng($file) : null);
        if($src !== null) {
            $dst = imagecreatetruecolor($newwidth, $newheight);                
            imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
            
            $exif = exif_read_data($file);
            if(!empty($exif['Orientation'])) {
                switch($exif['Orientation']) {
                    case 8:
                        $dst = imagerotate($dst,90,0);
                        break;
                    case 3:
                        $dst = imagerotate($dst,180,0);
                        break;
                    case 6:
                        $dst = imagerotate($dst,-90,0);
                        break;
                }
            }            
            return $dst;
        }
        return null;
    }
    return null;
}

function dragonecommercereservezyx987_resize_image($file, $w, $h, $crop=FALSE) {
    list($width, $height) = getimagesize($file);
    $newwidth;$newheight;
    if($height > 0) {
        $r = $width / $height;
        if($crop) {
            if($width > $height) {
                $width = ceil($width-($width*abs($r-$w/$h)));
            } else {
                $height = ceil($height-($height*abs($r-$w/$h)));
            }
            $newwidth = $w;
            $newheight = $h;
        } else {
            if($w/$h > $r) {
                $newwidth = $h*$r;
                $newheight = $h;
            } else {
                $newheight = $w/$r;
                $newwidth = $w;
            }
        }
        $fileType = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        $src = ($fileType === 'jpeg' || $fileType === 'jpg') ? imagecreatefromjpeg($file) : ($fileType === 'png' ? imagecreatefrompng($file) : null);
        if($src !== null) {
            $dst = imagecreatetruecolor($newwidth, $newheight);
            imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
            return $dst;
        }
        return null;
    }
    return null;
}

function dragonecommercereservezyx987_addProperty() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_addProperty') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_property';         
        $name = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addpropertyname']));
        $shownname = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addpropertyshownname']));
        $description = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addpropertydescription']));
        if($name === '' || $shownname === '') {$dragon_ecommerce_dbResult .= 'Create a new property: property name and view name are required. Not saved. ';return;}
        $priority_temp = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addpropertypriority']));
        $priority = $priority_temp === '' ? null : intval($priority_temp);
        if($priority !== null && !ctype_digit($priority_temp)) {$dragon_ecommerce_dbResult .= 'Create a new property: priority should be an integer. Not saved. ';return;}
        
        $forallproduct_temp = trim(sanitize_text_field($_POST['dragonecommerce_addpropertyforallproduct']));
        $forallproduct = intval($forallproduct_temp);
        if(($forallproduct !== -1) && ($forallproduct !== 0) &&($forallproduct !== 1)) {$dragon_ecommerce_dbResult .= "Create a new property: forallproduct has a wrong value: $forallproduct. Not saved. ";return;}
        
        $mandatory_temp = trim(sanitize_text_field($_POST['dragonecommerce_addpropertymandatory']));
        $mandatory = intval($mandatory_temp);
        if(($mandatory !== -1) && ($mandatory !== 0) &&($mandatory !== 1)) {$dragon_ecommerce_dbResult .= "Create a new property: mandatory has a wrong value: $mandatory. Not saved. ";return;}
        if (strpos($shownname, ',') !== false || strpos($shownname, ';') !== false || strpos($shownname, ':') !== false) {
            $dragon_ecommerce_dbResult .= 'Not saved. Property shown name should not contain , ; :'; 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 property: property name \"" . $name . "\" already exists in the property table. Not saved. ";return;}
            } else {
                $dragon_ecommerce_dbResult .= "Create a new property: property name \"" . $name . "\" query has error. Not saved. ";return;
            }
            $myresult = 0;
            if($priority === null && $forallproduct === -1 && $mandatory === -1) {
                $query = "INSERT INTO " . $table_name . " (`name`,`shownname`,`description`,`createtimeutc`) VALUES (?,?,?,UTC_TIMESTAMP())";
                $stmt = $wpdb->dbh->prepare($query);
                $types = '';
                $parameterArray = array('');
                
                $types .= 's';
                $parameterArray[] = &$name;
                
                $types .= 's';
                $parameterArray[] = &$shownname;            
                            
                $types .= 's';
                $parameterArray[] = &$description;
                
                $parameterArray[0] = $types;
                call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                $stmt->execute();
                $myresult = $stmt->insert_id;                        
                $stmt->close();
            } elseif($priority === null && $forallproduct === -1 && $mandatory !== -1) {
                $query = "INSERT INTO " . $table_name . " (`name`,`shownname`,`mandatory`,`description`,`createtimeutc`) VALUES (?,?,?,?,UTC_TIMESTAMP())";
                $stmt = $wpdb->dbh->prepare($query);
                $types = '';
                $parameterArray = array('');
                
                $types .= 's';
                $parameterArray[] = &$name;
                
                $types .= 's';
                $parameterArray[] = &$shownname;
                
                $types .= 'i';
                $parameterArray[] = &$mandatory;            
                            
                $types .= 's';
                $parameterArray[] = &$description;
                
                $parameterArray[0] = $types;
                call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                $stmt->execute();
                $myresult = $stmt->insert_id;                        
                $stmt->close();                        
            } elseif($priority === null && $forallproduct !== -1 && $mandatory === -1) {
                $query = "INSERT INTO " . $table_name . " (`name`,`shownname`,`forallproduct`,`description`,`createtimeutc`) VALUES (?,?,?,?,UTC_TIMESTAMP())";
                $stmt = $wpdb->dbh->prepare($query);
                $types = '';
                $parameterArray = array('');
                
                $types .= 's';
                $parameterArray[] = &$name;
                
                $types .= 's';
                $parameterArray[] = &$shownname;
                
                $types .= 'i';
                $parameterArray[] = &$forallproduct;            
                            
                $types .= 's';
                $parameterArray[] = &$description;
                
                $parameterArray[0] = $types;
                call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                $stmt->execute();
                $myresult = $stmt->insert_id;                        
                $stmt->close();                
            } elseif($priority === null && $forallproduct !== -1 && $mandatory !== -1) {
                $query = "INSERT INTO " . $table_name . " (`name`,`shownname`,`forallproduct`,`mandatory`,`description`,`createtimeutc`) VALUES (?,?,?,?,?,UTC_TIMESTAMP())";
                $stmt = $wpdb->dbh->prepare($query);
                $types = '';
                $parameterArray = array('');
                
                $types .= 's';
                $parameterArray[] = &$name;
                
                $types .= 's';
                $parameterArray[] = &$shownname;
                
                $types .= 'i';
                $parameterArray[] = &$forallproduct;

                $types .= 'i';
                $parameterArray[] = &$mandatory;            
                            
                $types .= 's';
                $parameterArray[] = &$description;
                
                $parameterArray[0] = $types;
                call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                $stmt->execute();
                $myresult = $stmt->insert_id;                        
                $stmt->close();                    
            } elseif($priority !== null && $forallproduct === -1 && $mandatory === -1) {
                $query = "INSERT INTO " . $table_name . " (`name`,`shownname`,`priority`,`description`,`createtimeutc`) VALUES (?,?,?,?,UTC_TIMESTAMP())";
                $stmt = $wpdb->dbh->prepare($query);
                $types = '';
                $parameterArray = array('');
                
                $types .= 's';
                $parameterArray[] = &$name;
                
                $types .= 's';
                $parameterArray[] = &$shownname;
                
                $types .= 'i';
                $parameterArray[] = &$priority;            
                            
                $types .= 's';
                $parameterArray[] = &$description;
                
                $parameterArray[0] = $types;
                call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                $stmt->execute();
                $myresult = $stmt->insert_id;                        
                $stmt->close();            
            } elseif($priority !== null && $forallproduct === -1 && $mandatory !== -1) {
                $query = "INSERT INTO " . $table_name . " (`name`,`shownname`,`priority`,`mandatory`,`description`,`createtimeutc`) VALUES (?,?,?,?,?,UTC_TIMESTAMP())";
                $stmt = $wpdb->dbh->prepare($query);
                $types = '';
                $parameterArray = array('');
                
                $types .= 's';
                $parameterArray[] = &$name;
                
                $types .= 's';
                $parameterArray[] = &$shownname;
                
                $types .= 'i';
                $parameterArray[] = &$priority;            

                $types .= 'i';
                $parameterArray[] = &$mandatory;    
                
                $types .= 's';
                $parameterArray[] = &$description;
                
                $parameterArray[0] = $types;
                call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                $stmt->execute();
                $myresult = $stmt->insert_id;                        
                $stmt->close();                
            } elseif($priority !== null && $forallproduct !== -1 && $mandatory === -1) {
                $query = "INSERT INTO " . $table_name . " (`name`,`shownname`,`priority`,`forallproduct`,`description`,`createtimeutc`) VALUES (?,?,?,?,?,UTC_TIMESTAMP())";
                $stmt = $wpdb->dbh->prepare($query);
                $types = '';
                $parameterArray = array('');
                
                $types .= 's';
                $parameterArray[] = &$name;
                
                $types .= 's';
                $parameterArray[] = &$shownname;
                
                $types .= 'i';
                $parameterArray[] = &$priority;            

                $types .= 'i';
                $parameterArray[] = &$forallproduct;    
                
                $types .= 's';
                $parameterArray[] = &$description;
                
                $parameterArray[0] = $types;
                call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                $stmt->execute();
                $myresult = $stmt->insert_id;                        
                $stmt->close();                
            } elseif($priority !== null && $forallproduct !== -1 && $mandatory !== -1) {
                $query = "INSERT INTO " . $table_name . " (`name`,`shownname`,`priority`,`forallproduct`,`mandatory`,`description`,`createtimeutc`) VALUES (?,?,?,?,?,?,UTC_TIMESTAMP())";
                $stmt = $wpdb->dbh->prepare($query);
                $types = '';
                $parameterArray = array('');
                
                $types .= 's';
                $parameterArray[] = &$name;
                
                $types .= 's';
                $parameterArray[] = &$shownname;
                
                $types .= 'i';
                $parameterArray[] = &$priority;            

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

                $types .= 'i';
                $parameterArray[] = &$mandatory;
                
                $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 property 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 dragonecommercereservezyx987_addPropertyValue() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_addPropertyvalue') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_propertyvalue';
        $propertyid = intval(sanitize_text_field($_POST['dragonecommercereservezyx987_addpropertyvalueproperty']));
        $name = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addpropertyvaluepropertyvaluename']));
        $shownname = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addpropertyvaluepropertyvalueshownname']));
        $description = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addpropertyvaluepropertyvaluedescription']));        
        if($propertyid === -1 || $name === '' || $shownname === '') {$dragon_ecommerce_dbResult .= 'Create a new property value: property, property value name and property value shown name are required. Not saved. ';return;}
        if (strpos($shownname, ',') !== false || strpos($shownname, ';') !== false || strpos($shownname, ':') !== false) {
            $dragon_ecommerce_dbResult .= 'Not saved. Property value shown name should not contain , ; :'; return;
        }    
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            //No duplicate property value for the same property.
            $stmt = $wpdb->dbh->prepare("SELECT COUNT(*) countresult FROM $table_name WHERE name = ? AND propertyid = ?");
            $stmt->bind_param("si", $name, $propertyid);                
            $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 property value: property value name \"" . $name . "\" for the same property already exists in the propertyvalue table. Not saved. ";return;}
            } else {
                $dragon_ecommerce_dbResult .= "Create a new property value: property value name \"" . $name . "\" query has error. Not saved. ";return;
            }
            $query = "INSERT INTO " . $table_name . " (`propertyid`,`name`,`shownname`,`description`,`createtimeutc`) VALUES (?,?,?,?,UTC_TIMESTAMP())";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');

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

            $types .= 's';
            $parameterArray[] = &$shownname;
            
            $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 property value 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 dragonecommercereservezyx987_getProperties($onlyActive = true) {
    global $wpdb; global $dragon_ecommerce_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_dragonecommercereservezyx987_property';
    if($onlyActive) {    
        $results = $wpdb->get_results("SELECT id,name,status from $table_name WHERE status = 1 order by name");
    } else {
        $results = $wpdb->get_results("SELECT id,name,status from $table_name order by name");        
    }        
    foreach($results as $result) {
        foreach($result as $key => $value) {
            $result->$key = deslash($value);
        }
    }
    return $results;
}

function dragonecommercereservezyx987_getPropertyvalues($onlyActive = true) {
    global $wpdb; global $dragon_ecommerce_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_dragonecommercereservezyx987_propertyvalue';
    $table_name2 = 'wp_dragonecommercereservezyx987_property';
    if($onlyActive) {    
        $results = $wpdb->get_results("SELECT a.id,a.propertyid,a.name,a.status,b.name as 'propertyname' from $table_name a JOIN $table_name2 b ON a.propertyid = b.id WHERE a.status = 1 and b.status = 1 order by a.name");
    } else {
        $results = $wpdb->get_results("SELECT a.id,a.propertyid,a.name,a.status,b.name as 'propertyname' from $table_name a JOIN $table_name2 b ON a.propertyid = b.id order by a.name");        
    }
    foreach($results as $result) {
        foreach($result as $key => $value) {
            $result->$key = deslash($value);
        }
    }
    return $results;
}

function dragonecommercereservezyx987_updateGroupProducts() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_updateGroupProducts') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $table_name = 'wp_dragonecommercereservezyx987_product_group';
            $table_name2 = 'wp_dragonecommercereservezyx987_product';        
            $groupid = intval($_POST['dragonecommercereservezyx987_updategroupproductsgroup']);
            $departmentid = intval($_POST['dragonecommercereservezyx987_updategroupproductsdepartment']);
            $query = "DELETE FROM $table_name WHERE groupid = ? and productid in (SELECT id from $table_name2 WHERE departmentid = ?);";
            $types = '';
            $parameterArray = array('');
            
            $types .= 'i';
            $parameterArray[] = &$groupid;
            $types .= 'i';
            $parameterArray[] = &$departmentid;
            $parameterArray[0] = $types;
            if($stmt = $wpdb->dbh->prepare($query)) {
                call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                $stmt->execute();
            } else {
                 $dragon_ecommerce_dbResult .= "Error saving a group's properties to database. query: " . $query;
            }            
                                                        
            if(count($_POST['dragonecommercereservezyx987_updategroupproducts_product']) > 0) {    
                foreach ($_POST['dragonecommercereservezyx987_updategroupproducts_product'] as $temp) {
                    $types = '';
                    $parameterArray = array('');
                    $productid = intval($temp);
                    $query = "INSERT INTO $table_name (groupid,productid,createtimeutc,status) VALUES (?,?,UTC_TIMESTAMP(),1);";
                    $types .= 'i';
                    $parameterArray[] = &$groupid;
                    $types .= 'i';
                    $parameterArray[] = &$productid;                
                    $parameterArray[0] = $types;
                    if($stmt = $wpdb->dbh->prepare($query)) {
                        call_user_func_array(array($stmt, 'bind_param'), $parameterArray);        
                        $stmt->execute();
                    } else {
                        $dragon_ecommerce_dbResult .= "Error saving a group's products to database. query: " . $query;
                    }
                }
            }
            $stmt->close();    
        } else {
            $dragon_ecommerce_dbResult = "This website can not use mysqli.";
        }
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }    
}

function dragonecommercereservezyx987_updateDepartmentProducts() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_updateDepartmentProducts') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $table_name = 'wp_dragonecommercereservezyx987_product';        
            $departmentid = intval($_POST['dragonecommercereservezyx987_updatedepartmentproductsdepartment']);
            $query = "UPDATE $table_name SET departmentid = NULL WHERE departmentid = ?;";
            $types = '';
            $parameterArray = array('');
            
            $types .= 'i';
            $parameterArray[] = &$departmentid;
            $parameterArray[0] = $types;
            if($stmt = $wpdb->dbh->prepare($query)) {
                call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                $stmt->execute();    
            } else {
                 $dragon_ecommerce_dbResult .= "Error saving a group's properties to database. query: " . $query;
            }                                                        
            if(count($_POST['dragonecommercereservezyx987_updatedepartmentproducts_product']) > 0) {    
                foreach($_POST['dragonecommercereservezyx987_updatedepartmentproducts_product'] as $temp) {
                    $types = '';
                    $parameterArray = array('');
                    $productid = intval($temp);
                    $query = "UPDATE $table_name SET departmentid = ?, updatetimeutc = UTC_TIMESTAMP() WHERE id = ?;";
                    $types .= 'i';
                    $parameterArray[] = &$departmentid;
                    $types .= 'i';
                    $parameterArray[] = &$productid;                
                    $parameterArray[0] = $types;
                    if($stmt = $wpdb->dbh->prepare($query)) {
                        call_user_func_array(array($stmt, 'bind_param'), $parameterArray);        
                        $stmt->execute();
                    } else {
                        $dragon_ecommerce_dbResult .= "Error saving a department's products to database. query: " . $query;
                    }
                }
            }
            $stmt->close();
        } else {
            $dragon_ecommerce_dbResult = "This website can not use mysqli.";
        }
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }    
}

function dragonecommercereservezyx987_addProcessStatus() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_addProcessstatus') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_processstatus';         
        $name = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addprocessstatusname']));
        $description = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addprocessstatusdescription']));        
        if($name === '') {$dragon_ecommerce_dbResult .= 'Create a new process status: process status 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_ecommerce_dbResult .= "Create a new process status: process status name \"" . $name . "\" already exists in the process status table. Not saved. ";return;}
            } else {
                $dragon_ecommerce_dbResult .= "Create a new process status: process status 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_ecommerce_dbResult .= 'Error adding a process status 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 dragonecommercereservezyx987_getAllProcessstatuses($onlyActive = false) {
    global $wpdb; global $dragon_ecommerce_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_dragonecommercereservezyx987_processstatus';
    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 dragonecommercereservezyx987_getSettingAmountPerPage() {
    global $wpdb; global $dragon_ecommerce_dbResult;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_dragonecommercereservezyx987_setting';
    $result = $wpdb->get_var("SELECT value FROM $table_name WHERE name = 'AMOUNT_PER_PAGE'");        
    return $result === null ? 0 : intval($result);
}

function dragonecommercereservezyx987_addChargeType() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_addChargetype') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_chargetype';         
        $name = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addchargetypename']));
        $description = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addchargetypedescription']));
        $priority_temp = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addchargetypepriority']));
        $priority = $priority_temp === '' ? null : intval($priority_temp);
        
        if($name === '') {$dragon_ecommerce_dbResult .= 'Create a new charge type: charge type name is required. Not saved. ';return;}
        if($priority !== null && $priority_temp !== '0' && $priority === 0) {$dragon_ecommerce_dbResult .= 'Create a new charge type: priority should be an integer. 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 charge type: charge type name \"" . $name . "\" already exists in the charge type table. Not saved. ";return;}
            } else {
                $dragon_ecommerce_dbResult .= "Create a new charge type: charge type name \"" . $name . "\" query has error. Not saved. ";return;
            }
            
            $myresult = 0;        
            if($priority === null) {
                $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();
            } else {
                $query = "INSERT INTO " . $table_name . " (`priority`,`name`,`description`,`createtimeutc`) VALUES (?,?,?,UTC_TIMESTAMP())";
                $stmt = $wpdb->dbh->prepare($query);
                $types = '';
                $parameterArray = array('');
                
                $types .= 'i';
                $parameterArray[] = &$priority;

                $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_ecommerce_dbResult .= 'Error adding a charge type 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 dragonecommercereservezyx987_addupdateSettingEmailMethod() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_createUpdateEmailMethod') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_setting';
        $settingnameemailmethod = 'EMAIL_METHOD';        
        $name = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addupdatesettingemailmethodname']));
        $cc = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addupdatesettingemailmethodcc']));
        $bcc = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addupdatesettingemailmethodbcc']));
        $token = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addupdatesettingemailmethodtoken']));
        $mytemp = (object) array("name" => $name, "cc" => $cc, "bcc" => $bcc, "token" => $token);
        $value = JSON_ENCODE($mytemp);
        
        if($name === '') {$dragon_ecommerce_dbResult .= 'Create email method value in setting table: email method name is required. Not saved. ';return;}
        $result;$dbcount=0;

        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", $settingnameemailmethod);
            $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);
            } else {
                $dragon_ecommerce_dbResult .= "Create a value for email method: setting name \"" . $name . "\" query has error. Not saved. ";return;
            }
            $myresult = 0;        
            if($dbcount === 0) {
                $query = "INSERT INTO " . $table_name . " (`name`,`value`,`createtimeutc`) VALUES (?,?,UTC_TIMESTAMP())";
                $stmt = $wpdb->dbh->prepare($query);
                $types = '';
                $parameterArray = array('');
                
                $types .= 's';
                $parameterArray[] = &$settingnameemailmethod;

                $types .= 's';
                $parameterArray[] = &$value;
                
                $parameterArray[0] = $types;
                call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                $stmt->execute();
                $myresult = $stmt->insert_id;                        
                $stmt->close();
            } else {//update
                $query = "UPDATE $table_name SET `value` = ?, `updatetimeutc` = UTC_TIMESTAMP() WHERE name=?";
                $stmt = $wpdb->dbh->prepare($query);
                $types = '';
                $parameterArray = array('');
                
                $types .= 's';
                $parameterArray[] = &$value;

                $types .= 's';
                $parameterArray[] = &$settingnameemailmethod;
                
                $parameterArray[0] = $types;
                call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                $stmt->execute();
                if($wpdb->dbh->errno > 0 || $stmt->errno > 0) {
                    $stmt->close();$dragon_ecommerce_dbResult .= "Edit value for email method in table " . $table_name . " failed. "; return;
                }                                    
                $stmt->close();            
            }

            if($myresult <= 0) {
                $dragon_ecommerce_dbResult .= 'Error adding value for email method 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 dragonecommercereservezyx987_addSettingProductDefaultLocation() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_addProductDefaultLocation') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_setting';         
        $name = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addsettingproductdefaultlocationname']));
        $value = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addsettingproductdefaultlocationcountry'])) . '|' . trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addsettingproductdefaultlocationprovince']));
        
        if($name === '') {$dragon_ecommerce_dbResult .= 'Create productdefaultlocation value in setting table: productdefaultlocation 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_ecommerce_dbResult .= "Create productdefaultlocation: productdefaultlocation name \"" . $name . "\" already exists in the setting table. Not saved. ";return;}
            } else {
                $dragon_ecommerce_dbResult .= "Create productdefaultlocation: productdefaultlocation name \"" . $name . "\" query has error. Not saved. ";return;
            }
            
            $query = "INSERT INTO " . $table_name . " (`name`,`value`,`createtimeutc`) VALUES ('PRODUCTDEFAULTLOCATION',?,UTC_TIMESTAMP())";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');
            
            $types .= 's';
            $parameterArray[] = &$value;
            
            $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 productdefaultlocation 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 dragonecommercereservezyx987_editSettingProductDefaultLocation() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_updateProductDefaultLocation') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb; $result;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_setting';
        $name = sanitize_text_field($_POST['dragonecommercereservezyx987_editsettingproductdefaultlocationname']);
        $value = sanitize_text_field($_POST['dragonecommercereservezyx987_editsettingproductdefaultlocationcountry']) . '|' . sanitize_text_field($_POST['dragonecommercereservezyx987_editsettingproductdefaultlocationprovince']);
        
        if($name === '' || $value === '') {$dragon_ecommerce_dbResult .= 'Edit product default location value: productdefaultlocation name is required. Product default location name and value are required. Not saved. ';return;}

        if($name !== '' && $value !== '') {
            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 .= "Update product default location value: product default location name \"" . $name . "\" does NOT exist in the setting table. Not saved. ";return;}
                } else {
                    $dragon_ecommerce_dbResult .= "Create product default location: product default location name \"" . $name . "\" query has error. Not saved. ";return;
                }
                
                $query = "UPDATE $table_name SET `value` = ?, `updatetimeutc` = UTC_TIMESTAMP() WHERE name='PRODUCTDEFAULTLOCATION'";
                $stmt = $wpdb->dbh->prepare($query);
                $types = '';
                $parameterArray = array('');
                
                $types .= 's';
                $parameterArray[] = &$value;
                
                $parameterArray[0] = $types;
                call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                $stmt->execute();
                if($wpdb->dbh->errno > 0 || $stmt->errno > 0) {
                    $stmt->close();$dragon_ecommerce_dbResult .= "Edit value for product default location in table " . $table_name . " failed. "; return;
                }            
                $stmt->close();        
            } else {
                $dragon_ecommerce_dbResult .= 'Mysqli is not supported by your system. ';return;
            }
        }
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }    
}

function dragonecommercereservezyx987_addSettingProductDefaultTimezone() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_createProductDefaultTimezone') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

        $table_name = 'wp_dragonecommercereservezyx987_setting';         
        $name = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addsettingproductdefaulttimezonename']));
        $value = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_addsettingproductdefaulttimezonevalue']));
        
        if($name === '') {$dragon_ecommerce_dbResult .= 'Create productdefaulttimezone value in setting table: productdefaulttimezone 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_ecommerce_dbResult .= "Create productdefaulttimezone: productdefaulttimezone name \"" . $name . "\" already exists in the setting table. Not saved. ";return;}
            } else {
                $dragon_ecommerce_dbResult .= "Create productdefaulttimezone: productdefaulttimezone name \"" . $name . "\" query has error. Not saved. ";return;
            }
            
            $query = "INSERT INTO " . $table_name . " (`name`,`value`,`createtimeutc`) VALUES ('PRODUCTDEFAULTTIMEZONE',?,UTC_TIMESTAMP())";
            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');
            
            $types .= 's';
            $parameterArray[] = &$value;
            
            $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 productdefaulttimezone 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 dragonecommercereservezyx987_editSettingProductDefaultTimezone() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_updateProductDefaultTimezone') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_setting';
        $name = sanitize_text_field($_POST['dragonecommercereservezyx987_editsettingproductdefaulttimezonename']);
        $value = sanitize_text_field($_POST['dragonecommercereservezyx987_editsettingproductdefaulttimezonevalue']);    
        
        if($name === '' || $value === '') {$dragon_ecommerce_dbResult .= 'Edit product default timezone value: productdefaulttimezone name is required. Product default timezone name and value are required. Not saved. ';return;}

        if($name !== '' && $value !== '') {
            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 .= "Update productdefaulttimezone: productdefaulttimezone name \"" . $name . "\" does NOT exist in the setting table. Not saved. ";return;}
                } else {
                    $dragon_ecommerce_dbResult .= "Create productdefaulttimezone: productdefaulttimezone name \"" . $name . "\" query has error. Not saved. ";return;
                }
                
                $query = "UPDATE $table_name SET `value` = ?, `updatetimeutc` = UTC_TIMESTAMP() WHERE name='PRODUCTDEFAULTTIMEZONE'";
                $stmt = $wpdb->dbh->prepare($query);
                $types = '';
                $parameterArray = array('');
                
                $types .= 's';
                $parameterArray[] = &$value;
                
                $parameterArray[0] = $types;
                call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                $stmt->execute();
                if($wpdb->dbh->errno > 0 || $stmt->errno > 0) {
                    $stmt->close();$dragon_ecommerce_dbResult .= "Edit value for productdefaulttimezone in table " . $table_name . " failed. "; return;
                }            
                $stmt->close();        
            } else {
                $dragon_ecommerce_dbResult .= 'Mysqli is not supported by your system. ';return;
            }        
        }
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }    
}

function dragonecommercereservezyx987_editSettingShippingfeechargebytimelength() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_editShippingfeeChargeByTimelength') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_setting';
        $name = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_editsettingshippingfeechargebytimelengthname']));
        $value = trim(sanitize_text_field($_POST['dragonecommercereservezyx987_editsettingshippingfeechargebytimelengthvalue']));    
        
        if($name === '' || $value === '') {$dragon_ecommerce_dbResult .= 'Edit SHIPPINGFEE_CHARGE_BY_TIMELENGTH value: SHIPPINGFEE_CHARGE_BY_TIMELENGTH name is required. SHIPPINGFEE_CHARGE_BY_TIMELENGTH name and value are required. Not saved. ';return;}

        if($name !== '' && $value !== '') {
            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 .= "Update SHIPPINGFEE_CHARGE_BY_TIMELENGTH: SHIPPINGFEE_CHARGE_BY_TIMELENGTH name \"" . $name . "\" does NOT exist in the setting table. Not saved. ";return;}
                } else {
                    $dragon_ecommerce_dbResult .= "Create SHIPPINGFEE_CHARGE_BY_TIMELENGTH: SHIPPINGFEE_CHARGE_BY_TIMELENGTH name \"" . $name . "\" query has error. Not saved. ";return;
                }
                
                $query = "UPDATE $table_name SET `value` = ?, `updatetimeutc` = UTC_TIMESTAMP() WHERE name='SHIPPINGFEE_CHARGE_BY_TIMELENGTH'";
                $stmt = $wpdb->dbh->prepare($query);
                $types = '';
                $parameterArray = array('');
                
                $types .= 's';
                $parameterArray[] = &$value;
                
                $parameterArray[0] = $types;
                call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                $stmt->execute();
                if($wpdb->dbh->errno > 0 || $stmt->errno > 0) {
                    $stmt->close();$dragon_ecommerce_dbResult .= "Edit value for SHIPPINGFEE_CHARGE_BY_TIMELENGTH in table " . $table_name . " failed. "; return;
                }            
                $stmt->close();        
            } else {
                $dragon_ecommerce_dbResult .= 'Mysqli is not supported by your system. ';return;
            }        
        }
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }    
}

function dragonecommercereservezyx987_editSettingShippingfeechargebydistance() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_editShippingfeeChargeByDistance') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_setting';
        $name = sanitize_text_field($_POST['dragonecommercereservezyx987_editsettingshippingfeechargebydistancename']);
        $value = sanitize_text_field($_POST['dragonecommercereservezyx987_editsettingshippingfeechargebydistancevalue']);    
        
        if($name === '' || $value === '') {$dragon_ecommerce_dbResult .= 'Edit SHIPPINGFEE_CHARGE_BY_DISTANCE value: SHIPPINGFEE_CHARGE_BY_DISTANCE name is required. SHIPPINGFEE_CHARGE_BY_DISTANCE name and value are required. Not saved. ';return;}

        if($name !== '' && $value !== '') {
            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 .= "Update SHIPPINGFEE_CHARGE_BY_DISTANCE: SHIPPINGFEE_CHARGE_BY_DISTANCE name \"" . $name . "\" does NOT exist in the setting table. Not saved. ";return;}
                } else {
                    $dragon_ecommerce_dbResult .= "Create SHIPPINGFEE_CHARGE_BY_DISTANCE: SHIPPINGFEE_CHARGE_BY_DISTANCE name \"" . $name . "\" query has error. Not saved. ";return;
                }
                
                $query = "UPDATE $table_name SET `value` = ?, `updatetimeutc` = UTC_TIMESTAMP() WHERE name='SHIPPINGFEE_CHARGE_BY_DISTANCE'";
                $stmt = $wpdb->dbh->prepare($query);
                $types = '';
                $parameterArray = array('');
                
                $types .= 's';
                $parameterArray[] = &$value;
                
                $parameterArray[0] = $types;
                call_user_func_array(array($stmt, 'bind_param'), $parameterArray);
                $stmt->execute();
                if($wpdb->dbh->errno > 0 || $stmt->errno > 0) {
                    $stmt->close();$dragon_ecommerce_dbResult .= "Edit value for SHIPPINGFEE_CHARGE_BY_DISTANCE in table " . $table_name . " failed. "; return;
                }            
                $stmt->close();        
            } else {
                $dragon_ecommerce_dbResult .= 'Mysqli is not supported by your system. ';return;
            }        
        }    
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }    
}

function dragonecommercereservezyx987_dropAddressTable() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_dropAddressTable') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_address;";
        $wpdb->query($sql);
        dragonecommercereservezyx987_createTable_address();        
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }    
}

function dragonecommercereservezyx987_dropChargetypeTable() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_dropChargetypeTable') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_chargetype;";
        $wpdb->query($sql);
        dragonecommercereservezyx987_createTable_chargetype();        
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }    
}

function dragonecommercereservezyx987_dropCountryTable() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_dropCountryTable') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_country;";
        $wpdb->query($sql);
        dragonecommercereservezyx987_createTable_country();
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }
}
            
function dragonecommercereservezyx987_dropProvinceAndRelatedTables() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_dropProvinceTable') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_province;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_country_province_city_distance;";
        $wpdb->query($sql);
        dragonecommercereservezyx987_createTable_province();        
        dragonecommercereservezyx987_createTable_country_province_city_distance();
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }    
}

function dragonecommercereservezyx987_dropCityAndRelatedTable() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_dropCityAndRelatedTable') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_country_province_city_distance;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_city;";
        $wpdb->query($sql);
        dragonecommercereservezyx987_createTable_country_province_city_distance();        
        dragonecommercereservezyx987_createTable_city();        
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }    
}

function dragonecommercereservezyx987_dropDepartmentTable() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_dropDepartmentTable') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {        
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_department;";
        $wpdb->query($sql);
        dragonecommercereservezyx987_createTable_department();
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }    
}

function dragonecommercereservezyx987_dropGroupcategoryTable() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_dropGroupcategoryTable') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_groupcategory;";
        $wpdb->query($sql);
        dragonecommercereservezyx987_createTable_groupcategory();
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }        
}

function dragonecommercereservezyx987_dropGroupAndRelatedTables() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_dropGroupTable') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_group;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_group_property;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_order_group;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_product_group;";
        $wpdb->query($sql);
        dragonecommercereservezyx987_createTable_group();
        dragonecommercereservezyx987_createTable_group_property();        
        dragonecommercereservezyx987_createTable_order_group();        
        dragonecommercereservezyx987_createTable_product_group();        
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }    
}

function dragonecommercereservezyx987_dropProcessstatusTable() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_dropProcessstatusTable') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {        
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_processstatus;";
        $wpdb->query($sql);
        dragonecommercereservezyx987_createTable_processstatus();
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }    
}

function dragonecommercereservezyx987_dropPropertyTable() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_dropPropertyTable') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {        
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_property;";
        $wpdb->query($sql);
        dragonecommercereservezyx987_createTable_property();
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }    
}

function dragonecommercereservezyx987_dropPropertyValueTable() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_dropPropertyvalueTable') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_propertyvalue;";
        $wpdb->query($sql);
        dragonecommercereservezyx987_createTable_propertyvalue();
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }    
}

function dragonecommercereservezyx987_dropSettingTable() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_dropSettingTable') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_setting;";
        $wpdb->query($sql);
        dragonecommercereservezyx987_createTable_setting();
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }    
}

function dragonecommercereservezyx987_dropUserStatusAndUserTokenTable() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_dropUserStatusAndUserTokenTable') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_user_status;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_user_token;";
        $wpdb->query($sql);
        dragonecommercereservezyx987_createTable_user_token();
        dragonecommercereservezyx987_createTable_user_status();
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }    
}

function dragonecommercereservezyx987_dropProductAndRelatedTables() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_dropProductTable') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_product;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_product_group;";
        $wpdb->query($sql);    
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_product_order;";
        $wpdb->query($sql);        
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_product_propertyvalue;";
        $wpdb->query($sql);        
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_product_propertyvalue_store;";
        $wpdb->query($sql);        
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_product_quantity_alert;";
        $wpdb->query($sql);        
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_product_store;";
        $wpdb->query($sql);
        dragonecommercereservezyx987_createTable_product();        
        dragonecommercereservezyx987_createTable_product_group();
        dragonecommercereservezyx987_createTable_product_order();    
        dragonecommercereservezyx987_createTable_product_propertyvalue();
        dragonecommercereservezyx987_createTable_product_propertyvalue_store();    
        dragonecommercereservezyx987_createTable_product_quantity_alert();    
        dragonecommercereservezyx987_createTable_product_store();    
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }    
}

function dragonecommercereservezyx987_dropCurrencyTable() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_dropCurrencyTable') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_currency;";
        $wpdb->query($sql);
        dragonecommercereservezyx987_createTable_currency();
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }    
}

function dragonecommercereservezyx987_dropCurrencyexchangerateTable() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_dropCurrencyexchangerateTable') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_currencyexchangerate;";
        $wpdb->query($sql);
        dragonecommercereservezyx987_createTable_currencyexchangerate();
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }    
}

function dragonecommercereservezyx987_dropOrderAndRelatedTables() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_dropOrderTable') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_order;";
        $wpdb->query($sql);        
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_order_group;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_order_propertyvalue;";
        $wpdb->query($sql);        
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_product_order;";
        $wpdb->query($sql);
        dragonecommercereservezyx987_createTable_order();
        dragonecommercereservezyx987_createTable_order_group();    
        dragonecommercereservezyx987_createTable_order_propertyvalue();        
        dragonecommercereservezyx987_createTable_product_order();        
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }    
}

function dragonecommercereservezyx987_dropLogTable() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_dropLogTable') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_log;";
        $wpdb->query($sql);
        dragonecommercereservezyx987_createTable_log();
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }    
}

function dragonecommercereservezyx987_dropLogCreateNewLogTable() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_dropLogCreateNewLogTable') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_log;";
        $wpdb->query($sql);
        dragonecommercereservezyx987_createTable_log();
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }
}

function dragonecommercereservezyx987_dropSlideshowTable() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_dropSlideshowTable') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_slideshow;";
        $wpdb->query($sql);
        dragonecommercereservezyx987_createTable_slideshow();
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }
}

function dragonecommercereservezyx987_dropStoreTable() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_dropStoreTable') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_store;";
        $wpdb->query($sql);
        dragonecommercereservezyx987_createTable_store();        
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }
}

function dragonecommercereservezyx987_dropAllTables() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_dropAllTables') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987';
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_address;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_chargetype;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_city;";
        $wpdb->query($sql);    
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_country;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_country_province_city_distance;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_currency;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_currencyexchangerate;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_department;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_distance;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_emailmethod;";
        $wpdb->query($sql);    
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_group;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_group_property;";        
        $wpdb->query($sql);    
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_groupcategory;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_language;";
        $wpdb->query($sql);    
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_log;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_order;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_order_group;";
        $wpdb->query($sql);    
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_order_propertyvalue;";
        $wpdb->query($sql);    
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_processstatus;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_product;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_product_group;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_product_order;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_product_propertyvalue;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_product_propertyvalue_store;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_product_quantity_alert;";
        $wpdb->query($sql);    
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_product_store;";
        $wpdb->query($sql);    
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_property;";        
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_propertyvalue;";        
        $wpdb->query($sql);    
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_province;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_setting;";        
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_slideshow;";
        $wpdb->query($sql);        
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_store;";
        $wpdb->query($sql);        
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_user_status;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_user_token;";
        $wpdb->query($sql);
        $sql = "DROP TABLE IF EXISTS " . $table_name . "_weight;";
        $wpdb->query($sql);                
        dragonecommercereservezyx987_createTable_slideshow();    
        dragonecommercereservezyx987_createTable_country();    
        dragonecommercereservezyx987_createTable_province();
        dragonecommercereservezyx987_createTable_country_province_city_distance();    
        dragonecommercereservezyx987_createTable_city();
        dragonecommercereservezyx987_createTable_department();
        dragonecommercereservezyx987_createTable_groupcategory();
        dragonecommercereservezyx987_createTable_group();
        dragonecommercereservezyx987_createTable_group_property();    
        dragonecommercereservezyx987_createTable_order_group();    
        dragonecommercereservezyx987_createTable_product_group();
        dragonecommercereservezyx987_createTable_processstatus();
        dragonecommercereservezyx987_createTable_property();    
        dragonecommercereservezyx987_createTable_propertyvalue();
        dragonecommercereservezyx987_createTable_user_token();
        dragonecommercereservezyx987_createTable_user_status();
        dragonecommercereservezyx987_createTable_product();
        dragonecommercereservezyx987_createTable_product_order();
        dragonecommercereservezyx987_createTable_product_propertyvalue();
        dragonecommercereservezyx987_createTable_product_propertyvalue_store();    
        dragonecommercereservezyx987_createTable_product_quantity_alert();
        dragonecommercereservezyx987_createTable_product_store();    
        dragonecommercereservezyx987_createTable_currency();
        dragonecommercereservezyx987_createTable_currencyexchangerate();
        dragonecommercereservezyx987_createTable_order();
        dragonecommercereservezyx987_createTable_order_propertyvalue();
        dragonecommercereservezyx987_createTable_log();
        dragonecommercereservezyx987_createTable_store();        
        dragonecommercereservezyx987_createTable_chargetype();    
        dragonecommercereservezyx987_createTable_address();    
        dragonecommercereservezyx987_createTable_language();
        dragonecommercereservezyx987_createTable_emailmethod();
        dragonecommercereservezyx987_createTable_distance();
        dragonecommercereservezyx987_createTable_weight();    
        dragonecommercereservezyx987_createTable_setting();    
        $dragon_ecommerce_dbResult .= 'Success.';
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }    
}

function dragonecommercereservezyx987_showEcommerceLandingPage() {    
    require_once dirname(__FILE__) . '/' . "dragonecommercereservezyx987_landingpage.php";
}

/* landing page - slideshow */
function dragonecommercereservezyx987_getSlides($onlyActive = true) {
    global $wpdb; global $dragon_ecommerce_dbResult; $results;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $table_name = 'wp_dragonecommercereservezyx987_slideshow';
    if($onlyActive) {    
        $results = $wpdb->get_results("SELECT * from $table_name WHERE status = 1 order by sequencenumber,id");
    } else {
        $results = $wpdb->get_results("SELECT * from $table_name order by sequencenumber,id");        
    }        
    foreach ($results as $result) {
        foreach ($result as $key => $value) {
            $result->$key = deslash($value);
        }
    }
    return $results;    
}

add_action('wp_ajax_dragonecommercereservezyx987_getproductsfordepartment', 'dragonecommercereservezyx987_getProductsForDepartment');
function dragonecommercereservezyx987_getProductsForDepartment() {
    check_ajax_referer('dragonecommercereservezyx987_getproductsfordepartment', 'dragonecommercereservezyx987_hidden_security_getproductsfordepartment');
    $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 json_encode("{}");
        exit();
    }    
    if($current_user !== null && (in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $departmentid_temp = empty($_POST['id']) ? '' : sanitize_text_field($_POST['id']);
        $departmentid_temp = strip_tags($departmentid_temp);
        $departmentid = intval($departmentid_temp);
        
        if($departmentid_temp == $_POST['id'] && $departmentid > 0 && ((string)(int)$departmentid_temp == $departmentid_temp)) {                                
            global $wpdb;
            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
            $table_name = 'wp_dragonecommercereservezyx987_product';                
            if($wpdb->use_mysqli) {
                if($wpdb->dbh->connect_error) {
                    die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
                }
                $stmt = $wpdb->dbh->prepare("SELECT id, name, departmentid from $table_name WHERE status = 1 order by name");//WHERE departmentid = ? 
                //$stmt->bind_param("i", $departmentid);
                $stmt->execute();
                $myresult = $stmt->get_result();
                $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
                $stmt->close();
                header("Content-Type: application/json");
                echo json_encode($result);    
                exit();
            } else {
                $result = array();
                header("Content-Type: application/json");
                echo json_encode($result);    
                exit();    
            }
        }
    }
    $result = array();
    header("Content-Type: application/json");
    echo json_encode($result);
    exit();    
}

add_action('wp_ajax_dragonecommercereservezyx987_getproductpropertyvaluesforproduct', 'dragonecommercereservezyx987_getProductPropertyvaluesForProduct');
function dragonecommercereservezyx987_getProductPropertyvaluesForProduct() {
    check_ajax_referer('dragonecommercereservezyx987_getproductpropertyvaluesforproduct', 'dragonecommercereservezyx987_hidden_security_getproductpropertyvaluesforproduct');
    $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 json_encode("{}");
        exit();
    }        
    if($current_user !== null && (in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $productid_temp = empty($_POST['id']) ? '' : sanitize_text_field($_POST['id']);
        $productid_temp = strip_tags($productid_temp);
        $productid = intval($productid_temp);

        $chosenpropertyids_temp = empty($_POST['values']) ? '' : sanitize_text_field($_POST['values']);
        $chosenpropertyids_temp = strip_tags($chosenpropertyids_temp);
        $chosenpropertyids = $chosenpropertyids_temp;
        
        if($productid_temp == $_POST['id'] && $productid > 0 && ((string)(int)$productid_temp == $productid_temp) &&
           $chosenpropertyids_temp == $_POST['values'] && $chosenpropertyids !== ''
        ) {                                
            global $wpdb;
            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
            $table_name = 'wp_dragonecommercereservezyx987_product_propertyvalue';                
            if($wpdb->use_mysqli) {
                if($wpdb->dbh->connect_error) {
                    die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
                }
                $query = "SELECT propertyvalueids from $table_name WHERE productid = ? ";  

                $chosenpropertyidArr = explode("|",$chosenpropertyids);
                if(count($chosenpropertyidArr) > 0) {
                    for($i=0; $i<count($chosenpropertyidArr); $i++) {
                        if($chosenpropertyidArr[$i] !== '') {
                            $query .= ' AND propertyvalueids LIKE ? ';
                        }
                    }                    
                }
                $query .= ' order by id;';

                $stmt = $wpdb->dbh->prepare($query);
                $types = '';
                $parameterArray = array('');
                
                $types .= 'i';
                $parameterArray[] = &$productid;
                
                if(count($chosenpropertyidArr) > 0) {
                    for($i=0; $i<count($chosenpropertyidArr); $i++) {
                        if($chosenpropertyidArr[$i] !== '') {                        
                            $types .= 's';
                            $temp_id = $chosenpropertyidArr[$i];
                            $temp_id = "%" . $temp_id . "%";
                            $parameterArray[] = &$temp_id;
                        }                    
                    }                
                }
                
                $parameterArray[0] = $types;
                call_user_func_array(array($stmt, 'bind_param'), $parameterArray);    
                $stmt->execute();
                $myresult = $stmt->get_result();
                $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
                $stmt->close();
                
                $finalresult = array();
                for($j=0; $j<count($result); $j++) {
                    $temp_row = $result[$j];
                    $temp_propertyvalueids = $temp_row["propertyvalueids"];
                    $temp_propertyvalueidArr = explode("|",$temp_propertyvalueids);
                    $matchcounter = 0;
                    if((count(array_unique($temp_propertyvalueidArr)) === count($temp_propertyvalueidArr)) && 
                       (count(array_unique($chosenpropertyidArr)) === count($chosenpropertyidArr)) && 
                       (count($temp_propertyvalueidArr) - count($chosenpropertyidArr) === 1)) {
                        for($m=0; $m<count($temp_propertyvalueidArr); $m++) {
                            for($n=0; $n<count($chosenpropertyidArr); $n++) {
                                if($temp_propertyvalueidArr[$m] === $chosenpropertyidArr[$n]) {
                                    $matchcounter++;
                                    break;
                                }                                    
                            }                                
                        }
                    }
                    if($matchcounter === count($chosenpropertyidArr)) {
                        $finalresult[] = $result[$j];
                    }
                }
                header("Content-Type: application/json");
                echo json_encode($finalresult);    
                exit();
            } else {
                $result = array();
                header("Content-Type: application/json");
                echo json_encode($result);    
                exit();    
            }
        }
    }
    $result = array();
    header("Content-Type: application/json");
    echo json_encode($result);
    exit();    
}

add_action('wp_ajax_dragonecommercereservezyx987_getproductpropertyvaluesforproductforoneproperty', 'dragonecommercereservezyx987_getProductPropertyvaluesForProductForOneProperty');
function dragonecommercereservezyx987_getProductPropertyvaluesForProductForOneProperty() {
    check_ajax_referer('dragonecommercereservezyx987_getproductpropertyvaluesforproductforoneproperty', 'dragonecommercereservezyx987_hidden_security_getproductpropertyvaluesforproductforoneproperty');
    $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 json_encode("{}");
        exit();
    }        
    if($current_user !== null && (in_array('administrator', (array) $current_user->roles)) && (!empty($_POST['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {
        $productid_temp = empty($_POST['id']) ? '' : sanitize_text_field($_POST['id']);
        $productid_temp = strip_tags($productid_temp);
        $productid = intval($productid_temp);

        //$chosenpropertyids_temp = empty($_POST['values']) ? '' : strip_tags($_POST['values']);
        //$chosenpropertyids_temp = sanitize_text_field($chosenpropertyids_temp);
        //$chosenpropertyids = $chosenpropertyids_temp;
        
        if($productid_temp == $_POST['id'] && $productid > 0 && ((string)(int)$productid_temp == $productid_temp)) {                                
            global $wpdb;
            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
            $table_name = 'wp_dragonecommercereservezyx987_product_propertyvalue';                
            if($wpdb->use_mysqli) {
                if($wpdb->dbh->connect_error) {
                    die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
                }
                $query = "SELECT propertyvalueids from $table_name WHERE productid = ? ";  

                /*$chosenpropertyidArr = explode("|",$chosenpropertyids);
                if(count($chosenpropertyidArr) > 0) {
                    for($i=0; $i<count($chosenpropertyidArr); $i++) {
                        if($chosenpropertyidArr[$i] !== '') {
                            $query .= ' AND propertyvalueids LIKE ? ';
                        }
                    }                    
                }*/
                $query .= ' order by id;';

                $stmt = $wpdb->dbh->prepare($query);
                $types = '';
                $parameterArray = array('');
                
                $types .= 'i';
                $parameterArray[] = &$productid;
                
                /*if(count($chosenpropertyidArr) > 0) {
                    for($i=0; $i<count($chosenpropertyidArr); $i++) {
                        if($chosenpropertyidArr[$i] !== '') {                        
                            $types .= 's';
                            $temp_id = $chosenpropertyidArr[$i];
                            $temp_id = "%" . $temp_id . "%";
                            $parameterArray[] = &$temp_id;
                        }                    
                    }                
                }*/
                
                $parameterArray[0] = $types;
                call_user_func_array(array($stmt, 'bind_param'), $parameterArray);    
                $stmt->execute();
                $myresult = $stmt->get_result();
                $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
                $stmt->close();
                
                /*$finalresult = array();
                for($j=0; $j<count($result); $j++) {
                    $temp_row = $result[$j];
                    $temp_propertyvalueids = $temp_row["propertyvalueids"];
                    $temp_propertyvalueidArr = explode("|",$temp_propertyvalueids);
                    $matchcounter = 0;
                    if((count(array_unique($temp_propertyvalueidArr)) === count($temp_propertyvalueidArr)) && 
                       (count(array_unique($chosenpropertyidArr)) === count($chosenpropertyidArr)) && 
                       (count($temp_propertyvalueidArr) - count($chosenpropertyidArr) === 1)) {
                        for($m=0; $m<count($temp_propertyvalueidArr); $m++) {
                            for($n=0; $n<count($chosenpropertyidArr); $n++) {
                                if($temp_propertyvalueidArr[$m] === $chosenpropertyidArr[$n]) {
                                    $matchcounter++;
                                    break;
                                }                                    
                            }                                
                        }
                    }
                    if($matchcounter === count($chosenpropertyidArr)) {
                        $finalresult[] = $result[$j];
                    }
                }*/
                header("Content-Type: application/json");
                echo json_encode($result);    
                exit();
            } else {
                $result = array();
                header("Content-Type: application/json");
                echo json_encode($result);    
                exit();    
            }
        }
    }
    $result = array();
    header("Content-Type: application/json");
    echo json_encode($result);
    exit();    
}

function dragonecommercereservezyx987_addupdateProductPropertyValues() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_addProductPropertyvalues') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_product_propertyvalue';                
        $table_name2 = 'wp_dragonecommercereservezyx987_propertyvalue';
        
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $productid = intval(sanitize_text_field($_POST['dragonecommercereservezyx987_addproductpropertyvaluesproduct']));                
            $propertyvaluesArr = array();
            $originalpropertyvaluesArr = array();
            $lastrowpropertyid = intval(sanitize_text_field($_POST['dragonecommercereservezyx987_addproductpropertyvaluesproduct_lastrowpropertyid']));    
            $lastrowpropertyid_allpropertyvalues = array();
            $lastrowpropertyid_checkedpropertyvalues = $_POST['dragonecommercereservezyx987_addproductpropertyvalues_lastpropertyvalue'];
            if($lastrowpropertyid_checkedpropertyvalues === null || intval($lastrowpropertyid_checkedpropertyvalues) <= 0){
                $dragon_ecommerce_dbResult .= 'The last property value is empty. Not saved. ';
                return;                
            }
            if(!empty($_POST['dragonecommercereservezyx987_addproductpropertyvalues_propertyvalue'])) {
                foreach($_POST['dragonecommercereservezyx987_addproductpropertyvalues_propertyvalue'] as $value){
                    if(intval(sanitize_text_field($value)) > 0) {
                        $propertyvaluesArr[] = intval(sanitize_text_field($value));
                        $originalpropertyvaluesArr[] = intval(sanitize_text_field($value));
                    }
                }
            }

            //first, get last row property's all property values - some are unchecked by admin, we need to remove it from db                
            $query = "SELECT id from $table_name2 WHERE propertyid = ?";  

            $stmt = $wpdb->dbh->prepare($query);
            $types = '';
            $parameterArray = array('');
                
            $types .= 'i';
            $parameterArray[] = &$lastrowpropertyid;                                
            
            $parameterArray[0] = $types;
            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);    
            $stmt->execute();
            $myresult = $stmt->get_result();
            $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
                        
            if($myresult === FALSE) {
                $dragon_ecommerce_dbResult .= 'Error reading from table ' . $table_name2 . ". ";
                return;
            } elseif(count($result) > 0){                                            
                for($j=0; $j<count($result); $j++) {
                    $lastrowpropertyid_allpropertyvalues[] = strval($result[$j]["id"]);
                }
            }
                                            
            foreach($lastrowpropertyid_allpropertyvalues as $value){
                $temp_value = intval(sanitize_text_field($value));
                if($temp_value > 0) {
                    $propertyvaluesArr = $originalpropertyvaluesArr;
                    $propertyvaluesArr[] = $temp_value;
                    sort($propertyvaluesArr);
                    $propertyvaluesString = join("|",$propertyvaluesArr);
                    if($productid <= 0 || $propertyvaluesString === '') {$dragon_ecommerce_dbResult .= "Create a product's property value: product and property values are required. Not saved. ";return;}        
                   
                    //second, delete that product's propertyvalueids from the table
                    $query = "DELETE from $table_name WHERE productid = ? and propertyvalueids = ?";  

                    $stmt = $wpdb->dbh->prepare($query);
                    $types = '';
                    $parameterArray = array('');
                    
                    $types .= 'i';
                    $parameterArray[] = &$productid;

                    $types .= 's';
                    $temp_id = $propertyvaluesString;
                    $parameterArray[] = &$temp_id;                                
                    
                    $parameterArray[0] = $types;
                    call_user_func_array(array($stmt, 'bind_param'), $parameterArray);    
                    $result =$stmt->execute();
                    $stmt->close();
                    
                    if($result === FALSE) {
                        $dragon_ecommerce_dbResult .= 'Error deleting from table ' . $table_name . ". ";
                        return;
                    } elseif(in_array($value, $lastrowpropertyid_checkedpropertyvalues)){
                        //3rd step - property values are not in the table, insert into the table
                        for($i=0; $i<count($propertyvaluesArr); $i++) {    
                            $query = "INSERT INTO $table_name (productid,propertyvalueids,propertyvalueid,createtimeutc) values (?,?,?,UTC_TIMESTAMP())";
                            
                            $stmt = $wpdb->dbh->prepare($query);
                            $errorstatus = false;
                            if($stmt === FALSE) {
                                $errorstatus = true;
                            }
                            $types = '';
                            $parameterArray = array('');
                            
                            $types .= 'i';
                            $parameterArray[] = &$productid;

                            $types .= 's';
                            $temp_id = $propertyvaluesString;
                            $parameterArray[] = &$temp_id;
                                                
                            $types .= 'i';
                            $parameterArray[] = &$propertyvaluesArr[$i];
                                                                                                                                
                            $parameterArray[0] = $types;
                            call_user_func_array(array($stmt, 'bind_param'), $parameterArray);    
                            $myresult = $stmt->execute();
                            if($myresult === FALSE) {
                                $errorstatus = true;
                            }
                            $stmt->close();        
                            
                            if($errorstatus === true) {
                                $dragon_ecommerce_dbResult .= 'Error inserting into table ' . $table_name . ". propertyvaluesString: " . $propertyvaluesString;
                                return;
                            } 
                        }                                        
                    }    
                }
            }
        } else {
            $dragon_ecommerce_dbResult .= "Mysqli is not supported. ";    
        }
        if($dragon_ecommerce_dbResult === '') {$dragon_ecommerce_dbResult .= 'Success.';}
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }    
}

function dragonecommercereservezyx987_cloneProductPropertyValues() {
    global $dragon_ecommerce_dbResult;
    $mynonce = empty($_POST['dragonecommercereservezyx987_hidden_security']) ? '' : sanitize_text_field($_POST['dragonecommercereservezyx987_hidden_security']);
    $mynonce = strip_tags($mynonce);
    if(wp_verify_nonce($mynonce, 'dragonecommercereservezyx987_updateProductPropertyvalues') !== 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['dragonecommercereservezyx987_hidden'])) && $_POST['dragonecommercereservezyx987_hidden'] === 'Y') {    
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $table_name = 'wp_dragonecommercereservezyx987_product_propertyvalue';                        
        if($wpdb->use_mysqli) {
            if($wpdb->dbh->connect_error) {
                die("Connection failed: " . esc_html($wpdb->dbh->connect_error));
            }
            $fromproductid = intval(sanitize_text_field($_POST['dragonecommercereservezyx987_updateproductpropertyvaluesproductfrom']));
            if($fromproductid <= 0) {$dragon_ecommerce_dbResult .= "Clone a product's property value: from product is required. Not saved. ";return;}        

            foreach($_POST['dragonecommercereservezyx987_updateproductpropertyvaluesproductto'] as $value){
                if(intval(sanitize_text_field($value)) > 0) {
                    $toproductid = intval(sanitize_text_field($value));
                    if($toproductid <= 0) {$dragon_ecommerce_dbResult .= "Clone a product's property value: to products are required. Not saved. ";return;}        
                    if($fromproductid === $toproductid) {continue;}
                    
                    //first, check if that from product has rows in the table
                    $query = "SELECT propertyvalueids from $table_name WHERE productid = ?";  

                    $stmt = $wpdb->dbh->prepare($query);
                    $types = '';
                    $parameterArray = array('');
                    
                    $types .= 'i';
                    $parameterArray[] = &$fromproductid;                                
                    
                    $parameterArray[0] = $types;
                    call_user_func_array(array($stmt, 'bind_param'), $parameterArray);    
                    $stmt->execute();
                    $myresult = $stmt->get_result();
                    $result = $myresult === FALSE ? array() : $myresult->fetch_all(MYSQLI_ASSOC);
                    $stmt->close();                    
                    
                    if($myresult === FALSE) {
                        $dragon_ecommerce_dbResult .= 'Error reading from table ' . $table_name . ". ";
                        return;
                    } elseif(count($result) > 0){
                        //2nd step - remove to products rows from table - do we need to do step 1 first?
                        $query = "DELETE FROM $table_name WHERE productid = ?";  

                        $stmt = $wpdb->dbh->prepare($query);
                        $errorstatus = false;
                        if($stmt === FALSE) {
                            $errorstatus = true;
                        }                        
                        
                        $types = '';
                        $parameterArray = array('');
                        
                        $types .= 'i';
                        $parameterArray[] = &$toproductid;                                
                        
                        $parameterArray[0] = $types;
                        call_user_func_array(array($stmt, 'bind_param'), $parameterArray);    
                        $myresult = $stmt->execute();
                        if($myresult === FALSE) {
                            $errorstatus = true;
                        }
                        $stmt->close();                                    
                        if($errorstatus === true) {
                            $dragon_ecommerce_dbResult .= 'Error deleting from table ' . $table_name . ". ";
                            return;
                        } 
                                                                                                        
                        //3rd step, insert into table
                        $query = "INSERT INTO $table_name (productid,propertyvalueids,";
                        $query .= "propertyvalueid,createtimeutc) SELECT ?,propertyvalueids,";
                        $query .= "propertyvalueid,UTC_TIMESTAMP() FROM $table_name WHERE productid = ?";  

                        $stmt = $wpdb->dbh->prepare($query);
                        $errorstatus = false;
                        if($stmt === FALSE) {
                            $errorstatus = true;
                        }
                        $types = '';
                        $parameterArray = array('');
                        
                        $types .= 'i';
                        $parameterArray[] = &$toproductid;

                        $types .= 'i';
                        $parameterArray[] = &$fromproductid;
                        
                        $parameterArray[0] = $types;
                        call_user_func_array(array($stmt, 'bind_param'), $parameterArray);    
                        $myresult = $stmt->execute();
                        if($myresult === FALSE) {
                            $errorstatus = true;
                        }
                        $stmt->close();                                    
                        if($errorstatus === true) {
                            $dragon_ecommerce_dbResult .= 'Error inserting into table ' . $table_name . ". ";
                            return;
                        }   
                    }    
                }
            }
        } else {
            $dragon_ecommerce_dbResult .= "Mysqli is not supported. ";return;    
        }
        if($dragon_ecommerce_dbResult === '') {$dragon_ecommerce_dbResult .= 'Success.';}
    } else {
        $dragon_ecommerce_dbResult .= 'Invalid data.';
    }    
}

function dragonecommercereservezyx987_saveToLogTable($message, $processname  = '', $type = 'info', $userid = null) {
    global $wpdb;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    
    if($wpdb->use_mysqli) {
        if($wpdb->dbh->connect_error) {
          echo "Connection failed: " . esc_html($wpdb->dbh->connect_error);
          exit();
        }
        $table_name = 'wp_dragonecommercereservezyx987_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 dragonecommercereservezyx987_getAllLogtypesProcessnamesUserids($onlyActive = true) {
    global $wpdb; global $dragon_ecommerce_dbResult; $results = array();;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');            
    $table_name = 'wp_dragonecommercereservezyx987_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;    
}
?>