<?php
/**
 * @link       https://rentopian.com
 * @since      1.0.0
 *
 * @package    rentopian-sync
 */

global $rental_api_url, $rental_tables;
// rentopian api url
$rental_api_url = 'https://account.rentopian.com/api/v1';
// $rental_api_url = 'https://staging2-proxy.rentopian.com/api/v1'; // to test Sync / Webhooks with staging2.rentopian.com
// $rental_api_url = 'http://host.docker.internal/api/v1';
// $rental_api_url = 'https://debug2-proxy.rentopian.com/api/v1'; // to test Sync / Webhooks with debug2.rentopian.com


// tables names
$rental_tables = [
    "error_log" => "rental_error_log",
    "product_relations" => "rental_product_relations",
    "variant_relations" => "rental_variant_relations",
    "set_relations" => "rental_set_relations",
    "category_relations" => "rental_category_relations",
    "tag_relations" => "rental_tag_relations",
    "sets_tag_relations" => "rental_sets_tag_relations",
    "attribute_relations" => "rental_attribute_relations",
    "brand_relations" => "rental_brand_relations",
    "image_relations" => "rental_image_relations",
    "order_relations" => "rental_order_relations",
    "day_tiers" => "rental_day_tiers",
    "shipping_zone_relations" => "rental_shipping_zone_relations",
    "coupon_relations" => "rental_coupon_relations",
    "price_multipliers" => "rental_price_multipliers",
    "product_options" => "rental_product_options",
    "product_option_relations" => "rental_product_option_relations",
    "inventory_blocks" => "rental_inventory_blocks",
    "inventory_block_relations" => "rental_inventory_block_relations",
    "lead_relations" => "rental_lead_relations",
    "set_options" => "rental_set_options",
    "set_option_relations" => "rental_set_option_relations",
];

const RELATION_LOGISTICS_CLIENT_PICK_UP_CLIENT_RETURN = 1;
const RELATION_LOGISTICS_CLIENT_PICK_UP_COMPANY_RETURN = 2;
const RELATION_LOGISTICS_COMPANY_PICK_UP_CLIENT_RETURN = 3;
const RELATION_LOGISTICS_COMPANY_PICK_UP_COMPANY_RETURN = 4;

// create all necessary tables
function rental_create_tables() {
    global $wpdb, $rental_tables;
    $rental_error_log = $wpdb->prefix . $rental_tables["error_log"];
    $rental_product_relations = $wpdb->prefix . $rental_tables["product_relations"];
    $rental_variant_relations = $wpdb->prefix . $rental_tables["variant_relations"];
    $rental_set_relations = $wpdb->prefix . $rental_tables["set_relations"];
    $rental_category_relations = $wpdb->prefix . $rental_tables["category_relations"];
    $rental_tag_relations = $wpdb->prefix . $rental_tables["tag_relations"];
    $rental_sets_tag_relations = $wpdb->prefix . $rental_tables["sets_tag_relations"];
    $rental_attribute_relations = $wpdb->prefix . $rental_tables["attribute_relations"];
    $rental_brand_relations = $wpdb->prefix . $rental_tables["brand_relations"];
    $rental_image_relations = $wpdb->prefix . $rental_tables["image_relations"];
    $rental_order_relations = $wpdb->prefix . $rental_tables["order_relations"];
    $rental_day_tiers = $wpdb->prefix . $rental_tables["day_tiers"];
    $rental_shipping_zone_relations = $wpdb->prefix . $rental_tables["shipping_zone_relations"];
    $rental_coupon_relations = $wpdb->prefix . $rental_tables["coupon_relations"];
    $rental_price_multipliers = $wpdb->prefix . $rental_tables["price_multipliers"];
    $rental_product_options = $wpdb->prefix . $rental_tables["product_options"];
    $rental_product_option_relations = $wpdb->prefix . $rental_tables["product_option_relations"];
    $rental_inventory_blocks = $wpdb->prefix . $rental_tables["inventory_blocks"];
    $rental_inventory_block_relations = $wpdb->prefix . $rental_tables["inventory_block_relations"];
    $rental_lead_relations = $wpdb->prefix . $rental_tables["lead_relations"];
    $rental_set_options = $wpdb->prefix . $rental_tables["set_options"];
    $rental_set_option_relations = $wpdb->prefix . $rental_tables["set_option_relations"];

    $sql = "";
    if ($wpdb->get_var("show tables like '$rental_error_log'") != $rental_error_log) {
        $sql .= "CREATE TABLE $rental_error_log (
          id BIGINT(11) NOT NULL AUTO_INCREMENT,
          status VARCHAR(255) NOT NULL,
          url VARCHAR(255),
          file VARCHAR(255),
          line VARCHAR(255),
          message TEXT,
          type SMALLINT,
          sync_time BIGINT(20),
          register_time BIGINT(20),
          data LONGTEXT,
          PRIMARY KEY id (id)
        );";
    }
    if ($wpdb->get_var("show tables like '$rental_product_relations'") != $rental_product_relations) {
        $sql .= "CREATE TABLE $rental_product_relations (
          id bigint(11) NOT NULL,
          rental_id bigint(11) NOT NULL,
          rental_division_id bigint(11) NOT NULL,
          UNIQUE KEY id (id)
        );";
    } elseif ($wpdb->get_var("SHOW COLUMNS FROM `$rental_product_relations` WHERE Field = 'rental_division_id'") != 'rental_division_id') {
        $wpdb->query("ALTER TABLE `$rental_product_relations` ADD COLUMN rental_division_id bigint(11) NOT NULL");
    }
    if ($wpdb->get_var("show tables like '$rental_variant_relations'") != $rental_variant_relations) {
        $sql .= "CREATE TABLE $rental_variant_relations (
          id bigint(11) NOT NULL,
          rental_id bigint(11) NOT NULL,
          rental_division_id bigint(11) NOT NULL,
          UNIQUE KEY id (id)
        );";
    } elseif ($wpdb->get_var("SHOW COLUMNS FROM `$rental_variant_relations` WHERE Field = 'rental_division_id'") != 'rental_division_id') {
        $wpdb->query("ALTER TABLE `$rental_variant_relations` ADD COLUMN rental_division_id bigint(11) NOT NULL");
    }
    if ($wpdb->get_var("show tables like '$rental_set_relations'") != $rental_set_relations) {
        $sql .= "CREATE TABLE $rental_set_relations (
          id bigint(11) NOT NULL,
          rental_id bigint(11) NOT NULL,
          rental_division_id bigint(11) NOT NULL,
          UNIQUE KEY id (id)
        );";
    } elseif ($wpdb->get_var("SHOW COLUMNS FROM `$rental_set_relations` WHERE Field = 'rental_division_id'") != 'rental_division_id') {
        $wpdb->query("ALTER TABLE `$rental_set_relations` ADD COLUMN rental_division_id bigint(11) NOT NULL");
    }
    if ($wpdb->get_var("show tables like '$rental_category_relations'") != $rental_category_relations) {
        $sql .= "CREATE TABLE $rental_category_relations (
          id bigint(11) NOT NULL,
          rental_id bigint(11) NOT NULL,
          UNIQUE KEY id (id)
        );";
    }
    if ($wpdb->get_var("show tables like '$rental_tag_relations'") != $rental_tag_relations) {
        $sql .= "CREATE TABLE $rental_tag_relations (
          id bigint(11) NOT NULL,
          rental_id bigint(11) NOT NULL,
          UNIQUE KEY id (id)
        );";
    }
    
    if ($wpdb->get_var("show tables like '$rental_sets_tag_relations'") != $rental_sets_tag_relations) {
        $sql .= "CREATE TABLE $rental_sets_tag_relations (
          id bigint(11) NOT NULL,
          rental_id bigint(11) NOT NULL,
          UNIQUE KEY id (id)
        );";
    }

    if ($wpdb->get_var("show tables like '$rental_attribute_relations'") != $rental_attribute_relations) {
        $sql .= "CREATE TABLE $rental_attribute_relations (
          id bigint(11) NOT NULL,
          rental_id bigint(11) NOT NULL,
          UNIQUE KEY id (id)
        );";
    }
    if ($wpdb->get_var("show tables like '$rental_brand_relations'") != $rental_brand_relations) {
        $sql .= "CREATE TABLE $rental_brand_relations (
          id bigint(11) NOT NULL,
          rental_id bigint(11) NOT NULL,
          UNIQUE KEY id (id)
        );";
    }
    if ($wpdb->get_var("show tables like '$rental_image_relations'") != $rental_image_relations) {
        $sql .= "CREATE TABLE $rental_image_relations (
          id bigint(11) NOT NULL,
          rental_id bigint(11) NOT NULL,
          UNIQUE KEY id (id)
        );";
    }
    if ($wpdb->get_var("show tables like '$rental_order_relations'") != $rental_order_relations) {
        $sql .= "CREATE TABLE $rental_order_relations (
          id BIGINT(11) NOT NULL,
          rental_id BIGINT(11) NOT NULL,
          http_code SMALLINT(255),
          message TEXT,
          data LONGTEXT,
          register_time BIGINT(20),
          version VARCHAR(255),
          UNIQUE KEY id (id)
        );";
    } else {
        $columns = [];
        foreach ($wpdb->get_results("SHOW COLUMNS FROM `$rental_order_relations`") as $column) {
            $columns[] = $column->Field;
        }
        $add_columns_sql = "";
        if ( !in_array("http_code", $columns)) {
            $add_columns_sql = "ADD COLUMN http_code SMALLINT(255)";
        }
        if ( !in_array("message", $columns)) {
            $add_columns_sql .= ($add_columns_sql? ", ": "") . "ADD COLUMN message TEXT";
        }
        if ( !in_array("data", $columns)) {
            $add_columns_sql .= ($add_columns_sql? ", ": "") . "ADD COLUMN data LONGTEXT";
        }
        if ( !in_array("register_time", $columns)) {
            $add_columns_sql .= ($add_columns_sql? ", ": "") . "ADD COLUMN register_time BIGINT(20)";
        }
        if ( !in_array("version", $columns)) {
            $add_columns_sql .= ($add_columns_sql? ", ": "") . "ADD COLUMN version VARCHAR(255)";
        }
        if ($add_columns_sql) {
            $wpdb->query("ALTER TABLE `$rental_order_relations` $add_columns_sql");
        }
    }
    if ($wpdb->get_var("show tables like '$rental_day_tiers'") != $rental_day_tiers) {
        $sql .= "CREATE TABLE $rental_day_tiers (
          id BIGINT(11) NOT NULL AUTO_INCREMENT,
          min INT NOT NULL,
          max INT NOT NULL,
          day INT NOT NULL,
          PRIMARY KEY id (id)
        );";
    }
    // create shipping_zone_relations table
    if ($wpdb->get_var("show tables like '$rental_shipping_zone_relations'") != $rental_shipping_zone_relations) {
        $sql .= "CREATE TABLE $rental_shipping_zone_relations (
            id bigint(11) NOT NULL,
            rental_id bigint(11) NOT NULL,
            rental_division_id bigint(11) NOT NULL,
            UNIQUE KEY id (id)
        );";
    }
    // create rental_coupon_relations table
    if ($wpdb->get_var("show tables like '$rental_coupon_relations'") != $rental_coupon_relations) {
        $sql .= "CREATE TABLE $rental_coupon_relations (
            id BIGINT(11) NOT NULL,
            rental_id BIGINT(11) NOT NULL,
            rental_coupon_divisions TEXT COLLATE utf8_unicode_ci NULL DEFAULT NULL,
            UNIQUE KEY id (id)
        );";
    }

    // create rental_price_multipliers table
    if ($wpdb->get_var("show tables like '$rental_price_multipliers'") != $rental_price_multipliers) {
        $sql .= "CREATE TABLE $rental_price_multipliers (
            id BIGINT(11) NOT NULL,
            title VARCHAR(255),
            slug VARCHAR(255),
            is_monthly TINYINT(1) DEFAULT 0,
            is_repeat TINYINT(1) DEFAULT 0,
            items LONGTEXT COLLATE utf8_unicode_ci,
            UNIQUE KEY id (id)
        );";
    } else {
        $columns = [];
        foreach ($wpdb->get_results("SHOW COLUMNS FROM `$rental_price_multipliers`") as $column) {
            $columns[] = $column->Field;
        }
        $add_columns_sql = "";
        if ( !in_array("is_monthly", $columns)) {
            $add_columns_sql = "ADD COLUMN is_monthly TINYINT(1) DEFAULT 0";
        }
        if ( !in_array("is_repeat", $columns)) {
            $add_columns_sql .= ($add_columns_sql? ", ": "") . "ADD COLUMN is_repeat TINYINT(1) DEFAULT 0";
        }
        if ($add_columns_sql) {
            $wpdb->query("ALTER TABLE `$rental_price_multipliers` $add_columns_sql");
        }
    }

    // create rental_product_options table
    if ($wpdb->get_var("show tables like '$rental_product_options'") != $rental_product_options) {
        $sql .= "CREATE TABLE $rental_product_options (
            id BIGINT(11) NOT NULL,
            title VARCHAR(255),
            once_per_order TINYINT(1) DEFAULT 0,
            option_values LONGTEXT COLLATE utf8_unicode_ci,
            UNIQUE KEY id (id)
        );";
    } else {
        $columns = [];
        foreach ($wpdb->get_results("SHOW COLUMNS FROM `$rental_product_options`") as $column) {
            $columns[] = $column->Field;
        }
        $add_columns_sql = "";
        if ( !in_array("once_per_order", $columns)) {
            $add_columns_sql = "ADD COLUMN once_per_order TINYINT(1) DEFAULT 0";
        }
        if ($add_columns_sql) {
            $wpdb->query("ALTER TABLE `$rental_product_options` $add_columns_sql");
        }
    }

    // create rental_product_option_relations table
    // wp_id : product id or category id
    // type : 1:product, 2:category
    if ($wpdb->get_var("show tables like '$rental_product_option_relations'") != $rental_product_option_relations) {
        $sql .= "CREATE TABLE $rental_product_option_relations (
            po_id BIGINT(11) NOT NULL,
            rental_id BIGINT(11) NOT NULL,
            wp_id BIGINT(11) NOT NULL, 
            type TINYINT(1),
            CONSTRAINT rental_unique_cols UNIQUE (po_id , rental_id, wp_id, type)
        );";
    } 
    // create rental_inventory_blocks table
    // type : 1 = all items, 2 = specific items 
    if ($wpdb->get_var("show tables like '$rental_inventory_blocks'") != $rental_inventory_blocks) {
        $sql .= "CREATE TABLE $rental_inventory_blocks (
            id BIGINT(11) NOT NULL,
            division_id INT(11) NOT NULL,
            `start_date` BIGINT(11) NOT NULL,
            `end_date` BIGINT(11) NOT NULL,
            `type` TINYINT(1),
            UNIQUE KEY id (id)
        );";
    } 
    // create rental_inventory_block_relations table
    // id : product_id/product_variant_id
    if ($wpdb->get_var("show tables like '$rental_inventory_block_relations'") != $rental_inventory_block_relations) {
        $sql .= "CREATE TABLE $rental_inventory_block_relations (
            block_id BIGINT(11) NOT NULL,
            rental_id BIGINT(11) NOT NULL,
            id BIGINT(11) NOT NULL, 
            CONSTRAINT rental_unique_cols UNIQUE (id , rental_id, block_id)
        );";
    } 
    // create rental_lead_relations table
    if ($wpdb->get_var("show tables like '$rental_lead_relations'") != $rental_lead_relations) {
        $sql .= "CREATE TABLE $rental_lead_relations (
            id BIGINT(11) NOT NULL AUTO_INCREMENT,
            rental_id BIGINT(11) NOT NULL,
            http_code SMALLINT(255),
            message TEXT,
            data LONGTEXT,
            register_time BIGINT(20),
            version VARCHAR(255),
            PRIMARY KEY id (id)
        );";
    }

    if ($wpdb->get_var("show tables like '$rental_set_options'") != $rental_set_options) {
        $sql .= "CREATE TABLE $rental_set_options (
            id BIGINT(11) NOT NULL,
            title VARCHAR(255),
            once_per_order TINYINT(1) DEFAULT 0,
            option_values LONGTEXT COLLATE utf8_unicode_ci,
            UNIQUE KEY id (id)
        );";
    }
    if ($wpdb->get_var("show tables like '$rental_set_option_relations'") != $rental_set_option_relations) {
        $sql .= "CREATE TABLE $rental_set_option_relations (
            set_option_id BIGINT(11) NOT NULL,
            rental_id BIGINT(11) NOT NULL,
            wp_id BIGINT(11) NOT NULL, 
            CONSTRAINT rental_unique_cols UNIQUE (set_option_id , rental_id, wp_id)
        );";
    }



    if ($sql) {
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }

    if (get_option('rental_synchronize_status')) {
        try {
            $api_key = get_option('rental_api_key');
            // set plugin path
            rental_curl('settings/plugin_path/update', $api_key, false, [
                'plugin_path' => substr(RENTOPIAN_SYNC_PATH, strlen(ABSPATH))
            ]);
            // sync company divisions
            rental_sync_divisions($api_key);
        } catch (RentalException $e) {}
    }
}

// remove all necessary tables
function rental_remove_tables() {
    global $wpdb, $rental_tables;
    $rental_error_log = $wpdb->prefix . $rental_tables["error_log"];
    $rental_product_relations = $wpdb->prefix . $rental_tables["product_relations"];
    $rental_variant_relations = $wpdb->prefix . $rental_tables["variant_relations"];
    $rental_set_relations = $wpdb->prefix . $rental_tables["set_relations"];
    $rental_category_relations = $wpdb->prefix . $rental_tables["category_relations"];
    $rental_tag_relations = $wpdb->prefix . $rental_tables["tag_relations"];
    $rental_sets_tag_relations = $wpdb->prefix . $rental_tables["sets_tag_relations"];
    $rental_attribute_relations = $wpdb->prefix . $rental_tables["attribute_relations"];
    $rental_brand_relations = $wpdb->prefix . $rental_tables["brand_relations"];
    $rental_image_relations = $wpdb->prefix . $rental_tables["image_relations"];
    $rental_order_relations = $wpdb->prefix . $rental_tables["order_relations"];
    $rental_day_tiers = $wpdb->prefix . $rental_tables["day_tiers"];
    $rental_shipping_zone_relations = $wpdb->prefix . $rental_tables["shipping_zone_relations"];
    $rental_coupon_relations = $wpdb->prefix . $rental_tables["coupon_relations"];
    $rental_price_multipliers = $wpdb->prefix . $rental_tables["price_multipliers"];
    $rental_product_options = $wpdb->prefix . $rental_tables["product_options"];
    $rental_product_option_relations = $wpdb->prefix . $rental_tables["product_option_relations"];
    $rental_inventory_blocks = $wpdb->prefix . $rental_tables["inventory_blocks"];
    $rental_inventory_block_relations = $wpdb->prefix . $rental_tables["inventory_block_relations"];
    $rental_lead_relations = $wpdb->prefix . $rental_tables["lead_relations"];

    delete_option("rental_api_key");
    delete_option("rental_synchronize_status");

    $wpdb->query("DROP TABLE IF EXISTS $rental_error_log, $rental_product_relations, $rental_variant_relations, ".
        "$rental_set_relations, $rental_category_relations, $rental_tag_relations, $rental_sets_tag_relations, $rental_attribute_relations, ".
        "$rental_brand_relations, $rental_image_relations, $rental_order_relations, $rental_day_tiers, $rental_shipping_zone_relations, ".
        "$rental_coupon_relations, $rental_price_multipliers, $rental_product_options, $rental_product_option_relations, ".
        "$rental_inventory_blocks, $rental_inventory_block_relations, $rental_lead_relations");
}

// default settings on plugin activation 
function set_default_settings() {
    if (false === get_option('rental_form_layout')) {
        update_option('rental_form_layout', 'horizontal');
    }
    if (false === get_option('rental_hide_product_type_label')) {
        update_option('rental_hide_product_type_label', 1);
    }
    if (false === get_option('rental_filter_unavailable_products')) {
        update_option('rental_filter_unavailable_products', 1);
    }

    update_option( 'woocommerce_enable_reviews', 'no' );

    $current_host = parse_url(home_url(), PHP_URL_HOST);
    $excluded_domains = ['lootrentals.com', 'boweryandbash.com'];

    // Check if the current host matches any of the excluded domains
    $exclude = false;
    foreach ($excluded_domains as $excluded_domain) {
        if (strpos($current_host, $excluded_domain) !== false) {
            $exclude = true;
            break;
        }
    }

    if (!$exclude) {
        update_option('woocommerce_stock_format', 'no_amount');
    }
    

    if (false === get_option('rental_encryption_key')) {
        update_option('rental_encryption_key', bin2hex(random_bytes(32)));
    }
}

function register_sale_products_template() {
    $page_slug = 'rntp-sale-products';

    if (get_page_by_path($page_slug) === null) {
        $page_id = wp_insert_post([
            'post_title'   => 'Sale Products',
            'post_name'    => $page_slug,
            'post_status'  => 'publish',
            'post_type'    => 'page',
            'post_content' => '',
        ]);

        if (!is_wp_error($page_id)) {
            update_post_meta($page_id, '_wp_page_template', 'rntp-sale-template.php');
        }
    }
}

// enqueue script and style
function rental_enqueue_scripts() {
    wp_enqueue_script('moment', plugins_url('/assets/vendor/calentim/build/vendor/moment.min.js', __FILE__), [], '2.17.1', true);
    wp_enqueue_script('calentim', plugins_url('/assets/vendor/calentim/build/js/calentim.min.js', __FILE__), ['jquery'], '2.0.8', true);
    wp_enqueue_style('calentim', plugins_url('/assets/vendor/calentim/build/css/calentim.min.css', __FILE__));
    wp_enqueue_style('dashicons');

    // if (is_product() || is_shop() || is_cart() || is_product_category() || is_product_tag()) {
    wp_enqueue_script('rental-script', plugins_url('/assets/js/rental-script.js', __FILE__), ['jquery'], RENTOPIAN_SYNC_VERSION, true);
    wp_enqueue_style('rental-style', plugins_url('/assets/css/rntp-styles.css', __FILE__), [], RENTOPIAN_SYNC_VERSION);
    wp_localize_script('rental-script', 'rentalObj', ['url' => admin_url('admin-ajax.php')]);

    if(get_option('rental_form_layout') === "in-cart"){
        wp_enqueue_script('rental-min-date-form-script', plugins_url('/assets/js/rental-min-date-form-script.js', RENTOPIAN_SYNC_PATH . '/functions.php'), ['jquery'], RENTOPIAN_SYNC_VERSION, true );
        wp_enqueue_style('rental-min-date-form-style', plugins_url('/assets/css/rental-min-date-form-style.css', RENTOPIAN_SYNC_PATH . '/functions.php'), [], RENTOPIAN_SYNC_VERSION);
    }

    if (get_option('rental_synchronized_product_type') == "hourly") {
        wp_enqueue_script('rental-hourly-product-script', plugins_url('/assets/js/rental-hourly-product-script.js', __FILE__), ['jquery'], RENTOPIAN_SYNC_VERSION, true);
        wp_localize_script('rental-hourly-product-script', 'rentalObj', ['url' => admin_url('admin-ajax.php')]);
    }
    
    wp_enqueue_script('rental-product-options-script', plugins_url('/assets/js/rental-product-options-script.js', __FILE__), ['jquery'], RENTOPIAN_SYNC_VERSION, true);
    wp_localize_script('rental-product-options-script', 'rentalObj', ['url' => admin_url('admin-ajax.php')]);
    
    // if (is_cart() || is_checkout()) {
    //     wp_enqueue_script('rental-coupon-script', plugins_url('/assets/js/rental-coupon-script.js', __FILE__), ['jquery'], null, true);
    //     wp_localize_script('rental-coupon-script', 'rentalObj', ['url' => admin_url('admin-ajax.php')]);
    // }

    if (is_product()) {
        wp_enqueue_script('rental-add-ons-script', plugins_url('/assets/js/rental-add-ons-script.js', __FILE__), ['jquery'], RENTOPIAN_SYNC_VERSION, true);
        wp_enqueue_script('rental-multiplier-script', plugins_url('/assets/js/rental-multiplier-script.js', __FILE__), ['jquery'], RENTOPIAN_SYNC_VERSION, true);
        wp_localize_script('rental-multiplier-script', 'rentalObj', ['url' => admin_url('admin-ajax.php'),]);
       
        if (get_option('rental_filter_unavailable_products', 1)) {
            // check product availability
            wp_enqueue_script('rental-product-check-availability-script', plugins_url('/assets/js/rental-product-check-availability-script.js', __FILE__), ['jquery'], RENTOPIAN_SYNC_VERSION, true);
            wp_localize_script('rental-product-check-availability-script', 'rentalObj', ['url' => admin_url('admin-ajax.php')]);
        }

        wp_enqueue_script('rental-sets', plugins_url('/assets/js/rental-sets.js', __FILE__), ['jquery'], null, true);
        wp_localize_script('rental-sets', 'rentalObj', ['url' => admin_url('admin-ajax.php')]);
    }

    if (is_checkout() && !is_order_received_page()) {

        $decrypted_rental_zip = '';
        if (isset($_COOKIE['rental_zip'])) {
            $decrypted_rental_zip = decrypt_data($_COOKIE['rental_zip'], get_option('rental_encryption_key'));
        }

        wp_enqueue_script('rental-checkout-script', plugins_url('/assets/js/rental-checkout-script.js', __FILE__), ['jquery'], RENTOPIAN_SYNC_VERSION, true);
        wp_localize_script('rental-checkout-script', 'rentalObj', ['url' => admin_url('admin-ajax.php'), 'zip' => isset($_COOKIE['rental_zip']) && !get_option('rental_hide_zip')? $decrypted_rental_zip : '']);
    }

    if (is_order_received_page()) {

        wp_enqueue_script('rental-order-received-script', plugins_url('/assets/js/rental-order-received-script.js', __FILE__), ['jquery'], RENTOPIAN_SYNC_VERSION, true);
        wp_localize_script('rental-order-received-script', 'rentalObj', ['url' => admin_url('admin-ajax.php')]);
    }
    

    if (is_cart()) {
        wp_enqueue_script('rental-cart-script', plugins_url('/assets/js/rental-cart-script.js', __FILE__), ['jquery'], RENTOPIAN_SYNC_VERSION, true);
        wp_localize_script('rental-cart-script', 'rentalObj', ['url' => admin_url('admin-ajax.php')]);
    }

    wp_register_script('rental-divisions-modal-script', plugins_url('/assets/js/rental-divisions-modal-script.js', __FILE__), ['jquery'], RENTOPIAN_SYNC_VERSION, true);
    wp_register_style('rental-divisions-modal-style', plugins_url('/assets/css/rental-divisions-modal-style.css', __FILE__), [], RENTOPIAN_SYNC_VERSION);

    wp_register_script('rental-wishlist-form-script', plugins_url('/assets/js/rental-wishlist-form-script.js', __FILE__), ['jquery'], RENTOPIAN_SYNC_VERSION, true);
    wp_register_style('rental-wishlist-style', plugins_url('/assets/css/rental-wishlist-style.css', __FILE__), [], RENTOPIAN_SYNC_VERSION);
    wp_localize_script('rental-wishlist-form-script', 'rentalObj', ['url' => admin_url('admin-ajax.php')]);

    // load fly-cart.min.js in cart/checkout pages when Rentpro theme exists only
    if (class_exists('Rentpro_THA')) {
        if ( 
            (is_cart() 
            || is_checkout())
            && get_option('rental_form_layout') === "in-cart"
        ) {

            if ( !wp_script_is( 'rentpro-fly-cart', 'enqueued' ) ) {
                wp_register_script(
                    'rentpro-fly-cart',
                    get_template_directory_uri() . '/assets/js/woo/fly-cart.min.js',
                    array( 'jquery' ),
                    '2.0',
                    true
                );
                // Enqueue it everywhere on the front end
                wp_enqueue_script( 'rentpro-fly-cart' );
            }
        }
       
    }
  

    // load font-awesome css for Eventorian theme only
    if (defined('EVENTORIAN_THEME_DIR')) {
        wp_enqueue_style(
            'font-awesome-cdn',
            'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css',
            [],
            '4.7.0'
        );
    }
}

// enqueue script and style to admin page
function rental_enqueue_scripts_to_admin($hook) {

    $plugin_folder_name = basename(dirname(__FILE__));

    if (is_admin() && ($hook == 'toplevel_page_'.$plugin_folder_name.'/functions' || $hook == 'rentopian-sync_page_rentopian-settings'
            || $hook == 'rentopian-sync_page_rentopian-log')) {
        
        wp_enqueue_script('moment', plugins_url('/assets/vendor/calentim/build/vendor/moment.min.js', __FILE__), [], '2.17.1', true);
        wp_enqueue_script('calentim', plugins_url('/assets/vendor/calentim/build/js/calentim.min.js', __FILE__), ['jquery'], '2.0.8', true);
        wp_enqueue_style('calentim', plugins_url('/assets/vendor/calentim/build/css/calentim.min.css', __FILE__));

        wp_enqueue_script('rental-admin-script', plugins_url('/assets/js/rental-admin-script.js', __FILE__), ['jquery'], RENTOPIAN_SYNC_VERSION, true);
        wp_enqueue_style('rental-admin-style', plugins_url('/assets/css/rental-admin-style.css', __FILE__), [], RENTOPIAN_SYNC_VERSION);
        wp_localize_script('rental-admin-script', 'rentalObj', ['url' => admin_url('admin-ajax.php')]);
    }
}



// function ajax which is responsible for sync
function wp_ajax_rental_sync() {

    if (isset($_POST['api_key']) && $_POST['api_key']) {
        update_option('rental_api_key', $_POST['api_key']);
        update_option('rental_synchronize_status', 2);
        update_option('rental_api_key_is_valid', 0);
        // call rental_synchronization function
        $sync_time = time();
        update_option('rental_sync_time', $sync_time);

        try {
            if (rental_synchronization($_POST['api_key'])) {
                $data = ['start' => 0];
                ErrorHandler::registerErrorInLog( __('The import is now complete', 'rentopian-sync'), __FILE__, __LINE__, RentalException::TYPE_SYNC_GLOBAL, $sync_time, 200);
                wp_send_json($data, 200);
            }
        } catch (RentalException $e) {
            ErrorHandler::registerErrorInLog($e->getMessage(), $e->getFile(), $e->getLine(), $e->getType(), $sync_time, $e->getStatusCode());
            wp_send_json([
                'message' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ], $e->getStatusCode());
        }
    } else {
        $data = ["message" => __('The API key is required', 'rentopian-sync')];
        wp_send_json($data, 400);
    }
    wp_die();
}

// function ajax which is responsible for uploading images
function wp_ajax_rental_upload_images() {
    if (isset($_GET['start'])) {

        $rental_file_sync_method = get_option('rental_file_sync_method', 1);

        $start = intval($_GET['start']);

        if ($start === 0) {
            Rental_Timer::start_persistent();
        }
       
        if (get_option('rental_sync_files_manual', 0) == 1) {
            update_option('rental_sync_files_manual_index', 0);
            $data = ['start' => $start, 'percent' => 100, 'sync_files_manual' => 1];
            $data['message'] = __('Synchronization process of data completed successfully', 'rentopian-sync');
            wp_send_json($data, 200);
        }

        $rental_image_upload_completed = get_option('rental_image_upload_completed');
        if ($rental_image_upload_completed === false) {
            $rental_image_upload_completed = true;
            update_option('rental_image_upload_completed', $rental_image_upload_completed);
        }

        $rental_products_img_last_id = get_option('rental_products_img_last_id');
        if ( $rental_products_img_last_id === false) {
            $rental_products_img_last_id = 0;
            update_option('rental_products_img_last_id', $rental_products_img_last_id);
        }

        $rental_sync_time = get_option('rental_sync_time');

        $img_count = get_option('rental_products_img_count', 0);
        if ($img_count) {
            if ($rental_file_sync_method == 1) {
                $limit = 3;
            } else {
                $limit = 5;
            }

            $last_id = $rental_products_img_last_id;
            try {

                if ($rental_file_sync_method == 1) {
                    // base 64 method
                    rental_upload_images($last_id, $limit);
                } else {
                    // nginx method
                    rental_upload_images_stream($last_id, $limit);
                }

            } catch (RentalException $e) {

                $rental_image_upload_completed = false;
                update_option('rental_image_upload_completed', false);
                
                $data = serialize(['start' => $last_id, 'limit' => $limit]);
                ErrorHandler::registerErrorInLog($e->getMessage(), $e->getFile(), $e->getLine(), $e->getType(), $rental_sync_time !== false ? $rental_sync_time : null, $e->getStatusCode(), $data);
            }

            $start += $limit;
        }

        if ( !$img_count || $start >= $img_count) {
            $data = ['start' => 0];
            if ($rental_image_upload_completed) {
                update_option('rental_synchronize_status', 1);
                update_option('rental_api_key_is_valid', 1);
                $data['message'] = __('Synchronization process completed successfully', 'rentopian-sync');
                $data['completed'] = true;
                $message = __('The images import is now complete', 'rentopian-sync');

                // Stop the timer and get duration
                $duration = Rental_Timer::stop_persistent();
                update_option("rental_show_sync_duration",  $duration !== false ? $duration : '');
                $data['show_duration'] = $duration;

            } else {
                $data['message'] = __('Some images were not retrieved during synchronization. Please check the log and try to re-upload the listed images.', 'rentopian-sync');
                $data['completed'] = false;
                $message = __('Some images were not retrieved during synchronization', 'rentopian-sync');

                $data['show_duration'] = '';
            }

            ErrorHandler::registerErrorInLog($message, __FILE__, __LINE__, RentalException::TYPE_SYNC_GLOBAL, $rental_sync_time !== false ? $rental_sync_time : null, 200);
            
            delete_option('rental_image_upload_completed');
            delete_option('rental_products_img_count');
            delete_option('rental_products_img_last_id');
            delete_option('rental_img_category_rel');
            delete_option('rental_img_variant_rel');
            delete_option('rental_img_attribute_value_rel');
            delete_option('rental_img_brand_rel');
            delete_option('rental_sync_time');
            delete_option('rental_sync_start_time');
            delete_option('rental_show_sync_duration');

        } else {
            $percent = floor(($start / $img_count) * 100);
            $data = ['start' => $start, 'percent' => $percent];
        }

        wp_send_json($data, 200);
    }

    wp_die();
}

function wp_ajax_rental_upload_images_manual() {
    if (isset($_GET['start']) && get_option('rental_sync_files_manual', 0) == 1) {
        $start = intval($_GET['start']);

        $rental_image_upload_completed = get_option('rental_image_upload_completed');
        if ( $rental_image_upload_completed === false) {
            $rental_image_upload_completed = true;
            update_option('rental_image_upload_completed', $rental_image_upload_completed);
        }

        $rental_products_img_last_id = get_option('rental_products_img_last_id');
        if ( $rental_products_img_last_id === false) {
            $rental_products_img_last_id = 0;
            update_option('rental_products_img_last_id', $rental_products_img_last_id);
        }

        $rental_sync_time = get_option('rental_sync_time');

        $rental_products_img_count = get_option('rental_products_img_count');
        $img_count = $rental_products_img_count !== false ? $rental_products_img_count : get_option('rental_sync_files_count', 0);
        if ($img_count) {
            $limit = 20; // manual file transfer limit

            $last_id = $rental_products_img_last_id;
            try {

                rental_upload_images($last_id, $limit);

            } catch (RentalException $e) {

                $rental_image_upload_completed = false;
                update_option('rental_image_upload_completed', false);

                $data = serialize(['start' => $last_id, 'limit' => $limit]);
                ErrorHandler::registerErrorInLog($e->getMessage(), $e->getFile(), $e->getLine(), $e->getType(), $rental_sync_time !== false ? $rental_sync_time : null, $e->getStatusCode(), $data);
            }

            $start += $limit;
            update_option('rental_sync_files_manual_index', $start);
        }

        if ( !$img_count || $start >= $img_count) {

            update_option('rental_sync_files_manual_index', $img_count);
            $data = ['start' => 0];

            if ($rental_image_upload_completed) {

                update_option('rental_synchronize_status', 1);
                update_option('rental_api_key_is_valid', 1);
                $data['message'] = __('Synchronization process completed successfully', 'rentopian-sync');
                $data['completed'] = true;
                $message = __('The images import is now complete', 'rentopian-sync');
            } else {

                $data['message'] = __('Some images were not retrieved during synchronization. Please check the log and try to re-upload the listed images.', 'rentopian-sync');
                $data['completed'] = false;
                $message = __('Some images were not retrieved during synchronization', 'rentopian-sync');
            }

            ErrorHandler::registerErrorInLog($message, __FILE__, __LINE__, RentalException::TYPE_SYNC_GLOBAL, $rental_sync_time !== false ? $rental_sync_time : null, 200);
            
            delete_option('rental_image_upload_completed');
            delete_option('rental_products_img_count');
            delete_option('rental_products_img_last_id');
            delete_option('rental_img_category_rel');
            delete_option('rental_img_variant_rel');
            delete_option('rental_img_attribute_value_rel');
            delete_option('rental_img_brand_rel');
            delete_option('rental_sync_time');

        } else {

            $data = ['start' => $start, 'percent' => 100];
            $data['message'] = __('Files Synchronization process completed partially (Imported files: '.$start.' , Remaining files: '. abs($img_count - $start).'  )', 'rentopian-sync');
        }
        wp_send_json($data, 200);
    }
    wp_die();
}

function rental_upload_images(&$start, $limit) {
    set_time_limit(800);
    global $wpdb, $rental_tables;
    $rental_set_relations = $wpdb->prefix . $rental_tables["set_relations"];
    $rental_product_relations = $wpdb->prefix . $rental_tables["product_relations"];
    $rental_variant_relations = $wpdb->prefix . $rental_tables["variant_relations"];
    $rental_image_relations = $wpdb->prefix . $rental_tables["image_relations"];

    $uploaded = $wpdb->get_results("SELECT `rental_id`, `id` FROM $rental_image_relations WHERE `rental_id` > $start ORDER BY `rental_id` ASC LIMIT $limit", 'OBJECT_K');
    
    $images = rental_curl('files/images', get_option('rental_api_key'), true, [
        'start' => $start,
        'limit' => $limit,
        'uploaded_images' => json_encode($uploaded),
    ]);

    $set_image_gallery = [];
    $product_image_gallery = [];
    $variant_image_gallery = [];
    $image_relations_sql = [];
    foreach ($images as $image) {

        $start = $image->id;
        update_option('rental_products_img_last_id', $start);

        if ( !$image->img_content && !isset($uploaded[$image->id])) {
            if ($image->products) {
                $product_ids = json_decode(stripslashes($image->products));
                foreach ($product_ids as $id) {
                    $products = $wpdb->get_results("SELECT `id` FROM $rental_product_relations WHERE `rental_id` = $id");
                    foreach ($products as $product) {
                        if (get_post_meta($product->id, '_thumbnail_id', true) == $image->id) {
                            update_post_meta($product->id, '_thumbnail_id', '');
                        }
                    }
                }
            }
            continue;
        }

        if (isset($uploaded[$image->id])) {
            $attach_id = $uploaded[$image->id]->id;
        } else {
            // Temporarily bypass MIME type check.
            add_filter('wp_check_filetype_and_ext', 'rental_bypass_mime_check', 10, 4);

            $upload = wp_upload_bits($image->filename, null, base64_decode($image->img_content));

            // Remove our temporary bypass after upload.
            remove_filter('wp_check_filetype_and_ext', 'rental_bypass_mime_check', 10);

            // Check for upload errors
            // if ( !empty($upload['error']) ) {

            //     error_log("Upload error for file {$image->filename}: " . $upload['error']);
            //     continue; // Skip this image and continue with the next.
            // }

            // $wp_filetype = wp_check_filetype( basename( $upload['file'] ), null );

            $wp_upload_dir = wp_upload_dir();

            if (isset($upload['file'])) {

                $attachment = ['guid' => $wp_upload_dir['baseurl'] . '/' . _wp_relative_upload_path($upload['file']),
                    'post_mime_type' => $image->mime,
                    'post_title' => $image->label,
                    'post_content' => $image->description? $image->description: "",
                    'post_status' => 'inherit'];

                $attach_id = wp_insert_attachment($attachment, $upload['file'], 0);

                require_once(ABSPATH . 'wp-admin/includes/image.php');

                $attach_data = wp_generate_attachment_metadata($attach_id, $upload['file']);
                wp_update_attachment_metadata($attach_id, $attach_data);

                $image_relations_sql[] = "($attach_id, $image->id)";
            }
        }

        if ($image->products) {

	        $products = implode(",", json_decode(stripslashes($image->products)));
            $products = $wpdb->get_results("SELECT `id` FROM $rental_product_relations WHERE `rental_id` IN ($products)");

            foreach ($products as $product) {
                if (get_post_meta($product->id, '_thumbnail_id', true) == $image->id) {
                    update_post_meta($product->id, '_thumbnail_id', $attach_id);
                } else if (isset($product_image_gallery[$product->id])) {
                    $product_image_gallery[$product->id] .= ",$attach_id";
                } else {
                    $product_image_gallery[$product->id] = "$attach_id";
                }
            }
        }

        $rental_img_category_rel = get_option('rental_img_category_rel');
        if ($rental_img_category_rel !== false && isset($rental_img_category_rel[$image->id])) {
            foreach ($rental_img_category_rel[$image->id] as $cat_id) {
                update_term_meta($cat_id, 'thumbnail_id', $attach_id);
            }
        }

        $rental_banner_img_category_rel = get_option('rental_banner_img_category_rel');
        if ($rental_banner_img_category_rel !== false && isset($rental_banner_img_category_rel[$image->id])) {
            foreach ($rental_banner_img_category_rel[$image->id] as $cat_id) {
                update_term_meta($cat_id, 'banner_id', $attach_id);
            }
        }
        

        $variant_main_images = [];
        $rental_img_variant_rel = get_option('rental_img_variant_rel');
        if ($rental_img_variant_rel !== false && isset($rental_img_variant_rel[$image->id])) {
            foreach ($rental_img_variant_rel[$image->id] as $variant_id) {
                update_post_meta($variant_id, '_thumbnail_id', $attach_id);
	            $variant_main_images[$variant_id] = true;
            }
        }

        $rental_img_attribute_value_rel = get_option('rental_img_attribute_value_rel');
        if ($rental_img_attribute_value_rel !== false && isset($rental_img_attribute_value_rel[$image->id])) {
            foreach ($rental_img_attribute_value_rel[$image->id] as $attr_val_id) {
                if (defined('ZOO_CW_VERSION')) {
                    update_term_meta($attr_val_id, 'slctd_img', wp_get_attachment_image_url($attach_id));
                }
                if (defined('RENTPRO_SWATCHES_PATH')) {
                    update_term_meta($attr_val_id, 'sw_image', $attach_id);
                }
            }
        }

        $rental_img_brand_rel = get_option('rental_img_brand_rel');
        if ($rental_img_brand_rel !== false && isset($rental_img_brand_rel[$image->id])) {
            foreach ($rental_img_brand_rel[$image->id] as $brand_id) {
                update_term_meta($brand_id, 'thumbnail_id', $attach_id);
            }
        }

	    if ($image->variants) {
		    $variants = implode(",", json_decode(stripslashes($image->variants)));
		    $variants = $wpdb->get_results("SELECT `id` FROM $rental_variant_relations WHERE `rental_id` IN ($variants)");
		    foreach ($variants as $variant) {
			    if (isset($variant_main_images[$variant->id])) {
				    continue;
			    }
			    if (isset($variant_image_gallery[$variant->id])) {
				    $variant_image_gallery[$variant->id] .= ",$attach_id";
			    } else {
				    $variant_image_gallery[$variant->id] = "$attach_id";
			    }
		    }
	    }

        if ($image->sets) {
		    $sets = implode(",", json_decode(stripslashes($image->sets)));
		    $sets = $wpdb->get_results("SELECT `id` FROM $rental_set_relations WHERE `rental_id` IN ($sets)");
		    foreach ($sets as $set) {
			    if (isset($variant_main_images[$set->id])) {
				    continue;
			    }
			    if (isset($set_image_gallery[$set->id])) {
				    $set_image_gallery[$set->id] .= ",$attach_id";
			    } else {
				    $set_image_gallery[$set->id] = "$attach_id";
			    }
		    }
	    }
    }

    if ($image_relations_sql) {
        $image_relations_sql = implode(", ", $image_relations_sql);
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta("INSERT INTO `$rental_image_relations` (`id`, `rental_id`) VALUES $image_relations_sql;");
    }

    foreach ($product_image_gallery as $id => $images) {
        $gallery = get_post_meta($id, '_product_image_gallery', true);
        if ($gallery) {
	        $images = $gallery . ',' . $images;
        }
        update_post_meta($id, '_product_image_gallery', $images);
    }

	foreach ($variant_image_gallery as $id => $images) {
		$gallery = get_post_meta($id, 'zoo-cw-variation-gallery', true);
		if ($gallery) {
			$images = $gallery . ',' . $images;
		}
		update_post_meta($id, 'zoo-cw-variation-gallery', $images);
	}

    foreach ($set_image_gallery as $id => $images) {
		$gallery = get_post_meta($id, '_product_image_gallery', true);
		if ($gallery) {
			$images = $gallery . ',' . $images;
		}
		update_post_meta($id, '_product_image_gallery', $images);
	}

    if ($wpdb->last_error !== '') {
        throw new RentalException("SQL_ERROR: $wpdb->last_error (SQL: $wpdb->last_query)", RentalException::TYPE_SYNC_RUNTIME);
    }
}


function rental_upload_images_stream(&$start, $limit) {

    error_reporting(error_reporting() & ~E_WARNING);

    global $wpdb, $rental_tables;
    $rental_set_relations = $wpdb->prefix . $rental_tables["set_relations"];
    $rental_product_relations = $wpdb->prefix . $rental_tables["product_relations"];
    $rental_variant_relations = $wpdb->prefix . $rental_tables["variant_relations"];
    $rental_image_relations = $wpdb->prefix . $rental_tables["image_relations"];

    perf_point( "Starting upload stream");

    try {

        $images = rental_curl('files/images/stream', get_option('rental_api_key'), true, [
            'start' => $start,
            'limit' => $limit,
        ]);

        perf_point( "Got images meta from API server");

    } catch (RentalException $e) {

        ErrorHandler::registerErrorInLog(
            "API fetch failed: " . $e->getMessage(),
            __FILE__, __LINE__,
            RentalException::TYPE_SYNC_RUNTIME,   // preserve type
            null,
            $e->getStatusCode(),
            serialize(['start'=>$start, 'limit'=>$limit])
        );
        throw $e;
    }

    
    $set_image_gallery = [];
    $product_image_gallery = [];
    $variant_image_gallery = [];
    $image_relations_sql = [];
    foreach ($images as $image) {

        perf_point( "Handling an image with id of : ".$image->id);
        
        $start = $image->id;

        perf_point( "Starting dl ".$image->url);
        if ( ! function_exists('download_url') ) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
        }
        $tmp_file = download_url( $image->url );
        perf_point( "Ended dl");

        if (is_wp_error($tmp_file)) {

            ErrorHandler::registerErrorInLog(
                "Download failed for image {$image->id}: " . $tmp_file->get_error_message(),
                __FILE__, __LINE__,
                RentalException::TYPE_SYNC_RUNTIME
            );

            // Download failed; skip this image
            continue;
        }


        $upload = wp_upload_bits(basename($image->url), null, file_get_contents($tmp_file));
        perf_point( "Uploading with wp_upload_bits done");

        if ($upload['error']) {
            throw new Exception("Upload error: " . $upload['error']);

            ErrorHandler::registerErrorInLog(
                "Upload error: " . $upload['error'],
                __FILE__, __LINE__,
                RentalException::TYPE_SYNC_RUNTIME
            );
        }
        
        $wp_upload_dir = wp_upload_dir();
        if (isset($upload['file'])) {

            perf_point( "Inserting file attachment");

            $attachment = [
                'guid' => $wp_upload_dir['baseurl'] . '/' . _wp_relative_upload_path($upload['file']),
                'post_mime_type' => $image->mime,
                'post_title' => $image->label,
                'post_content' => $image->description? $image->description: "",
                'post_status' => 'inherit'
            ];


            $attach_id = wp_insert_attachment($attachment, $upload['file'], 0);
            perf_point( "wp_insert_attachment done");

            if (is_wp_error($attach_id)) {

                perf_point( "Attach error - continuing");

                ErrorHandler::registerErrorInLog(
                    "Sideload failed for image {$image->id}: " . $attach_id->get_error_message(),
                    __FILE__, __LINE__,
                    RentalException::TYPE_SYNC_RUNTIME
                );

                continue;
            }

            require_once(ABSPATH . 'wp-admin/includes/image.php');
    
            perf_point( "wp gen subsizes start");
            $szs = rental_make_image_subsizes( $upload['file'], $attach_id);
            perf_point( "wp gen subsizes end: ".var_export($szs,true));

            $image_relations_sql[] = "($attach_id, $image->id)";
        }


        update_option('rental_products_img_last_id', $start);
        

        if ($image->products) {

            $products = implode(",", _rental_parse_ids($image->products) );
            $products = $wpdb->get_results("SELECT `id` FROM $rental_product_relations WHERE `rental_id` IN ($products)");

	        foreach ($products as $product) {

                if (get_post_meta($product->id, '_thumbnail_id', true) == $image->id) {
                    
                    update_post_meta($product->id, '_thumbnail_id', $attach_id);

                } else if (isset($product_image_gallery[$product->id])) {
                    $product_image_gallery[$product->id] .= ",$attach_id";
                } else {
                    $product_image_gallery[$product->id] = "$attach_id";
                }
            }
        }

        $rental_img_category_rel = get_option('rental_img_category_rel');
        if ($rental_img_category_rel !== false && isset($rental_img_category_rel[$image->id])) {
            foreach ($rental_img_category_rel[$image->id] as $cat_id) {
                update_term_meta($cat_id, 'thumbnail_id', $attach_id);
            }
        }

        $rental_banner_img_category_rel = get_option('rental_banner_img_category_rel');
        if ($rental_banner_img_category_rel !== false && isset($rental_banner_img_category_rel[$image->id])) {
            foreach ($rental_banner_img_category_rel[$image->id] as $cat_id) {
                update_term_meta($cat_id, 'banner_id', $attach_id);
            }
        }
        

        $variant_main_images = [];
        $rental_img_variant_rel = get_option('rental_img_variant_rel');
        if ($rental_img_variant_rel !== false && isset($rental_img_variant_rel[$image->id])) {
            foreach ($rental_img_variant_rel[$image->id] as $variant_id) {
                update_post_meta($variant_id, '_thumbnail_id', $attach_id);
                $variant_main_images[$variant_id] = true;
            }
        }

        $rental_img_attribute_value_rel = get_option('rental_img_attribute_value_rel');
        if ($rental_img_attribute_value_rel !== false && isset($rental_img_attribute_value_rel[$image->id])) {
            foreach ($rental_img_attribute_value_rel[$image->id] as $attr_val_id) {
                if (defined('ZOO_CW_VERSION')) {
                    update_term_meta($attr_val_id, 'slctd_img', wp_get_attachment_image_url($attach_id));
                }
                if (defined('RENTPRO_SWATCHES_PATH')) {
                    update_term_meta($attr_val_id, 'sw_image', $attach_id);
                }
            }
        }

        $rental_img_brand_rel = get_option('rental_img_brand_rel');
        if ($rental_img_brand_rel !== false && isset($rental_img_brand_rel[$image->id])) {
            foreach ($rental_img_brand_rel[$image->id] as $brand_id) {
                update_term_meta($brand_id, 'thumbnail_id', $attach_id);
            }
        }

        if ($image->variants) {
            $variants = implode(",", _rental_parse_ids($image->variants) );
            $variants = $wpdb->get_results("SELECT `id` FROM $rental_variant_relations WHERE `rental_id` IN ($variants)");
            foreach ($variants as $variant) {
                if (isset($variant_main_images[$variant->id])) {
                continue;
                }
                if (isset($variant_image_gallery[$variant->id])) {
                $variant_image_gallery[$variant->id] .= ",$attach_id";
                } else {
                $variant_image_gallery[$variant->id] = "$attach_id";
                }
            }
        }

        if ($image->sets) {
            $sets = implode(",", _rental_parse_ids($image->sets) );
            $sets = $wpdb->get_results("SELECT `id` FROM $rental_set_relations WHERE `rental_id` IN ($sets)");
            foreach ($sets as $set) {
                if (isset($variant_main_images[$set->id])) {
                continue;
                }
                if (isset($set_image_gallery[$set->id])) {
                $set_image_gallery[$set->id] .= ",$attach_id";
                } else {
                $set_image_gallery[$set->id] = "$attach_id";
                }
            }
            }
        }

        perf_point( "before image relations");
        if ($image_relations_sql) {
            $image_relations_sql = implode(", ", $image_relations_sql);
            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

            dbDelta("INSERT INTO `$rental_image_relations` (`id`, `rental_id`) VALUES $image_relations_sql;");
            perf_point( "inserted rental image relations");
        }

    foreach ($product_image_gallery as $id => $images) {

        $gallery = get_post_meta($id, '_product_image_gallery', true);
        if ($gallery) {
            $images = $gallery . ',' . $images;
        }

        update_post_meta($id, '_product_image_gallery', $images);
    }

    foreach ($variant_image_gallery as $id => $images) {
        $gallery = get_post_meta($id, 'zoo-cw-variation-gallery', true);
        if ($gallery) {
            $images = $gallery . ',' . $images;
        }
        update_post_meta($id, 'zoo-cw-variation-gallery', $images);
    }

    foreach ($set_image_gallery as $id => $images) {

        $gallery = get_post_meta($id, '_product_image_gallery', true);
        if ($gallery) {
            $images = $gallery . ',' . $images;
        }
        
        update_post_meta($id, '_product_image_gallery', $images);
    }

    if ($wpdb->last_error !== '') {
        throw new RentalException("SQL_ERROR: $wpdb->last_error (SQL: $wpdb->last_query)", RentalException::TYPE_SYNC_RUNTIME);
    }
}


global $logfp;
global $lastmt;

function perf_point($name) {
    if (!defined('REN_PERF') || !REN_PERF) {
        return;
    }

    global $logfp, $lastmt;
    if(!$lastmt > 0.0) {
        $lastmt = microtime();
    }
    $mt = microtime();
    if(!$logfp) {
        $logfp = fopen(REN_PERF,'a+');
    }
    
    fwrite($logfp, number_format(floatval($mt)-floatval($lastmt),10)."s\t".$name."\n");
    fflush($logfp);
    $lastmt=$mt;
}

function rental_make_image_subsizes($file, $attachment_id) {

    $imagesize = wp_getimagesize( $file );

    $image_meta = array(
        'width'    => $imagesize[0],
        'height'   => $imagesize[1],
        'file'     => _wp_relative_upload_path( $file ),
        'filesize' => wp_filesize( $file ),
        'sizes'    => array(),
    );

	$new_sizes = wp_get_registered_image_subsizes();

	/**
	 * Filters the image sizes automatically generated when uploading an image.
	 *
	 * @since 2.9.0
	 * @since 4.4.0 Added the `$image_meta` argument.
	 * @since 5.3.0 Added the `$attachment_id` argument.
	 *
	 * @param array $new_sizes     Associative array of image sizes to be created.
	 * @param array $image_meta    The image meta data: width, height, file, sizes, etc.
	 * @param int   $attachment_id The attachment post ID for the image.
	 */
	perf_point("apply filters");

	$new_sizes = apply_filters( 'intermediate_image_sizes_advanced', $new_sizes, $image_meta, $attachment_id );

    // We can filter unnecessary sizes if we need
    //	$new_sizes = array_filter($new_sizes, function($k) {
//	    return strpos($k, 'woocommerce') === 0;
//	}, ARRAY_FILTER_USE_KEY);

	$image_meta = resizeImageMultiple( $file, $new_sizes, $image_meta);
    return wp_update_attachment_metadata($attachment_id, $image_meta);
}

function resizeImageMultiple($filename, $sizes, $image_meta) {
    // Get original image dimensions and type

    list($origWidth, $origHeight, $imageType) = getimagesize($filename);

    // Extract file info
    $pathInfo = pathinfo($filename);
    $basename = $pathInfo['filename'];
    $extension = strtolower($pathInfo['extension']);

    // Create image from file based on type
    
    try {
        switch ($imageType) {
            case IMAGETYPE_JPEG:
                $sourceImage = @imagecreatefromjpeg($filename);
                break;
            case IMAGETYPE_PNG:
                $sourceImage = @imagecreatefrompng($filename);
                break;
            case IMAGETYPE_GIF:
                $sourceImage = @imagecreatefromgif($filename);
                break;
            default:
                return $image_meta;
        }
    } catch(Exception $e) {
       perf_point( $e->getMessage());
       exit();
   }

    $imageMime = image_type_to_mime_type($imageType);

    foreach ($sizes as $size_name => $size) {

        if($size['crop'] && $size['width'] > 0 && $size['height'] > 0) {
            $newWidth = $size['width'];
            $newHeight = $size['height'];
        } else {
            // resize keeping the aspect ratio
            $aspectRatio = $origWidth / $origHeight;

            if ($size['height'] > 0 && ($size['width'] / $size['height'] > $aspectRatio)) {
                $newHeight = $size['height'];
                $newWidth = intval($size['width'] * $aspectRatio);
            } else {
                $newWidth = $size['width'];
                $newHeight = intval($size['width'] / $aspectRatio);
            }
        }

        // Create new image
        $resizedImage = imagecreatetruecolor($newWidth, $newHeight);

        // Preserve transparency for PNG and GIF
        if ($imageType == IMAGETYPE_PNG) {
            imagecolortransparent($resizedImage, imagecolorallocatealpha($resizedImage, 0, 0, 0, 127));
            imagealphablending($resizedImage, false);
            imagesavealpha($resizedImage, true);
        } elseif ($imageType == IMAGETYPE_GIF) {
            $transparencyIndex = imagecolortransparent($sourceImage);
            if ($transparencyIndex >= 0) {
                $transparencyColor = imagecolorsforindex($sourceImage, $transparencyIndex);
                $transparencyIndex = imagecolorallocate($resizedImage, $transparencyColor['red'], $transparencyColor['green'], $transparencyColor['blue']);
                imagefill($resizedImage, 0, 0, $transparencyIndex);
                imagecolortransparent($resizedImage, $transparencyIndex);
            }
        }

        // Resize
        @imagecopyresampled($resizedImage, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $origWidth, $origHeight);

        // Prepare output filename
        $suffix = "-{$size['width']}x{$size['height']}";
        $new_filename = $basename . $suffix . '.' . $extension;
        $outputFile = $pathInfo['dirname'] . DIRECTORY_SEPARATOR . $new_filename;

        // Save resized image
        switch ($imageType) {
            case IMAGETYPE_JPEG:
                imagejpeg($resizedImage, $outputFile, 90);
                break;
            case IMAGETYPE_PNG:
                imagepng($resizedImage, $outputFile);
                break;
            case IMAGETYPE_GIF:
                imagegif($resizedImage, $outputFile);
                break;
        }

        imagedestroy($resizedImage);
        $image_meta['sizes'][ $size_name ] = [
              'file' => $new_filename,
              'width' => $newWidth,
              'height' => $newHeight,
              'mime-type' => $imageMime,
              'filesize' => filesize($outputFile)
        ];
    }

    imagedestroy($sourceImage);
    return $image_meta;
}
function _rental_parse_ids( $raw ) {
    if ( is_array( $raw ) ) {
        return $raw;
    }
    if ( empty( $raw ) ) {
        return [];
    }
    return json_decode( stripslashes( $raw ), true ) ?: [];
}

function format_time(float $seconds): string {
    if ($seconds < 0.001) {
        // under a millisecond
        return round($seconds * 1e6, 2) . ' under ms';
    } elseif ($seconds < 1) {
        // under a second
        return round($seconds * 1000, 2) . ' ms';
    } else {
        // one second or more
        return round($seconds, 2) . ' s';
    }
}


// action function for adding item in admin menus
function rental_add_pages() {
    // Add a new top-level menu (ill-advised):
    add_menu_page(__( 'Rentopian Sync', 'rentopian-sync'), __( 'Rentopian Sync', 'rentopian-sync'), 'import', __FILE__, 'rental_rentopian_sync_page', '', 57);

    // Add a submenu to the custom top-level menu:
    add_submenu_page(__FILE__, __( 'Rentopian Sync Settings', 'rentopian-sync'), __( 'Settings', 'rentopian-sync'), 'customize', 'rentopian-settings', 'rental_settings_page');

    // Add a submenu to the custom top-level menu:
    add_submenu_page(__FILE__, __( 'Rentopian Sync Log', 'rentopian-sync'), __( 'Log', 'rentopian-sync'), 'import', 'rentopian-log', 'rental_log_page');
}

// rental_rentopian_sync_page() displays the page content for the custom Rentopian Sync menu
function rental_rentopian_sync_page() {
    // variables for the field and option names
    $opt_api_key = 'rental_api_key';
    $opt_synchronize_status = 'rental_synchronize_status';
    $data_field_name = 'rental_api_key';

    $api_key_saved = false;
    if (isset($_POST["rental_save_api_key"])) {
        update_option($opt_api_key, $_POST[$opt_api_key]);
        update_option('rental_api_key_is_valid', 0);
        $api_key_saved = true;
    }

    // read in existing option value from database
    $opt_val = get_option($opt_api_key);
    $synchronize_status = get_option($opt_synchronize_status);
    $sync_files_manual = get_option('rental_sync_files_manual', 0);
    $rental_sync_files_manual_index = get_option('rental_sync_files_manual_index', 0);

    if ($synchronize_status == 1) {
        ?>
        <div class="rental-notice notice notice-success">
            <p><?php _e('Synchronization process completed successfully', 'rentopian-sync'); ?></p>
        </div>
        <?php
    } elseif ($synchronize_status == 2) {
        ?>
        <div class="rental-notice notice notice-error">
            <p><?php  _e('The synchronization is not complete, check the log section for details', 'rentopian-sync'); ?></p>
        </div>
        <?php
    } else {
        ?>
        <div class="rental-notice notice notice-warning">
            <p><?php _e('All your existing products will be deleted during synchronization! If you have any existing WooCommerce data, it is highly recommended to backup first.', 'rentopian-sync'); ?></p>
        </div>
        <?php
    }

    if ($api_key_saved) {
        ?>
        <div class="rental-notice notice notice-success">
            <p><?php _e('API key successfully saved', 'rentopian-sync');?></p>
        </div>
        <?php
    }
    ?>

    <div class="wrap">
        <div class="rntp-sync-panel panel-default">
            <div class="ajax-alert">
                <strong></strong>
            </div>

            <form method="post">
                <div class="panel-heading">
                    <h3 style="margin-top:6px"><?php _e('Synchronize with Rentopian system', 'rentopian-sync'); ?></h3>
                    <a href="https://rentopian.com/system-assets/rentopian-sync-documentation/" target="_blank" class="rntp-documentation-link">Documentation</a>
                    <div class="clearfix"></div>
                </div>
                <div class="panel-body">
                    <div class="rntp-sync-field">
                        <label for="rental_api_key" class="rental-label">
                            <?php _e("API Key:", 'rentopian-sync'); ?>
                        </label>

                        <input type="text" id="rental_api_key" class="rntp-input" name="<?php echo $data_field_name; ?>"
                               value="<?php echo $opt_val; ?>" size="30" />
                        <button type="submit" id="rental_save_api_key" name="rental_save_api_key" class="btn btn-inline-success btn-sm">
                            <span class="dashicons dashicons-yes"></span>
                            <?php _e('Save Key', 'rentopian-sync') ?>
                        </button>
                    </div>

                    <div class="rntp-help-block">
                        <div class="rntp-help-block-content">
                            <?php $api_key_url = esc_url('https://account.rentopian.com/admin/settings/company');
                            printf(
                                __( ' To get the API key, go to %1$s, click on "Copy to Clipboard" button and paste it into API key field.', 'rentopian-sync' ),
                                sprintf(
                                    '<a href="%s" target="_blank">%s</a>',
                                    $api_key_url,
                                    __( 'Company details section', 'rentopian-sync' )
                                )
                            );
                            ?>
                        </div>
                    </div>
                    <div class="clearfix"></div>
                </div>
                <div class="panel-body">
                    <div class="rntp-sync-form-title">
                        <label for="rental-checkbox-sync-files-manual" class="rental-label">
                            <?php _e('Enforce Manual File Synchronization', 'rentopian-sync')?>
                        </label>
                    </div>
                    <div class="rntp-sync-field">
                        <div class="rntp-checkbox inline">
                            <label>
                                <input id="rental-checkbox-sync-files-manual" name="rental-checkbox-sync-files-manual" type="checkbox" value="true" <?php if( esc_attr( $sync_files_manual )):?>checked="checked"<?php endif?> />
                                <span></span>
                            </label>
                        </div>
                    </div>
                    <div class="clearfix"></div>
                </div>
                <div class="panel-footer">
                    <div class="submit">

                        <?php if($synchronize_status == 1): ?>
                            <p>
                                <?php _e('Status: The synchronization has been completed successfully.', 'rentopian-sync') ?>
                        
                                <?php
                                    $rental_show_sync_duration = get_option("rental_show_sync_duration", 0);
                                    if ($rental_show_sync_duration):
                                ?>
                                    <strong> (File Synchronization took : <?php echo $rental_show_sync_duration; ?> to complete.) </strong>
                                <?php endif; ?>
                            </p>
                           

                            <button type="button" id="rental_resync" class="btn btn-danger">
                                <span class="dashicons dashicons-update"></span>
                                <?php _e('Resynchronize', 'rentopian-sync') ?>
                            </button>
                        <?php else:?>
                            <button type="submit" id="rental_sync" name="submit" class="btn btn-success">
                                <span class="dashicons dashicons-update"></span>
                                <?php _e('Synchronize', 'rentopian-sync') ?>
                            </button>
                        <?php endif?>

                        <?php
                            $rental_file_sync_method = get_option('rental_file_sync_method', 1);
                            if($sync_files_manual != 1): 
                        ?>
                            <div class="sync-options">
                                <p><strong>Select Sync Method:</strong></p>
                                <!-- <p style="color:#fc6223 !important; font-weight:bold !important;"> Notice : After changing the sync method, you MUST do a re-sync. </p> <br/> -->
                                
                                <label class="sync-radio" style="width: 10rem;">
                                    <input type="radio" name="sync_type" value="base64" <?php echo $rental_file_sync_method == 1 ? " checked " : " "; ?> >
                                    Base 64 Encode 
                                </label>

                                <label class="sync-radio" style="width: 10rem;">
                                    <input type="radio" name="sync_type" value="nginx" <?php echo $rental_file_sync_method == 2 ? " checked " : " "; ?>>
                                    Signed URL
                                </label>
                            </div>

                            <button style="margin-top: 1rem" type="submit" id="rental_remove_orphaned_files" name="submit" class="btn btn-success">
                                <span class="dashicons dashicons-remove"></span>
                                <?php _e('Remove Orphaned Files', 'rentopian-sync') ?>
                            </button>

                        <?php endif ?>

                        <?php if($sync_files_manual == 1 && $rental_sync_files_manual_index < get_option('rental_sync_files_count', 0)): ?>
                            <button type="submit" id="rental_sync_files_manual" name="submit" data-index="<?php echo $rental_sync_files_manual_index; ?>" class="btn btn-success">
                                <span class="dashicons dashicons-admin-media"></span>
                                <?php _e('Synchronize Files Manually', 'rentopian-sync') ?>
                            </button>
                        <?php endif?>

                        <?php if(defined('WPSEO_VERSION') && get_option('rental_do_not_index_hidden_duplicate_products_for_seo', 0) && !get_option('rental_sync_yoast_seo_plugin_finished', 0)): ?>
                            <button type="submit" id="rental_sync_yoast" name="rental_sync_yoast" class="btn btn-primary">
                                <?php _e('Synchronize Yoast SEO plugin', 'rentopian-sync') ?>
                            </button>
                        <?php endif?>

                    </div>
                </div>
            </form>
        </div>
    </div>

    <div id="rental_load" class="rental-modal">
        <div class="rental-modal-content">
            <h3><?php _e('Rentopian Sync', 'rentopian-sync'); ?></h3>
            <hr/>
            <div class="rental-loader-block">
                <p><?php  _e('Synchronization is in progress, please wait...', 'rentopian-sync'); ?></p>
                <div class="rental-loader-border">
                    <div class="rental-loader-progress"></div>
                </div>
                <span class="rental-loader-percent">0%</span>
            </div>
            <div class="rental-error-block" style="display: none">
                <p class="rental-error-message"></p>
                <button class="rental-loading-finish button"><?php _e("Cancel", 'rentopian-sync'); ?></button>
            </div>
        </div>
    </div>

    <div id="rental_confirmation_resync" class="rental-modal">
        <div class="rental-modal-content">
            <h3><?php _e('Rentopian Sync', 'rentopian-sync'); ?></h3>
            <hr/>
            <p><?php  _e('Are you sure you want to re-run the synchronization process?', 'rentopian-sync'); ?></p>
            <div class="rental-modal-footer">
                <button class="rental-modal-cancel btn"><?php _e("Cancel", 'rentopian-sync'); ?></button>
                <button id="rental_confirm_resync" class="btn btn-danger"><?php _e("Confirm", 'rentopian-sync'); ?></button>
            </div>
        </div>
    </div>

    <?php
}


function wp_ajax_rental_sync_yoast_seo_plugin_in_chunks() {
    $offset = isset($_POST['offset']) ? intval($_POST['offset']) : 0;
    $batch_size = 50; 
    $rental_no_index_items = get_option('rental_no_index_items', []);

    if ($rental_no_index_items && get_option('rental_do_not_index_hidden_duplicate_products_for_seo', 0)) {

        $total_items = count($rental_no_index_items);
        $items_to_process = array_slice($rental_no_index_items, $offset, $batch_size);

        // foreach ($items_to_process as $duplicate_hidden_product_id) {
        //     $rental_not_private_items = get_option('rental_not_private_items', []);
        //     if ($rental_not_private_items && isset($rental_not_private_items[$duplicate_hidden_product_id])) {
        //         continue;
        //     }

        //     rental_set_product_general_visibility($duplicate_hidden_product_id, 'private');
        // }

        foreach ($items_to_process as $duplicate_hidden_product_id) {
            $rental_not_private_items = get_option('rental_not_private_items', []);
            if ($rental_not_private_items && isset($rental_not_private_items[$duplicate_hidden_product_id])) {
                continue;
            }

            // rental_set_product_catalog_visibility($duplicate_hidden_product_id, 'hidden');
            update_post_meta($duplicate_hidden_product_id, '_rental_is_add_on', 1);
        }


        foreach ($items_to_process as $duplicate_hidden_product_id) {
            toggle_index_yoast_seo($duplicate_hidden_product_id);
        }

        if ($offset + $batch_size < $total_items) {

            wp_send_json([
                'message' => 'Batch processed successfully',
                'next_offset' => $offset + $batch_size,
                'progress_percent' => floor((($offset + $batch_size) / $total_items) * 100),
                'total_items' => $total_items
            ]);

        } else {

            update_option('rental_sync_yoast_seo_plugin_finished', 1);

            wp_send_json([
                'message' => 'Yoast SEO synchronization was successful',
                'next_offset' => null,
                'progress_percent' => 100,
                'total_items' => $total_items
            ]);
        }

    } else {
        wp_send_json_error(['message' => 'There were no items to sync for Yoast SEO plugin!']);
    }
    wp_die();    
}

function wp_ajax_rental_update_file_sync_settings() {
    if (isset($_POST['sync_files_manual'])) {
        update_option('rental_sync_files_manual', intval($_POST['sync_files_manual']));
        wp_send_json(true, 200);
    }
    wp_die();    
}

// rental_settings_page() displays the page content for the first submenu of the custom Rentopian Settings menu
function rental_settings_page() {
    global $wpdb, $rental_tables;
    $rental_day_tiers = $wpdb->prefix . $rental_tables["day_tiers"];

    // variables for the field and option names
    $opt_form_layout = 'rental_form_layout';
    $opt_set_listing_style = 'rental_set_listing_style';
    $opt_dates_on_checkout = 'rental_dates_on_checkout';
    $opt_direct_only_bookings = 'rental_direct_only_bookings';
    $opt_allow_to_pay_deposit = 'rental_allow_to_pay_deposit';
    $opt_allow_to_pay_security_deposit = 'rental_allow_to_pay_security_deposit';
    $opt_allow_to_pay_another_amount = 'rental_allow_to_pay_another_amount';
    $opt_send_email = 'rental_send_email';
    $opt_rental_referral_sources_setting = 'rental_referral_sources_setting';
    $opt_rental_event_types_setting = 'rental_event_types_setting';
    $opt_rental_exclude_order_fees = 'rental_exclude_order_fees';
    $opt_rental_payment_tips_enabled = 'rental_payment_tips_enabled';
    $opt_min_order_amount = 'rental_min_order_amount';
    $opt_min_order_text = 'rental_min_order_text';
    $opt_min_order_pickup = 'rental_min_order_pickup';
    $opt_special_terms = 'rental_special_terms';
    $opt_client_blacklisted_notif_email = 'rental_client_blacklisted_notif_email';
    $opt_client_blacklisted_reject_msg = 'rental_client_blacklisted_reject_msg';
    $opt_dates_header_label = 'rental_dates_header_label';
    $opt_select_division = 'rental_select_division';
    $opt_hide_zip = 'rental_hide_zip';
    $opt_event_start_time = 'rental_event_start_time';
    $opt_hide_end_date = 'rental_hide_end_date';
    $opt_hide_time_pickers = 'rental_hide_time_pickers';
    $opt_min_start_date = 'rental_min_start_date';
    $opt_min_dates_range = 'rental_min_dates_range';
    $opt_max_dates_range = 'rental_max_dates_range';
    $opt_date_step = 'rental_date_step';
    $opt_select_date_range = 'rental_select_date_range';
    $opt_hide_damage_waiver = 'rental_hide_damage_waiver';
    $opt_buy_damage_waiver_by_default = 'rental_buy_damage_waiver_by_default';
    $opt_hide_and_buy_damage_waiver_by_default = 'rental_hide_and_buy_damage_waiver_by_default';
    $opt_disabled_week_days = 'rental_disabled_week_days';
    $opt_hide_set_items = 'rental_hide_set_items';
    $opt_filter_unavailable_products = 'rental_filter_unavailable_products';
    $opt_display_sale_products_page = 'rental_display_sale_products_page';
    $opt_hide_product_type_label = 'rental_hide_product_type_label';
    $opt_hide_product_price = 'rental_hide_product_price';
    $opt_show_product_price_only_in_cart = 'rental_show_product_price_only_in_cart';
    $opt_do_not_use_rentopian_shipping = 'rental_do_not_use_rentopian_shipping';
    $opt_track_wc_shipping = 'rental_track_wc_shipping';
    // $opt_disable_pick_up_option = 'rental_disable_pick_up_option';
    $opt_different_pick_up_addresses = 'rental_different_pick_up_addresses';
    $opt_double_shipping_fee = 'rental_double_shipping_fee';
    $opt_combine_shipping_tax = 'rental_combine_shipping_tax';
    $opt_google_distance_key = 'rental_google_distance_key';
    $opt_free_shipping_amount = 'rental_free_shipping_amount';
    $opt_pickup_delivery = 'rental_pickup_delivery';
    $opt_special_terms_placement = 'rental_special_terms_placement';
    $opt_overbook_text = 'rental_overbook_text';
    $opt_cart_button_text = 'rental_cart_button_text';
    $opt_order_text = 'rental_order_text';
    $opt_read_more_text = 'rental_read_more_text';
    $opt_checkout_button_text = 'rental_checkout_button_text';
    $opt_order_button_text = 'rental_order_button_text';
    $opt_daily_fee_text = 'rental_daily_fee_text';
    $opt_tax_text = 'rental_tax_text';
    $opt_shipping_text = 'rental_shipping_text';
    $opt_ship_to_dif_adrs_text = 'rental_ship_to_dif_adrs_text';
    $opt_select_option_text = 'rental_select_option_text';
    $opt_start_date_text = 'rental_start_date_text';
    $opt_end_date_text = 'rental_end_date_text';
    $opt_proceed_text = 'rental_proceed_text';
    $opt_set_components_text = 'rental_set_components_text';
    $opt_referral_sources_text = 'rental_referral_sources_text';
    $opt_event_types_text = 'rental_event_types_text';
    $opt_payment_tips_text = 'rental_payment_tips_text';
    $opt_thank_you_message = 'rental_thank_you_message';
    $opt_miles_text = 'rental_miles_shipping_label_text';
    $opt_billing_details_text = 'rental_billing_details_text';
    $opt_coupon_label_text = 'rental_coupon_label_text';
    $opt_street_address_label_text = 'rental_street_address_label_text';
    $opt_not_open_dates_form = 'rental_not_open_dates_form';
    $opt_location = 'rental_show_location';
    $opt_google_map_key = 'rental_google_map_key';
    $opt_use_google_distance_key = 'rental_use_google_distance_key';
    $opt_select_a_day_by_default = 'rental_select_a_day_by_default';
    $opt_selected_default_day = 'rental_selected_default_day';
    $opt_selected_default_day_automate = 'rental_selected_default_day_automate';
    $opt_default_zip_code = 'rental_default_zip_code';
    $opt_default_start_time = 'rental_default_start_time';
    $opt_default_end_time = 'rental_default_end_time';

    $not_only_sale_products = get_option('rental_synchronized_product_type') != "sale";
    $not_only_hourly_products = get_option('rental_synchronized_product_type') != "hourly";

    $error = false;
    $success = false;
    if (isset($_POST["submit"])) {
        if (isset($_POST['rental_day_tiers'])) {
            $tiers = json_decode(stripslashes($_POST['rental_day_tiers']));
            $wpdb->query("DELETE FROM $rental_day_tiers");
            if ( !empty($tiers)) {
                $count = count($tiers);
                $tiers_sql = [];
                for ($i = 0; $i < $count; $i++) {
                    if ( !isset($tiers[$i]->min) || !isset($tiers[$i]->max) || !isset($tiers[$i]->day)
                        || ($i && $tiers[$i]->min != $tiers[$i - 1]->max)
                        || ( !$tiers[$i]->max || $tiers[$i]->min >= $tiers[$i]->max)) {
                        $error = "Wrong days calculation rules";
                        break;
                    }
                    $tiers_sql[] = "(". $tiers[$i]->min .", ". $tiers[$i]->max .", ". $tiers[$i]->day .")";
                }
                if ( !$error) {
                    rental_insert("INSERT INTO `$rental_day_tiers` (`min`, `max`, `day`) VALUES", $tiers_sql);
                }
            }
        }

        $val_form_layout = $_POST["$opt_form_layout"] ?? 'horizontal';
        $val_set_listing_style = $_POST["$opt_set_listing_style"] ?? 'standard';
        $val_dates_on_checkout = isset($_POST["$opt_dates_on_checkout"]) ? 1 : 0;
        $val_direct_only_bookings = isset($_POST["$opt_direct_only_bookings"]) ? 1 : 0;
        $val_allow_to_pay_deposit = ($val_direct_only_bookings && isset($_POST["$opt_allow_to_pay_deposit"])) ? 1 : 0;
        $val_allow_to_pay_another_amount = ($val_allow_to_pay_deposit && isset($_POST["$opt_allow_to_pay_another_amount"]) && $_POST["$opt_allow_to_pay_another_amount"]) ? 1 : 0;
        $val_allow_to_pay_security_deposit = (isset($_POST["$opt_allow_to_pay_security_deposit"])) ? 1 : 0;
        $val_send_email = isset($_POST["$opt_send_email"]) ? 1 : 0;
        $val_rental_referral_sources_setting = isset($_POST["$opt_rental_referral_sources_setting"]) ? 1 : 0;
        $val_rental_event_types_setting = isset($_POST["$opt_rental_event_types_setting"]) ? 1 : 0;
        $val_rental_exclude_order_fees = isset($_POST["$opt_rental_exclude_order_fees"]) ? 1 : 0;
        $val_rental_payment_tips_enabled = isset($_POST["$opt_rental_payment_tips_enabled"]) ? 1 : 0;
        $val_client_blacklisted_notif_email = isset($_POST["$opt_client_blacklisted_notif_email"]) ? 1 : 0;
        $val_min_order_amount = isset($_POST["$opt_min_order_amount"]) && $_POST["$opt_min_order_amount"] > 0 ? $_POST["$opt_min_order_amount"] : '';
        $val_min_order_text = $_POST["$opt_min_order_text"] ?? '';
        $val_min_order_pickup = isset($_POST["$opt_min_order_pickup"]) ? 1 : 0;
        if ( isset($_POST["$opt_pickup_delivery"]) && ($_POST["$opt_pickup_delivery"] === 'company_delivery_return' || $_POST["$opt_pickup_delivery"] === 'client_pickup_return') ) {
            $val_min_order_pickup = 0;
        }
        $val_special_terms = $_POST["$opt_special_terms"] ?? '';
        $val_client_blacklisted_reject_msg = $_POST["$opt_client_blacklisted_reject_msg"] ?? 'Sorry, your request has been declined';
        $val_dates_header_label = $_POST["$opt_dates_header_label"] ?? '';
        $val_select_division = isset($_POST["$opt_select_division"]) ? 1 : 0;
        if ($not_only_sale_products && $not_only_hourly_products) {
            $val_hide_zip = $val_select_division || isset($_POST["$opt_hide_zip"]) ? 1 : 0;
            $val_event_start_time = isset($_POST["$opt_event_start_time"]) ? 1 : 0;
            $val_hide_end_date = isset($_POST["$opt_hide_end_date"]) ? 1 : 0;
            $val_hide_time_pickers = isset($_POST["$opt_hide_time_pickers"]) ? 1 : 0;
            $val_min_start_date = isset($_POST["$opt_min_start_date"]) && $_POST["$opt_min_start_date"] > 0 ? $_POST["$opt_min_start_date"] : '';
            $val_min_dates_range = isset($_POST["$opt_min_dates_range"]) && $_POST["$opt_min_dates_range"] > 0 ? $_POST["$opt_min_dates_range"] : '';
            $val_max_dates_range = isset($_POST["$opt_max_dates_range"]) && $_POST["$opt_max_dates_range"] > 0 && ( !$val_min_dates_range || $_POST["$opt_max_dates_range"] >= $val_min_dates_range)?
                $_POST["$opt_max_dates_range"]: '';
            $val_date_step = isset($_POST["$opt_date_step"]) && $_POST["$opt_date_step"] >= 1 && ( !$val_max_dates_range || $_POST["$opt_date_step"] <= $val_max_dates_range)?
                $_POST["$opt_date_step"] : '';
            $val_select_date_range = isset($_POST["$opt_select_date_range"]) && $val_date_step? 1: 0;

            if (
                !empty($val_min_start_date)
                || !empty($val_min_dates_range)
                || !empty($val_max_dates_range)
                || !empty($val_date_step)
                || !empty($val_select_date_range)
            ) {
                if (isset($_COOKIE['rental_end_date'])) {
                    unset($_COOKIE['rental_end_date']);
                    setcookie('rental_end_date', '', time() - (31556952), "/", "", false, true);
                }
                if (isset($_COOKIE['rental_start_date'])) {
                    unset($_COOKIE['rental_start_date']);
                    setcookie('rental_start_date', '', time() - (31556952), "/", "", false, true);
                }

                //update_option('rental_selected_dates_clear', true);
            }

            $val_hide_damage_waiver = isset($_POST["$opt_hide_damage_waiver"]) ? 1 : 0;
            $val_buy_damage_waiver_by_default = isset($_POST["$opt_buy_damage_waiver_by_default"]) ? 1 : 0;
            $val_hide_and_buy_damage_waiver_by_default = isset($_POST["$opt_hide_and_buy_damage_waiver_by_default"]) ? 1 : 0;
            if (empty($val_date_step)) {
                $val_disabled_week_days = $_POST["$opt_disabled_week_days"] ?? '';
            } else {
                $val_disabled_week_days = '';
            }
           
            $val_location = isset($_POST["$opt_location"]) ? 1 : 0;
            if ($val_dates_on_checkout === 1 && get_option('rental_allow_overbook', 0) == 1) {
                $val_location = 0;
            }
            $val_select_a_day_by_default = isset($_POST["$opt_select_a_day_by_default"]) ? 1 : 0;
            $val_selected_default_day = isset($_POST["$opt_selected_default_day"]) ? intval($_POST["$opt_selected_default_day"]) : 1;
            if ($val_selected_default_day > 8) {
                $val_selected_default_day = 8;
            }
            if ($val_selected_default_day < 1) {
                $val_selected_default_day = 1;
            }

            if ($val_min_start_date != '' && ($val_selected_default_day - 1) != $val_min_start_date) {
                $val_selected_default_day = $val_min_start_date;
            }

            if ($val_select_a_day_by_default) {
                $val_min_dates_range = '';
            }

            // automate the selected default date trigger
            $val_selected_default_day_automate = isset($_POST["$opt_selected_default_day_automate"]) ? 1 : 0;

            $val_default_start_time = isset($_POST["$opt_default_start_time"]) ? $_POST["$opt_default_start_time"] : '9:00 AM';
            $val_default_end_time = isset($_POST["$opt_default_end_time"]) ? $_POST["$opt_default_end_time"] : '5:00 PM';

            if ($val_select_a_day_by_default && $val_selected_default_day && $val_selected_default_day_automate) {

                $val_location = 0;
                // auto filter products
                $today_start = $today_end = '';
                if ($val_selected_default_day <= 1) {
                    $today = date('Y/m/d, g:i A', strtotime("today"));
                } else {
                    $days_added_number = $val_selected_default_day - 1;
                    $day_string = $days_added_number == 1 ? "day" : "days";
                    $days_added_string = "+".$days_added_number." ".$day_string;
                    
                    $today = date('Y/m/d, g:i A', strtotime($days_added_string));
                }

                if ($val_default_start_time) {
                    $today_exploded = explode(',', $today);
                    $today_start = $today_exploded[0] .' '. $val_default_start_time;
                }
                if (!get_option('rental_hide_end_date') && !empty($val_default_end_time)) {
                    $today_exploded = explode(',', $today);
                    $today_end = $today_exploded[0] .' '. $val_default_end_time;
                }

                $zip = false;
                if ($opt_hide_zip) {
                    $zip = true;
                } else {
                    if (isset($_POST["$opt_default_zip_code"])) {
                        $zip = $_POST["$opt_default_zip_code"];
                    } else {
                        $zip = false;
                    }
                }
                
                if (false !== $zip) {
                    $rental_dates_form_automat_values = [
                        "start_date" => $today_start, 
                        "end_date" => $today_end, 
                        "zip" => $zip, 
                    ];
                    update_option('rental_dates_form_automat_values', json_encode($rental_dates_form_automat_values));
                    rental_validate_dates_form_and_get_products_data_init(get_option('rental_hide_time_pickers'), get_option('rental_hide_zip'), $val_location, $today_start, $today_end, '', $zip);
                }
            }
            
        }
        $val_hide_set_items = isset($_POST["$opt_hide_set_items"]) ? 1 : 0;
        $val_filter_unavailable_products = isset($_POST["$opt_filter_unavailable_products"]) ? 1 : 0;
        $val_display_sale_products_page = isset($_POST["$opt_display_sale_products_page"]) ? 1 : 0;
        $val_hide_product_type_label = isset($_POST["$opt_hide_product_type_label"]) ? 1 : 0;
        $val_hide_product_price = ( !$val_direct_only_bookings && isset($_POST["$opt_hide_product_price"])) ? 1 : 0;
        $val_show_product_price_only_in_cart = ( !$val_hide_product_price && isset($_POST["$opt_show_product_price_only_in_cart"])) ? 1 : 0;
        $val_cart_button_text = $_POST["$opt_cart_button_text"] ?? '';
        $val_checkout_button_text = $_POST["$opt_checkout_button_text"] ?? '';
        $val_order_button_text = $_POST["$opt_order_button_text"] ?? '';
        $val_order_text = $_POST["$opt_order_text"] ?? '';
        $val_read_more_text  = $_POST["$opt_read_more_text"] ?? 'Select Options';
        $val_daily_fee_text = $_POST["$opt_daily_fee_text"] ?? '';
        $val_tax_text= $_POST["$opt_tax_text"] ?? '';
        $val_shipping_text= $_POST["$opt_shipping_text"] ?? '';
        $val_ship_to_dif_adrs_text= $_POST["$opt_ship_to_dif_adrs_text"] ?? '';
        $val_select_option_text= $_POST["$opt_select_option_text"] ?? '';
        $val_start_date_text= $_POST["$opt_start_date_text"] ?? '';
        $val_end_date_text= $_POST["$opt_end_date_text"] ?? '';
        $val_proceed_text= $_POST["$opt_proceed_text"] ?? '';
        $val_set_components_text= $_POST["$opt_set_components_text"] ?? '';
        $val_referral_sources_text= $_POST["$opt_referral_sources_text"] ?? '';
        $val_event_types_text= $_POST["$opt_event_types_text"] ?? '';
        $val_payment_tips_text= $_POST["$opt_payment_tips_text"] ?? '';
        $val_thank_you_message= $_POST["$opt_thank_you_message"] ?? '';
        $val_miles_text= $_POST["$opt_miles_text"] ?? '';
        $val_billing_details_text= $_POST["$opt_billing_details_text"] ?? '';
        $val_coupon_label_text= $_POST["$opt_coupon_label_text"] ?? '';
        $val_street_address_label_text= $_POST["$opt_street_address_label_text"] ?? '';
        $val_do_not_use_rentopian_shipping = isset($_POST["$opt_do_not_use_rentopian_shipping"]) ? 1 : 0;
        $val_track_wc_shipping = $val_do_not_use_rentopian_shipping == 1 && isset($_POST["$opt_track_wc_shipping"]) ? 1 : 0;

        // $val_disable_pick_up_option = isset($_POST["$opt_disable_pick_up_option"]) ? 1 : 0;
        $val_different_pick_up_addresses = ( !$val_do_not_use_rentopian_shipping && isset($_POST["$opt_different_pick_up_addresses"])) ? 1 : 0;
        $val_double_shipping_fee = ( !$val_do_not_use_rentopian_shipping && isset($_POST["$opt_double_shipping_fee"])) ? 1 : 0;
        $val_combine_shipping_tax = isset($_POST["$opt_combine_shipping_tax"]) ? 1 : 0;
        $val_free_shipping_amount = isset($_POST["$opt_free_shipping_amount"]) && $_POST["$opt_free_shipping_amount"] > 0 ? $_POST["$opt_free_shipping_amount"] : '';
        
        $val_google_distance_key = $_POST["$opt_google_distance_key"] ?? '';
        $val_pickup_delivery = isset($_POST["$opt_pickup_delivery"]) ? $_POST["$opt_pickup_delivery"] : "company_delivery_return";
        $val_special_terms_placement = isset($_POST["$opt_special_terms_placement"]) ? $_POST["$opt_special_terms_placement"] : "special_terms_on_top";
        
        // $shipping_settings = get_option('rental_shipping_settings', false);
        // if ( $shipping_settings === false ) {
        //     $shipping_settings = rental_curl('shipping/settings', get_option('rental_api_key'));
        // }
        
        // if (
        //     ($shipping_settings->shipping_by === 'mile'
        //     || $shipping_settings->shipping_by === 'kilometre') 
        //     && $val_google_distance_key == ''
        // ){
        //     $val_pickup_delivery = "client_pickup_return";
        // }

        if ($val_do_not_use_rentopian_shipping == 1) {

            $val_different_pick_up_addresses = 0;
            $val_double_shipping_fee = 0;
            $val_combine_shipping_tax = 0;
            $val_free_shipping_amount = '';
            $val_google_distance_key = '';

            // removing all shipping zones
            // rental_empty_shipping_zones();
            // if (get_option('woocommerce_miles_based_settings')) {
            //     update_option('woocommerce_miles_based_settings', array(
            //         'enabled'           =>  'no',
            //     ));
            // }

        } else {

            $woocommerce_shipping_zones = $wpdb->prefix . 'woocommerce_shipping_zones';
            $woocommerce_shipping_zone_locations = $wpdb->prefix . 'woocommerce_shipping_zone_locations';
            $woocommerce_shipping_zone_methods = $wpdb->prefix . 'woocommerce_shipping_zone_methods';
            $rental_shipping_zone_relations = $wpdb->prefix . $rental_tables["shipping_zone_relations"];

            // company pickup/return
            if ($val_pickup_delivery == 'company_delivery_return') {
                // no local pickup

                // remove existing (local pickup) shipping zones 
                $sql_delete = "
                    DELETE FROM 
                        $woocommerce_shipping_zones
                    WHERE 
                        zone_name like '%Pickup%'
                    LIMIT 1
                ";
                $wpdb->query($sql_delete);

                $sql_delete = "
                    DELETE FROM 
                        $woocommerce_shipping_zone_methods
                    WHERE 
                        method_id = 'local_pickup'
                ";
                $wpdb->query($sql_delete);

                // removing all shipping zones
                rental_empty_shipping_zones();

                // $api_key = get_option('rental_api_key');
                // $shipping_settings = get_option('rental_shipping_settings', false);
                // if ( $shipping_settings === false ) {
                //     $shipping_settings = rental_curl('shipping/settings', $api_key);
                // }

                // if ($shipping_settings->shipping_by != 'mile' && $shipping_settings->shipping_by != 'kilometre') {

                    // update_option('woocommerce_miles_based_settings', array(
                    //     'enabled'           =>  'no',
                    // ));

                    // $shipping_zones = rental_curl('shipping/zones', $api_key);
                    // if (!empty($shipping_zones)) {

                    //     /** Arrays to hold shipping zone related sqls */
                    //     $shipping_zone_sql = [];
                    //     $shipping_zone_locations_sql = [];
                    //     $shipping_zone_methods_sql = [];
                    //     $shipping_zone_options_sql = [];
                    //     $shipping_zone_relations_sql = [];

                    //     /**
                    //      * Shipping zone entry in database
                    //      */
                    //     foreach ($shipping_zones as $zone) {
                    //         $shipping_zone_sql[] = "($zone->id, '" . $zone->country . "', 0)";

                    //         if ($zone->state) {
                    //             $shipping_zone_locations_sql[] = "($zone->id, '{$zone->country}:{$zone->state}', 'state')";
                    //         } else {
                    //             $shipping_zone_locations_sql[] = "($zone->id, '$zone->country', 'country')";
                    //         }
                    //         if ( !empty($zone->zip)) {
                    //             if (is_array($zone->zip)) {
                    //                 foreach ($zone->zip as $postcode) {
                    //                     $shipping_zone_locations_sql[] = "($zone->id, '$postcode', 'postcode')";
                    //                 }
                    //             } else {
                    //                 $shipping_zone_locations_sql[] = "($zone->id, '$zone->zip', 'postcode')";
                    //             }
                    //         }

                    //         $shipping_zone_methods_sql[] = "($zone->id, $zone->id, 'reduced_rate', 1, 1)";

                    //         $shipping_zone_options_sql[] = "('woocommerce_reduced_rate_" . $zone->id . "_settings', '" . addslashes(serialize([
                    //                 'min_order_price' => $zone->min_order_price,
                    //                 'shipping_rate' => $zone->shipping_rate,
                    //                 'regular_shipping_rate' => $zone->regular_shipping_rate
                    //             ])) . "')";

                    //         $shipping_zone_relations_sql[] = "($zone->id, $zone->id, $zone->division_id)";
                    //     }

                    //     /**
                    //      * shipping zone relations insert queries
                    //      */
                    //     // query to insert shipping zone
                    //     $wpdb->query("INSERT INTO `$woocommerce_shipping_zones` (`zone_id`, `zone_name`, `zone_order`) VALUES " . implode(", ", $shipping_zone_sql));
                    //     // query to insert shipping zone locations
                    //     $wpdb->query("INSERT INTO `$woocommerce_shipping_zone_locations` (`zone_id`, `location_code`, `location_type`) VALUES " . implode(", ", $shipping_zone_locations_sql));
                    //     // query to insert shipping zone methods
                    //     $wpdb->query("INSERT INTO `$woocommerce_shipping_zone_methods` (`zone_id`, `instance_id`, `method_id`, `method_order`, `is_enabled`) VALUES " . implode(", ", $shipping_zone_methods_sql));
                    //     // query to insert shipping zone options
                    //     $wpdb->query("INSERT INTO `$wpdb->options` (`option_name`, `option_value`) VALUES " . implode(", ", $shipping_zone_options_sql));
                    //     // query to insert shipping zone relations
                    //     $wpdb->query("INSERT INTO `$rental_shipping_zone_relations` (`id`, `rental_id`, `rental_division_id`) VALUES " . implode(", ", $shipping_zone_relations_sql));

                    //     if ($wpdb->last_error !== '') {
                    //         throw new RentalException("SQL_ERROR: $wpdb->last_error (SQL: $wpdb->last_query)", RentalException::TYPE_SYNC_GLOBAL);
                    //     }
                    // }

                // } else {

                    // $shipping_title = $shipping_settings->shipping_by === 'mile' ? 'Miles' : 'Kilometre';
                    // $shipping_label = $shipping_title . ' Based Shipping';
                    // if ($rental_miles_shipping_label_text = get_option('rental_miles_shipping_label_text', '')) {
                    //     $shipping_label = $rental_miles_shipping_label_text;
                    // }

                    // // mile based shipping
                    // update_option('woocommerce_miles_based_settings', array(
                    //     'enabled'           =>  'yes',
                    //     'title'             =>  $shipping_label,
                    //     'first_miles'       =>  $shipping_settings->min_miles,
                    //     'first_miles_rate'  =>  $shipping_settings->min_miles_cost,
                    //     'per_mile_rate'     =>  $shipping_settings->per_mile_cost,
                    // ));

                    // update_option('woocommerce_enable_shipping_calc', 'no');
                // }
            }

            // client pickup/return
            if ($val_pickup_delivery == 'client_pickup_return') {
                // only local pickup

                $val_different_pick_up_addresses = 0;
                $val_double_shipping_fee = 0;
                $val_combine_shipping_tax = 0;
                $val_free_shipping_amount = '';

                // removing all shipping zones
                rental_empty_shipping_zones();
                // if (get_option('woocommerce_miles_based_settings')) {
                //     update_option('woocommerce_miles_based_settings', array(
                //         'enabled'           =>  'no',
                //     ));
                // }
               

                $local_pickup_zone_id = $wpdb->get_col("
                    SELECT 
                        wszm.zone_id
                    FROM 
                        $woocommerce_shipping_zone_methods as wszm
                    LEFT JOIN $woocommerce_shipping_zones as zones ON zones.zone_id = wszm.zone_id
                    WHERE 
                        wszm.method_id = 'local_pickup'
                        AND zones.zone_name = 'Local Pickup'
                ");

                if (empty($local_pickup_zone_id)) {
                    $wpdb->insert($woocommerce_shipping_zones, [
                        "zone_name" => 'Local Pickup',
                        "zone_order" => 9999
                    ]);
                    $wpdb->insert($woocommerce_shipping_zone_methods, [
                        "zone_id" => $wpdb->insert_id,
                        "method_id" => 'local_pickup',
                        "method_order" => 9999,
                        "is_enabled" => 1
                    ]);
                }
            }

            // allow both
            if ($val_pickup_delivery == 'company_client_delivery_return') {
                // local pickup + other methods

                // removing all shipping zones
                rental_empty_shipping_zones();
                  
                // $api_key = get_option('rental_api_key');
                // $shipping_settings = get_option('rental_shipping_settings', false);
                // if ( $shipping_settings === false ) {
                //     $shipping_settings = rental_curl('shipping/settings', $api_key);
                // }

                // if ($shipping_settings->shipping_by === 'mile' || $shipping_settings->shipping_by === 'kilometre') {

                //     $shipping_title = $shipping_settings->shipping_by === 'mile' ? 'Miles' : 'Kilometre';
                //     $shipping_label = $shipping_title . ' Based Shipping';
                //     if ($rental_miles_shipping_label_text = get_option('rental_miles_shipping_label_text', '')) {
                //         $shipping_label = $rental_miles_shipping_label_text;
                //     }

                //     // mile based shipping
                //     update_option('woocommerce_miles_based_settings', array(
                //         'enabled'           =>  'yes',
                //         'title'             =>  $shipping_label,
                //         'first_miles'       =>  $shipping_settings->min_miles,
                //         'first_miles_rate'  =>  $shipping_settings->min_miles_cost,
                //         'per_mile_rate'     =>  $shipping_settings->per_mile_cost,
                //     ));
                //     update_option('woocommerce_enable_shipping_calc', 'no');

                // } else {
                    
                //     update_option('woocommerce_miles_based_settings', array(
                //         'enabled'           =>  'no',
                //     ));

                //     $shipping_zones = rental_curl('shipping/zones', $api_key);
                //     if ( !empty($shipping_zones)) {

                //         /** Arrays to hold shipping zone related sqls */
                //         $shipping_zone_sql = [];
                //         $shipping_zone_locations_sql = [];
                //         $shipping_zone_methods_sql = [];
                //         $shipping_zone_options_sql = [];
                //         $shipping_zone_relations_sql = [];

                //         /**
                //          * Shipping zone entry in database
                //          */
                //         foreach ($shipping_zones as $zone) {
                //             $shipping_zone_sql[] = "($zone->id, '" . $zone->country . "', 0)";

                //             if ($zone->state) {
                //                 $shipping_zone_locations_sql[] = "($zone->id, '{$zone->country}:{$zone->state}', 'state')";
                //             } else {
                //                 $shipping_zone_locations_sql[] = "($zone->id, '$zone->country', 'country')";
                //             }
                //             if ( !empty($zone->zip)) {
                //                 if (is_array($zone->zip)) {
                //                     foreach ($zone->zip as $postcode) {
                //                         $shipping_zone_locations_sql[] = "($zone->id, '$postcode', 'postcode')";
                //                     }
                //                 } else {
                //                     $shipping_zone_locations_sql[] = "($zone->id, '$zone->zip', 'postcode')";
                //                 }
                //             }

                //             $shipping_zone_methods_sql[] = "($zone->id, $zone->id, 'reduced_rate', 1, 1)";

                //             $shipping_zone_options_sql[] = "('woocommerce_reduced_rate_" . $zone->id . "_settings', '" . addslashes(serialize([
                //                     'min_order_price' => $zone->min_order_price,
                //                     'shipping_rate' => $zone->shipping_rate,
                //                     'regular_shipping_rate' => $zone->regular_shipping_rate
                //                 ])) . "')";

                //             $shipping_zone_relations_sql[] = "($zone->id, $zone->id, $zone->division_id)";
                //         }

                //         /**
                //          * shipping zone relations insert queries
                //          */
                //         // query to insert shipping zone
                //         $wpdb->query("INSERT INTO `$woocommerce_shipping_zones` (`zone_id`, `zone_name`, `zone_order`) VALUES " . implode(", ", $shipping_zone_sql));
                //         // query to insert shipping zone locations
                //         $wpdb->query("INSERT INTO `$woocommerce_shipping_zone_locations` (`zone_id`, `location_code`, `location_type`) VALUES " . implode(", ", $shipping_zone_locations_sql));
                //         // query to insert shipping zone methods
                //         $wpdb->query("INSERT INTO `$woocommerce_shipping_zone_methods` (`zone_id`, `instance_id`, `method_id`, `method_order`, `is_enabled`) VALUES " . implode(", ", $shipping_zone_methods_sql));
                //         // query to insert shipping zone options
                //         $wpdb->query("INSERT INTO `$wpdb->options` (`option_name`, `option_value`) VALUES " . implode(", ", $shipping_zone_options_sql));
                //         // query to insert shipping zone relations
                //         $wpdb->query("INSERT INTO `$rental_shipping_zone_relations` (`id`, `rental_id`, `rental_division_id`) VALUES " . implode(", ", $shipping_zone_relations_sql));

                //         if ($wpdb->last_error !== '') {
                //             throw new RentalException("SQL_ERROR: $wpdb->last_error (SQL: $wpdb->last_query)", RentalException::TYPE_SYNC_GLOBAL);
                //         }

                        $zones_not_to_add_local_pickup = $wpdb->get_col("
                            SELECT 
                                zones.zone_id
                            FROM 
                                $woocommerce_shipping_zones as zones
                            LEFT JOIN $woocommerce_shipping_zone_methods as wszm ON wszm.zone_id = zones.zone_id
                            WHERE 
                                wszm.method_id = 'local_pickup'
                        ");

                        $zones_to_add_local_pickup = [];
                        if (!empty($zones_not_to_add_local_pickup)) {

                            $zone_ids = implode(',', $zones_not_to_add_local_pickup);
                            $zones_to_add_local_pickup = $wpdb->get_col("
                                SELECT 
                                    DISTINCT zone_id
                                FROM 
                                    $woocommerce_shipping_zones
                                WHERE 
                                    zone_id NOT IN ($zone_ids)
                            ");
                        } else {

                            $zones_to_add_local_pickup = $wpdb->get_col("
                                SELECT 
                                    DISTINCT zone_id
                                FROM 
                                    $woocommerce_shipping_zones
                            ");
                        }

                        if ($zones_to_add_local_pickup) {
                            foreach($zones_to_add_local_pickup as $zone_id) {
                                $wpdb->insert($woocommerce_shipping_zone_methods, [
                                    "zone_id" => $zone_id,
                                    "method_id" => 'local_pickup',
                                    "method_order" => 1,
                                    "is_enabled" => 1
                                ]);
                            }
                        }

                //     }
                // }


                $local_pickup_zone_id = $wpdb->get_col("
                    SELECT 
                        wszm.zone_id
                    FROM 
                        $woocommerce_shipping_zone_methods as wszm
                    LEFT JOIN $woocommerce_shipping_zones as zones ON zones.zone_id = wszm.zone_id
                    WHERE 
                        wszm.method_id = 'local_pickup'
                        AND zones.zone_name = 'Local Pickup'
                ");

                if (empty($local_pickup_zone_id)) {
                    $wpdb->insert($woocommerce_shipping_zones, [
                        "zone_name" => 'Local Pickup',
                        "zone_order" => 9999
                    ]);
                    $wpdb->insert($woocommerce_shipping_zone_methods, [
                        "zone_id" => $wpdb->insert_id,
                        "method_id" => 'local_pickup',
                        "method_order" => 9999,
                        "is_enabled" => 1
                    ]);
                }
                
            }
           
        }

        $val_overbook_text = $_POST["$opt_overbook_text"] ?? '';
        $val_not_open_dates_form = isset($_POST["$opt_not_open_dates_form"]) ? 1 : 0;
        $val_google_map_key = $_POST["$opt_google_map_key"] ?? '';
        if (!empty($val_google_distance_key)) {
            $val_use_google_distance_key = $_POST["$opt_use_google_distance_key"] ?? '';
        } else {
            $val_use_google_distance_key = '';
        }
        
        if ( !$error) {

            update_option($opt_form_layout, $val_form_layout);
            update_option($opt_set_listing_style, $val_set_listing_style);
            update_option($opt_dates_on_checkout, $val_dates_on_checkout);
            update_option($opt_direct_only_bookings, $val_direct_only_bookings);
            update_option($opt_allow_to_pay_deposit, $val_allow_to_pay_deposit);
            update_option($opt_allow_to_pay_another_amount, $val_allow_to_pay_another_amount);
            update_option($opt_allow_to_pay_security_deposit, $val_allow_to_pay_security_deposit);
            update_option($opt_send_email, $val_send_email);
            update_option($opt_rental_referral_sources_setting, $val_rental_referral_sources_setting);
            update_option($opt_rental_event_types_setting, $val_rental_event_types_setting);
            update_option($opt_rental_exclude_order_fees, $val_rental_exclude_order_fees);
            update_option($opt_rental_payment_tips_enabled, $val_rental_payment_tips_enabled);
            update_option($opt_client_blacklisted_notif_email, $val_client_blacklisted_notif_email);
            update_option($opt_dates_header_label, $val_dates_header_label);
            update_option($opt_min_order_amount, $val_min_order_amount);
            if ($val_min_order_amount) {
                update_option($opt_min_order_text, $val_min_order_text);
                update_option($opt_min_order_pickup, $val_min_order_pickup);
            }
            update_option($opt_special_terms, $val_special_terms);
            update_option($opt_client_blacklisted_reject_msg, $val_client_blacklisted_reject_msg);
            update_option($opt_dates_header_label, $val_dates_header_label);
            update_option($opt_select_division, $val_select_division);
           
            /* 
             *  unset rental_division_id cookie when turnning off the select location option
             *  in order to get products & sets of all divisions 
             *  (it removes the individual division_id filter from products and sets)
            */
            if (empty($val_select_division)) {
                if (isset($_COOKIE['rental_division_id'])) {
                    unset($_COOKIE['rental_division_id']);
                    setcookie('rental_division_id', '', time() - (31556952), "/", "", false, true);
                }
            }
            
            if ($not_only_sale_products && $not_only_hourly_products) {
                update_option($opt_hide_zip, $val_hide_zip);
                update_option($opt_event_start_time, $val_event_start_time);
                update_option($opt_hide_end_date, $val_hide_end_date);
                update_option($opt_hide_time_pickers, $val_hide_time_pickers);
                update_option($opt_min_start_date, $val_min_start_date);
                update_option($opt_min_dates_range, $val_min_dates_range);
                update_option($opt_max_dates_range, $val_max_dates_range);
                update_option($opt_date_step, $val_date_step);
                update_option($opt_select_date_range, $val_select_date_range);
                update_option($opt_hide_damage_waiver, $val_hide_damage_waiver);
                update_option($opt_buy_damage_waiver_by_default, $val_buy_damage_waiver_by_default);
                update_option($opt_hide_and_buy_damage_waiver_by_default, $val_hide_and_buy_damage_waiver_by_default);
                update_option($opt_disabled_week_days, $val_disabled_week_days);
                update_option($opt_location, $val_location);
                update_option($opt_select_a_day_by_default, $val_select_a_day_by_default);
                update_option($opt_selected_default_day, $val_selected_default_day);
                update_option($opt_selected_default_day_automate, $val_selected_default_day_automate);
                update_option($opt_default_start_time, $val_default_start_time);
                update_option($opt_default_end_time, $val_default_end_time);
            }
            update_option($opt_hide_set_items, $val_hide_set_items);
            update_option($opt_filter_unavailable_products, $val_filter_unavailable_products);
            update_option($opt_display_sale_products_page, $val_display_sale_products_page);
            update_option($opt_hide_product_type_label, $val_hide_product_type_label);
            update_option($opt_hide_product_price, $val_hide_product_price);
            update_option($opt_show_product_price_only_in_cart, $val_show_product_price_only_in_cart);
            update_option($opt_cart_button_text, $val_cart_button_text);
            update_option($opt_checkout_button_text, $val_checkout_button_text);
            update_option($opt_order_button_text, $val_order_button_text);
            update_option($opt_order_text, $val_order_text);
            update_option($opt_read_more_text, $val_read_more_text);
            update_option($opt_daily_fee_text, $val_daily_fee_text);
            update_option($opt_shipping_text, $val_shipping_text);
            update_option($opt_ship_to_dif_adrs_text, $val_ship_to_dif_adrs_text);
            update_option($opt_select_option_text, $val_select_option_text);
            update_option($opt_start_date_text, $val_start_date_text);
            update_option($opt_end_date_text, $val_end_date_text);
            update_option($opt_proceed_text, $val_proceed_text);
            update_option($opt_set_components_text, $val_set_components_text);

            update_option($opt_referral_sources_text, $val_referral_sources_text);
            update_option($opt_event_types_text, $val_event_types_text);
            update_option($opt_payment_tips_text, $val_payment_tips_text);
            update_option($opt_thank_you_message, $val_thank_you_message);
            update_option($opt_miles_text, $val_miles_text);
            update_option($opt_billing_details_text, $val_billing_details_text);
            update_option($opt_coupon_label_text, $val_coupon_label_text);
            update_option($opt_street_address_label_text, $val_street_address_label_text);

            // if ($val_miles_text) {
                
                // $shipping_settings = get_option('rental_shipping_settings', false);
                // if ($shipping_settings) {


                //     if ($shipping_settings->shipping_by === 'mile' || $shipping_settings->shipping_by === 'kilometre') {

                //         $shipping_title = $shipping_settings && isset($shipping_settings->shipping_by_title) && $shipping_settings->shipping_by_title ? $shipping_settings->shipping_by_title : 'Miles';
                //         $shipping_label = $shipping_title . ' Based Shipping';
                //         if ($val_miles_text) {
                //             $shipping_label = $val_miles_text;
                //         }
        
                //         update_option('woocommerce_miles_based_settings', array(
                //             'enabled'           =>  'yes',
                //             'title'             =>  $shipping_label,
                //             'first_miles'       =>  $shipping_settings->min_miles,
                //             'first_miles_rate'  =>  $shipping_settings->min_miles_cost,
                //             'per_mile_rate'     =>  $shipping_settings->per_mile_cost,
                //         ));

                //     } else {

                //         update_option('woocommerce_miles_based_settings', array(
                //             'enabled'           =>  'no',
                //         ));
                //     }
                    
                // }
               
            // }

            update_option($opt_do_not_use_rentopian_shipping, $val_do_not_use_rentopian_shipping);
            update_option($opt_track_wc_shipping, $val_track_wc_shipping);
            // update_option($opt_disable_pick_up_option, $val_disable_pick_up_option);
            update_option($opt_different_pick_up_addresses, $val_different_pick_up_addresses);
            update_option($opt_double_shipping_fee, $val_double_shipping_fee);
            update_option($opt_combine_shipping_tax, $val_combine_shipping_tax);
            update_option($opt_google_distance_key, $val_google_distance_key);
            update_option($opt_free_shipping_amount, $val_free_shipping_amount);
            update_option($opt_pickup_delivery, $val_pickup_delivery);
            update_option($opt_special_terms_placement, $val_special_terms_placement);
            update_option($opt_overbook_text, $val_overbook_text);
            update_option($opt_not_open_dates_form, $val_not_open_dates_form);
            update_option($opt_google_map_key, $val_google_map_key);
            update_option($opt_use_google_distance_key, $val_use_google_distance_key);
            
            $success = true;
        }
    } else {
        // read in existing option value from database
        $val_form_layout = get_option($opt_form_layout);
        $val_set_listing_style = get_option($opt_set_listing_style, 'standard');
        $val_dates_on_checkout = get_option($opt_dates_on_checkout);
        $val_direct_only_bookings = get_option($opt_direct_only_bookings);
        $val_allow_to_pay_deposit = get_option($opt_allow_to_pay_deposit);
        $val_allow_to_pay_another_amount = get_option($opt_allow_to_pay_another_amount);
        $val_allow_to_pay_security_deposit = get_option($opt_allow_to_pay_security_deposit);
        $val_send_email = get_option($opt_send_email);
        $val_rental_referral_sources_setting = get_option($opt_rental_referral_sources_setting);
        $val_rental_event_types_setting = get_option($opt_rental_event_types_setting);
        $val_rental_exclude_order_fees = get_option($opt_rental_exclude_order_fees);
        $val_rental_payment_tips_enabled = get_option($opt_rental_payment_tips_enabled);
        $val_client_blacklisted_notif_email = get_option($opt_client_blacklisted_notif_email);
        $val_min_order_amount = get_option($opt_min_order_amount);
        $val_min_order_text = get_option($opt_min_order_text);
        $val_min_order_pickup = get_option($opt_min_order_pickup);
        $val_special_terms = get_option($opt_special_terms);
        $val_client_blacklisted_reject_msg = get_option($opt_client_blacklisted_reject_msg, 'Sorry, your request has been declined');
        $val_dates_header_label = get_option($opt_dates_header_label);
        $val_select_division = get_option($opt_select_division);
        if ($not_only_sale_products && $not_only_hourly_products) {
            $val_hide_zip = get_option($opt_hide_zip);
            $val_event_start_time = get_option($opt_event_start_time);
            $val_hide_end_date = get_option($opt_hide_end_date);
            $val_hide_time_pickers = get_option($opt_hide_time_pickers);
            $val_min_start_date = get_option($opt_min_start_date);
            $val_min_dates_range = get_option($opt_min_dates_range);
            $val_max_dates_range = get_option($opt_max_dates_range);
            $val_date_step = get_option($opt_date_step);
            $val_select_date_range = get_option($opt_select_date_range);
            $val_hide_damage_waiver = get_option($opt_hide_damage_waiver);
            $val_buy_damage_waiver_by_default = get_option($opt_buy_damage_waiver_by_default);
            $val_hide_and_buy_damage_waiver_by_default = get_option($opt_hide_and_buy_damage_waiver_by_default);
            $val_disabled_week_days = get_option($opt_disabled_week_days);
            $val_location = get_option($opt_location);
            $val_select_a_day_by_default = get_option($opt_select_a_day_by_default);
            $val_selected_default_day = get_option($opt_selected_default_day);
            $val_selected_default_day_automate = get_option($opt_selected_default_day_automate, 0);
            $val_default_start_time = get_option($opt_default_start_time, '9:00 AM');
            $val_default_end_time = get_option($opt_default_end_time, '5:00 PM');
        }
        $val_hide_set_items = get_option($opt_hide_set_items, 0);
        $val_filter_unavailable_products = get_option($opt_filter_unavailable_products, 1);
        $val_display_sale_products_page = get_option($opt_display_sale_products_page, 0);
        $val_hide_product_type_label = get_option($opt_hide_product_type_label, 1);
        $val_hide_product_price = get_option($opt_hide_product_price);
        $val_show_product_price_only_in_cart = get_option($opt_show_product_price_only_in_cart);
        $val_cart_button_text = get_option($opt_cart_button_text);
        $val_checkout_button_text = get_option($opt_checkout_button_text);
        $val_order_button_text = get_option($opt_order_button_text);
        $val_order_text = get_option($opt_order_text);
        $val_read_more_text = get_option($opt_read_more_text);
        $val_daily_fee_text = get_option($opt_daily_fee_text);
        $val_shipping_text = get_option($opt_shipping_text);
        $val_ship_to_dif_adrs_text = get_option($opt_ship_to_dif_adrs_text);
        $val_tax_text = get_option($opt_tax_text);
        $val_select_option_text = get_option($opt_select_option_text);
        $val_start_date_text = get_option($opt_start_date_text);
        $val_end_date_text = get_option($opt_end_date_text);
        $val_proceed_text = get_option($opt_proceed_text);
        $val_set_components_text = get_option($opt_set_components_text);

        $val_referral_sources_text = get_option($opt_referral_sources_text);
        $val_event_types_text = get_option($opt_event_types_text);
        $val_payment_tips_text = get_option($opt_payment_tips_text);
        $val_thank_you_message = get_option($opt_thank_you_message);
        $val_miles_text = get_option($opt_miles_text);
        $val_billing_details_text = get_option($opt_billing_details_text);
        $val_coupon_label_text = get_option($opt_coupon_label_text);
        $val_street_address_label_text = get_option($opt_street_address_label_text);
        $val_do_not_use_rentopian_shipping = get_option($opt_do_not_use_rentopian_shipping);
        $val_track_wc_shipping = get_option($opt_track_wc_shipping);
        // $val_disable_pick_up_option = get_option($opt_disable_pick_up_option);
        $val_different_pick_up_addresses = get_option($opt_different_pick_up_addresses);
        $val_double_shipping_fee = get_option($opt_double_shipping_fee);
        $val_combine_shipping_tax = get_option($opt_combine_shipping_tax);
        $val_google_distance_key = get_option($opt_google_distance_key);
        $val_free_shipping_amount = get_option($opt_free_shipping_amount);
        $val_pickup_delivery = get_option($opt_pickup_delivery, 'company_delivery_return');
        $val_special_terms_placement = get_option($opt_special_terms_placement, 'special_terms_on_top');
        $val_overbook_text = get_option($opt_overbook_text);
        $val_not_open_dates_form = get_option($opt_not_open_dates_form);
        $val_google_map_key = get_option($opt_google_map_key);
        $val_use_google_distance_key = get_option($opt_use_google_distance_key);
        $tiers = $wpdb->get_results("SELECT * FROM $rental_day_tiers");
    }


    if ($success) {
        ?>
        <div class="rental-notice notice notice-success">
            <p><?php _e('Settings saved successfully', 'rentopian-sync') ?></p>
        </div>
        <?php
    } elseif ($error) {
        ?>
        <div class="rental-notice notice notice-danger">
            <p><?php echo $error ?></p>
        </div>
        <?php
    }
    ?>
    <div class="wrap">
        <h2 class="rental-title"><?php _e("Plugin Options", 'rentopian-sync'); ?></h2>
        <hr/>

        <div class="rntp-sync-panel">
            <form method="post" id="rental_settings">
                <div class="rental-tabs">
                    <ul class="rental-tabs__list">
                        <li><a><?php _e('General Settings', 'rentopian-sync')?></a></li>
                        <li><a><?php _e('Textual Labels', 'rentopian-sync')?></a></li>
                        <li><a><?php _e('Multiplication Tiers', 'rentopian-sync')?></a></li>
                    </ul>
                    <div class="rental-tabs__tab-content">
                        <div class="rental-tab">
                            <div class="rental-inner-title">
                                <h3>Layout</h3>
                            </div>
                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label">
                                        <?php _e('Booking Form Type', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-radio inline">
                                        <input id="rntp-form-horizontal"
                                               name="<?php echo esc_attr($opt_form_layout); ?>"
                                               required="required"
                                               type="radio"
                                               value="horizontal"
                                               <?php if( esc_attr( $val_form_layout )  === 'horizontal' ):?>checked="checked"<?php endif?>
                                        />
                                        <label for="rntp-form-horizontal" class="radio-label">Standalone, Horizontal</label>
                                    </div>
                                    <div class="rntp-radio inline">
                                        <input id="rntp-form-in-cart"
                                               required="required"
                                               name="<?php echo esc_attr($opt_form_layout); ?>"
                                               type="radio"
                                               value="in-cart"
                                               <?php if( esc_attr( $val_form_layout ) === 'in-cart'):?>checked="checked"<?php endif?>
                                        />
                                        <label for="rntp-form-in-cart" class="radio-label">Inside Fly-In Cart</label>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('The "Inside Fly-In Cart" option is not supported by all themes. It is recommended to use a theme provided by Rentopian for guaranteed compatibility.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>

                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label">
                                        <?php _e('Textual header (label) for Fly-In Cart booking type', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <textarea id="rental_dates_header_label" name="<?php echo $opt_dates_header_label; ?>"><?php echo $val_dates_header_label? $val_dates_header_label: ''; ?></textarea>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('The "Textual header (label) for Fly-In Cart" option appears on top of the date selection form in fly-in cart section if not blank.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>
                            
                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label for="rntp-checkbox-<?php echo esc_attr($opt_dates_on_checkout)?>" class="rental-label">
                                        <?php _e('Show the dates form only on the checkout page', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-checkbox inline">
                                        <label>
                                            <input id="rntp-checkbox-<?php echo esc_attr($opt_dates_on_checkout)?>" name="<?php echo esc_attr($opt_dates_on_checkout); ?>" type="checkbox" value="true" <?php if( esc_attr( $val_dates_on_checkout )):?>checked="checked"<?php endif; if (!get_option('rental_allow_overbook', 1)):?> disabled=true <?php endif;?> />
                                            <span></span>
                                        </label>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('Show the start/end dates form only in checkout page.', 'rentopian-sync')?>
                                        <?php if (!get_option('rental_allow_overbook', 1)): _e('It works only when overbooks are allowed.', 'rentopian-sync'); endif;?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>

                            <div class="rental-inner-title">
                                <h3>Quotes / Orders</h3>
                            </div>
                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label for="rntp-checkbox-<?php echo esc_attr($opt_direct_only_bookings)?>" class="rental-label">
                                        <?php _e('Allow Direct Bookings', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-checkbox inline">
                                        <label>
                                            <input id="rntp-checkbox-<?php echo esc_attr($opt_direct_only_bookings)?>" name="<?php echo esc_attr($opt_direct_only_bookings); ?>" type="checkbox" value="true" <?php if( esc_attr( $val_direct_only_bookings )):?>checked="checked"<?php endif?> />
                                            <span></span>
                                        </label>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('Allow visitors add items to cart and checkout directly, without sending a quote first.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>
                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_allow_to_pay_deposit)?>">
                                        <?php _e('Allow Deposit', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-checkbox inline">
                                        <label>
                                            <input id="rntp-checkbox-<?php echo esc_attr($opt_allow_to_pay_deposit)?>"
                                                   name="<?php echo esc_attr($opt_allow_to_pay_deposit); ?>"
                                                   type="checkbox"
                                                   value="true"
                                                <?php echo $val_allow_to_pay_deposit? 'checked': ''; echo $val_direct_only_bookings? '': ' disabled' ?>/>
                                            <span></span>
                                        </label>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('Allow checkout by paying the deposit only.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>
                            <div class="rental-form-group" id="rental-another-amount-group" <?php if( !$val_allow_to_pay_deposit): ?>style="display: none"<?php endif; ?>>
                                <div>
                                    <input id='rental-disable-another-amount' name="<?php echo esc_attr($opt_allow_to_pay_another_amount); ?>"
                                           type='radio' <?php echo $val_allow_to_pay_another_amount? '': 'checked'; ?> class='input-radio' value=''>
                                    <label for='rental-disable-another-amount'><?php _e('Either exact deposit sum or full sum must be paid.', 'rentopian-sync'); ?></label>
                                    <input id='rental-enable-another-amount' name="<?php echo esc_attr($opt_allow_to_pay_another_amount); ?>"
                                           type='radio' <?php echo $val_allow_to_pay_another_amount? 'checked': ''; ?> class='input-radio' value='1'>
                                    <label for='rental-enable-another-amount'><?php _e('Any amount from deposit sum to order total sum is allowed.', 'rentopian-sync'); ?></label>
                                </div>
                                <div class="clearfix"></div>
                            </div>
                            <!-- security deposit -->
                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title"> 
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_allow_to_pay_security_deposit)?>">
                                        <?php _e('Enforce Security Deposit', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-checkbox inline">
                                        <label>
                                            <input id="rntp-checkbox-<?php echo esc_attr($opt_allow_to_pay_security_deposit)?>"
                                                   name="<?php echo esc_attr($opt_allow_to_pay_security_deposit); ?>"
                                                   type="checkbox"
                                                   value="true"
                                                <?php echo $val_allow_to_pay_security_deposit? 'checked': ''; ?>/>
                                            <span></span>
                                        </label>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('Allow checkout by paying the security deposit only.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>
                            <!-- end of security deposit -->
                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label for="rntp-checkbox-<?php echo esc_attr($opt_send_email)?>" class="rental-label">
                                        <?php _e('Send email once a quote/order is placed', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-checkbox inline">
                                        <label>
                                            <input id="rntp-checkbox-<?php echo esc_attr($opt_send_email)?>" name="<?php echo esc_attr($opt_send_email); ?>" type="checkbox" value="true" <?php if(esc_attr($val_send_email)):?>checked="checked"<?php endif?> />
                                            <span></span>
                                        </label>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('Send an email to the company about the new quote/order when it is registered in the Rentopian system.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>
                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_min_order_amount)?>">
                                        <?php _e('Minimum order amount', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-input-text">
                                        <input type="number" id="rntp-input-<?php echo esc_attr($opt_min_order_amount)?>"
                                               min="0.01" step="0.01"
                                               name="<?php echo esc_attr($opt_min_order_amount); ?>"
                                               value="<?php echo esc_attr($val_min_order_amount); ?>"/>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('Restrict the checkout option to minimal order amount. Possible options: do not allow, allow pickup only', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>
                            <div class="rental-form-group rental-min-order-group" <?php if( !$val_min_order_amount): ?>style="display: none"<?php endif; ?>>
                                <div class="rntp-sync-form-title">
                                    <label for="rntp-input-<?php echo esc_attr($opt_min_order_text)?>">
                                        <?php _e('Cart message', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <textarea id="rntp-input-<?php echo esc_attr($opt_min_order_text); ?>"
                                              name="<?php echo esc_attr($opt_min_order_text); ?>"><?php echo esc_attr($val_min_order_text); ?></textarea>
                                </div>
                                <div class="rntp-help-block"></div>
                                <div class="clearfix"></div>
                            </div>
                            <div class="rental-form-group rental-min-order-group" <?php if( !$val_min_order_amount): ?>style="display: none"<?php endif; ?>>
                                <div class="rntp-sync-form-title">
                                    <label for="rntp-checkbox-<?php echo esc_attr($opt_min_order_pickup)?>">
                                        <?php _e('Allow pickup if minimal is not met', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-checkbox inline">
                                        <label>
                                            <input id="rntp-checkbox-<?php echo esc_attr($opt_min_order_pickup)?>" name="<?php echo esc_attr($opt_min_order_pickup); ?>" type="checkbox" value="true" <?php if(esc_attr($val_min_order_pickup)):?>checked="checked"<?php endif?> />
                                            <span></span>
                                        </label>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('Can be enabled only if "Pickup / Delivery options" setting is set to "Allow Both".', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>


                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label for="rntp-checkbox-<?php echo esc_attr($opt_rental_referral_sources_setting)?>" class="rental-label">
                                        <?php _e('Checkout page - show referral sources selection', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-checkbox inline">
                                        <label>
                                            <input id="rntp-checkbox-<?php echo esc_attr($opt_rental_referral_sources_setting)?>" name="<?php echo esc_attr($opt_rental_referral_sources_setting); ?>" type="checkbox" value="true" <?php if(esc_attr($val_rental_referral_sources_setting)):?>checked="checked"<?php endif?> />
                                            <span></span>
                                        </label>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('Will show a dropdown on the checkout page, suggesting to select a referral source.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>

                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label for="rntp-checkbox-<?php echo esc_attr($opt_rental_event_types_setting)?>" class="rental-label">
                                        <?php _e('Checkout page - show Event Types selection', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-checkbox inline">
                                        <label>
                                            <input id="rntp-checkbox-<?php echo esc_attr($opt_rental_event_types_setting)?>" name="<?php echo esc_attr($opt_rental_event_types_setting); ?>" type="checkbox" value="true" <?php if(esc_attr($val_rental_event_types_setting)):?>checked="checked"<?php endif?> />
                                            <span></span>
                                        </label>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('Will show a dropdown on the checkout page, suggesting to select an Event Type.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>

                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label for="rntp-checkbox-<?php echo esc_attr($opt_rental_exclude_order_fees)?>" class="rental-label">
                                        <?php _e('Exclude auto applied fees from the quotes/orders', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-checkbox inline">
                                        <label>
                                            <input id="rntp-checkbox-<?php echo esc_attr($opt_rental_exclude_order_fees)?>" name="<?php echo esc_attr($opt_rental_exclude_order_fees); ?>" type="checkbox" value="true" <?php if(esc_attr($val_rental_exclude_order_fees)):?>checked="checked"<?php endif?> />
                                            <span></span>
                                        </label>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('Will remove the auto applied fees from the quotes/orders.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>

                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label for="rntp-checkbox-<?php echo esc_attr($opt_rental_payment_tips_enabled)?>" class="rental-label">
                                        <?php _e('Enable payment tips', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-checkbox inline">
                                        <label>
                                            <input id="rntp-checkbox-<?php echo esc_attr($opt_rental_payment_tips_enabled)?>" name="<?php echo esc_attr($opt_rental_payment_tips_enabled); ?>" type="checkbox" value="true" <?php if(esc_attr($val_rental_payment_tips_enabled)):?>checked="checked"<?php endif?> />
                                            <span></span>
                                        </label>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('Will enable displaying the list of payment tips for customers to choose from on checkout page for orders with direct payment.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>

                            <div class="rental-inner-title">
                                <h3>Blacklists</h3>
                            </div>
                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label for="rntp-checkbox-<?php echo esc_attr($opt_client_blacklisted_notif_email)?>" class="rental-label">
                                        <?php _e('Notify admin about blacklisted client activity', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-checkbox inline">
                                        <label>
                                            <input id="rntp-checkbox-<?php echo esc_attr($opt_client_blacklisted_notif_email)?>" name="<?php echo esc_attr($opt_client_blacklisted_notif_email); ?>" type="checkbox" value="true" <?php if(esc_attr($val_client_blacklisted_notif_email)):?>checked="checked"<?php endif?> />
                                            <span></span>
                                        </label>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('Send an email to the admin user(s) of the company about the blacklisted clients activity.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>
                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="client_blacklisted_reject_msg">
                                        <?php _e('Blacklisted client rejection message', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <textarea id="client_blacklisted_reject_msg" name="<?php echo $opt_client_blacklisted_reject_msg; ?>"><?php echo $val_client_blacklisted_reject_msg? $val_client_blacklisted_reject_msg: 'Sorry, your request has been declined'; ?></textarea>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('Rejection message for blacklisted client(s).', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>

                            <?php if ($not_only_sale_products && $not_only_hourly_products) : ?>

                                <div class="rental-inner-title">
                                    <h3>Date / Time / ZIP Code / Location Options</h3>
                                </div>

                                <div class="rental-form-group">
                                    <div class="rntp-sync-form-title">
                                        <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_hide_end_date)?>">
                                            <?php _e('Hide return date', 'rentopian-sync')?>
                                        </label>
                                    </div>
                                    <div class="rntp-sync-field">
                                        <div class="rntp-checkbox inline">
                                            <label>
                                                <input id="rntp-checkbox-<?php echo esc_attr($opt_hide_end_date)?>" name="<?php echo esc_attr($opt_hide_end_date); ?>" type="checkbox" value="true" <?php if( esc_attr( $val_hide_end_date)):?>checked="checked"<?php endif?> />
                                                <span></span>
                                            </label>
                                        </div>
                                    </div>
                                    <div class="rntp-help-block">
                                        <div class="rntp-help-block-content">
                                            <?php _e('Hide end date field from shop page.', 'rentopian-sync')?>
                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                </div>
                                <div class="rental-form-group">
                                    <div class="rntp-sync-form-title">
                                        <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_hide_time_pickers)?>">
                                            <?php _e('Hide start and end time pickers', 'rentopian-sync')?>
                                        </label>
                                    </div>
                                    <div class="rntp-sync-field">
                                        <div class="rntp-checkbox inline">
                                            <label>
                                                <input id="rntp-checkbox-<?php echo esc_attr($opt_hide_time_pickers)?>" name="<?php echo esc_attr($opt_hide_time_pickers); ?>" type="checkbox" value="true" <?php if( esc_attr( $val_hide_time_pickers )):?>checked="checked"<?php endif?> />
                                                <span></span>
                                            </label>
                                        </div>
                                    </div>
                                    <div class="rntp-help-block">
                                        <div class="rntp-help-block-content">
                                            <?php _e('If selected, the calendar picker will show start / end days and hide the times.', 'rentopian-sync')?>
                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                </div>
                                <div class="rental-form-group">
                                    <div class="rntp-sync-form-title">
                                        <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_hide_zip)?>">
                                            <?php _e('Hide ZIP code', 'rentopian-sync')?>
                                        </label>
                                    </div>
                                    <div class="rntp-sync-field">
                                        <div class="rntp-checkbox inline">
                                            <label>
                                                <input id="rntp-checkbox-<?php echo esc_attr($opt_hide_zip) ?>"
                                                       name="<?php echo esc_attr($opt_hide_zip); ?>" type="checkbox"
                                                       <?php if ($val_hide_zip): ?>checked="checked"<?php endif ?>
                                                       <?php if ($val_select_division): ?>disabled<?php endif ?>
                                                       value="true"/>
                                                <span></span>
                                            </label>
                                        </div>
                                    </div>
                                    <div class="rntp-help-block">
                                        <div class="rntp-help-block-content">
                                            <?php _e('If you have only one division and do not use mileage based delivery option, you can hide the ZIP code field.', 'rentopian-sync')?>
                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                </div>
                                <div class="rental-form-group">
                                    <div class="rntp-sync-form-title">
                                        <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_event_start_time)?>">
                                            <?php _e('Show event start time', 'rentopian-sync')?>
                                        </label>
                                    </div>
                                    <div class="rntp-sync-field">
                                        <div class="rntp-checkbox inline">
                                            <label>
                                                <input id="rntp-checkbox-<?php echo esc_attr($opt_event_start_time)?>" name="<?php echo esc_attr($opt_event_start_time); ?>" type="checkbox" value="true" <?php if( esc_attr( $val_event_start_time )):?>checked="checked"<?php endif?> />
                                                <span></span>
                                            </label>
                                        </div>
                                    </div>
                                    <div class="rntp-help-block">
                                        <div class="rntp-help-block-content">
                                            <?php _e('Adds an "Event start time" field in checkout section.', 'rentopian-sync')?>
                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                </div>
                                <div class="rental-form-group">
                                    <div class="rntp-sync-form-title">
                                        <label class="rental-label" for="rntp-input-<?php echo esc_attr($opt_min_start_date)?>">
                                            <?php _e('Orders offset (in days)', 'rentopian-sync')?>
                                        </label>
                                    </div>
                                    <div class="rntp-sync-field">
                                        <div class="rntp-input-text">
                                            <input type="number" id="rntp-input-<?php echo esc_attr($opt_min_start_date)?>"
                                                   min="1" step="1"
                                                   name="<?php echo esc_attr($opt_min_start_date); ?>"
                                                   value="<?php echo esc_attr($val_min_start_date); ?>"/>
                                        </div>
                                    </div>
                                    <div class="rntp-help-block">
                                        <div class="rntp-help-block-content">
                                            <?php _e('Blocks the ability to put orders for specified number of days starting from today.', 'rentopian-sync')?>
                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                </div>
                                <div class="rental-form-group">
                                    <div class="rntp-sync-form-title">
                                        <label class="rental-label" for="rntp-input-<?php echo esc_attr($opt_min_dates_range)?>">
                                            <?php _e('Minimum range (in days)', 'rentopian-sync')?>
                                        </label>
                                    </div>
                                    <div class="rntp-sync-field">
                                        <div class="rntp-input-text">
                                            <input type="number" id="rntp-input-<?php echo esc_attr($opt_min_dates_range)?>"
                                                   min="1" step="1"
                                                   name="<?php echo esc_attr($opt_min_dates_range); ?>"
                                                   value="<?php echo esc_attr($val_min_dates_range); ?>"/>
                                        </div>
                                    </div>
                                    <div class="rntp-help-block">
                                        <div class="rntp-help-block-content">
                                            <?php _e('The minimum interval between start date and end date.', 'rentopian-sync')?>
                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                </div>
                                <div class="rental-form-group">
                                    <div class="rntp-sync-form-title">
                                        <label class="rental-label" for="rntp-input-<?php echo esc_attr($opt_max_dates_range)?>">
                                            <?php _e('Maximum range (in days)', 'rentopian-sync')?>
                                        </label>
                                    </div>
                                    <div class="rntp-sync-field">
                                        <div class="rntp-input-text">
                                            <input type="number" id="rntp-input-<?php echo esc_attr($opt_max_dates_range)?>"
                                                   min="1" step="1"
                                                   name="<?php echo esc_attr($opt_max_dates_range); ?>"
                                                   value="<?php echo esc_attr($val_max_dates_range); ?>"/>
                                        </div>
                                    </div>
                                    <div class="rntp-help-block">
                                        <div class="rntp-help-block-content">
                                            <?php _e('The maximum interval between start date and end date.', 'rentopian-sync')?>
                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                </div>
                                <div class="rental-form-group fixed-interval-group">
                                    <div class="rntp-sync-form-title">
                                        <label class="rental-label" for="rntp-input-<?php echo esc_attr($opt_date_step)?>">
                                            <?php _e('Fixed Rental Interval (in days)', 'rentopian-sync'); ?>
                                        </label>
                                    </div>
                                    <div class="rntp-sync-field">
                                        <div class="rntp-input-text">
                                            <input type="number" id="rntp-input-<?php echo esc_attr($opt_date_step)?>"
                                                   min="1" step="1"
                                                   name="<?php echo esc_attr($opt_date_step); ?>"
                                                   value="<?php echo esc_attr($val_date_step); ?>"/>
                                        </div>
                                    </div>
                                    <div class="rntp-help-block">
                                        <div class="rntp-help-block-content">
                                            <?php _e('Allow renting only with specific intervals. For example, a 4 day interval means the item with rental start date of Sept 1, can be rented for Sep 1-5, or 1-9 but not 1-7.', 'rentopian-sync'); ?>
                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                </div>
                                <div class="rental-form-group fixed-interval-group">
                                    <div class="rntp-sync-form-title">
                                        <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_select_date_range) ?>">
                                            <?php _e('Select Dates Range', 'rentopian-sync') ?>
                                        </label>
                                    </div>
                                    <div class="rntp-sync-field">
                                        <div class="rntp-checkbox inline">
                                            <label>
                                                <input type="checkbox" value="1"
                                                       name="<?php echo esc_attr($opt_select_date_range); ?>"
                                                       id="rntp-checkbox-<?php echo esc_attr($opt_select_date_range) ?>"
                                                    <?php echo $val_select_date_range? 'checked="checked"': '';
                                                    echo $val_date_step? '': ' disabled'; ?>/>
                                                <span></span>
                                            </label>
                                        </div>
                                    </div>
                                    <div class="rntp-help-block">
                                        <div class="rntp-help-block-content">
                                            <?php _e('Select a rental date range instead of an end date. The "Fixed Rental interval (in days)" option above MUST be set to enable this option.', 'rentopian-sync') ?>

                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                </div>
                                <div class="rental-form-group restricted-days-section">
                                    <div class="rntp-sync-form-title">
                                        <label class="rental-label">
                                            <?php _e('Restrict orders to specific days of week', 'rentopian-sync')?>
                                        </label>
                                    </div>
                                    <div class="rntp-sync-field">
                                        <ul>
                                            <li>
                                                <input id="rntp-disabled-week-1" name="<?php echo esc_attr($opt_disabled_week_days); ?>[1]"
                                                       <?php if ($val_disabled_week_days && isset($val_disabled_week_days[1])): ?>checked<?php endif ?>
                                                       type="checkbox" value="1"/>
                                                <label for="rntp-disabled-week-1"><?php _e('Monday', 'rentopian-sync')?></label>
                                            </li>
                                            <li>
                                                <input id="rntp-disabled-week-2" name="<?php echo esc_attr($opt_disabled_week_days); ?>[2]"
                                                       <?php if ($val_disabled_week_days && isset($val_disabled_week_days[2])): ?>checked<?php endif ?>
                                                       type="checkbox" value="1"/>
                                                <label for="rntp-disabled-week-2"><?php _e('Tuesday', 'rentopian-sync')?></label>
                                            </li>
                                            <li>
                                                <input id="rntp-disabled-week-3" name="<?php echo esc_attr($opt_disabled_week_days); ?>[3]"
                                                       <?php if ($val_disabled_week_days && isset($val_disabled_week_days[3])): ?>checked<?php endif ?>
                                                       type="checkbox" value="1"/>
                                                <label for="rntp-disabled-week-3"><?php _e('Wednesday', 'rentopian-sync')?></label>
                                            </li>
                                            <li>
                                                <input id="rntp-disabled-week-4" name="<?php echo esc_attr($opt_disabled_week_days); ?>[4]"
                                                       <?php if ($val_disabled_week_days && isset($val_disabled_week_days[4])): ?>checked<?php endif ?>
                                                       type="checkbox" value="1"/>
                                                <label for="rntp-disabled-week-4"><?php _e('Thursday', 'rentopian-sync')?></label>
                                            </li>
                                            <li>
                                                <input id="rntp-disabled-week-5" name="<?php echo esc_attr($opt_disabled_week_days); ?>[5]"
                                                       <?php if ($val_disabled_week_days && isset($val_disabled_week_days[5])): ?>checked<?php endif ?>
                                                       type="checkbox" value="1"/>
                                                <label for="rntp-disabled-week-5"><?php _e('Friday', 'rentopian-sync')?></label>
                                            </li>
                                            <li>
                                                <input id="rntp-disabled-week-6" name="<?php echo esc_attr($opt_disabled_week_days); ?>[6]"
                                                       <?php if ($val_disabled_week_days && isset($val_disabled_week_days[6])): ?>checked<?php endif ?>
                                                       type="checkbox" value="1"/>
                                                <label for="rntp-disabled-week-6"><?php _e('Saturday', 'rentopian-sync')?></label>
                                            </li>
                                            <li>
                                                <input id="rntp-disabled-week-0" name="<?php echo esc_attr($opt_disabled_week_days); ?>[0]"
                                                       <?php if ($val_disabled_week_days && isset($val_disabled_week_days[0])): ?>checked<?php endif ?>
                                                       type="checkbox" value="1"/>
                                                <label for="rntp-disabled-week-0"><?php _e('Sunday', 'rentopian-sync')?></label>
                                            </li>
                                        </ul>
                                    </div>
                                    <div class="rntp-help-block">
                                        <div class="rntp-help-block-content">
                                            <?php _e('Blocks the ability to put an order that starts on the day(s) of week specified here.', 'rentopian-sync')?>
                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                </div>
                                <div class="rental-form-group">
                                    <div class="rntp-sync-form-title">
                                        <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_location)?>">
                                            <?php _e('Show Delivery Address Input', 'rentopian-sync')?>
                                        </label>
                                    </div>
                                    <div class="rntp-sync-field">
                                        <div class="rntp-checkbox inline">
                                            <label>
                                                <input id="rntp-checkbox-<?php echo esc_attr($opt_location)?>" name="<?php echo esc_attr($opt_location); ?>" type="checkbox" value="true" <?php if( esc_attr( $val_location )):?>checked="checked"<?php endif?> />
                                                <span></span>
                                            </label>
                                        </div>
                                    </div>
                                    <div class="rntp-help-block">
                                        <div class="rntp-help-block-content">
                                            <?php _e('If selected, beside the start/end date fields, there will be a "Location" field for customers to enter full delivery address.', 'rentopian-sync')?>
                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                </div>
                                <div class="rental-form-group google-key-wrapper">
                                    <div class="rntp-sync-form-title">
                                        <label class="rental-label" for="rntp-input-<?php echo esc_attr($opt_google_map_key)?>">
                                            <?php _e('Google Address Autocomplete API Key', 'rentopian-sync')?>
                                        </label>

                                        <label class="rental-label rntp-use-google-distance" for="rntp-checkbox-<?php echo esc_attr($opt_use_google_distance_key)?>" style="margin-top: 2rem;font-size: .8rem;">
                                            <?php _e('Use The Existing Google Distance Key.', 'rentopian-sync')?>
                                        </label>
                                    </div>
                                    <div class="rntp-sync-field">
                                        <div class="rntp-input-text">
                                            <input type="text" id="rntp-input-<?php echo esc_attr($opt_google_map_key)?>"
                                                name="<?php echo esc_attr($opt_google_map_key); ?>"
                                                value="<?php echo esc_attr($val_google_map_key); ?>"/>
                                        </div>

                                        <div class="rntp-checkbox inline rntp-use-google-distance" style="margin-top: 2rem;">
                                            <label>
                                                <input id="rntp-checkbox-<?php echo esc_attr($opt_use_google_distance_key)?>" name="<?php echo esc_attr($opt_use_google_distance_key); ?>" type="checkbox" value="true" <?php if( esc_attr( $val_use_google_distance_key )):?>checked="checked"<?php endif?> />
                                                <span></span>
                                            </label>
                                        </div>
                                    </div>
                                    <div class="rntp-help-block">
                                        <div class="rntp-help-block-content">
                                            <?php
                                                $gmap_docs = RENTOPIAN_SYNC_DOCUMENTATION_URL.'#google-map-key';
                                                echo sprintf(__( 'Will autocomplete the address for “Delivery address input” field and on the checkout page. Detailed instructions for retrieving a key are provided ', 'rentopian-sync').wp_kses( '<a href="%1s" target="_blank">%2s</a>.', array(  'a' => array( 'href' => array(), 'target' => array() ) ) ), esc_url( $gmap_docs ), __( 'here', 'rentopian-sync'));
                                            ?>
                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                </div>

                                <div class="rental-form-group">
                                    <div class="rntp-sync-form-title">
                                        <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_select_a_day_by_default)?>">
                                            <?php _e('Enable selecting a day by default in calendar', 'rentopian-sync')?>
                                        </label>
                                    </div>
                                    <div class="rntp-sync-field">
                                        <div class="rntp-checkbox inline">
                                            <label>
                                                <input id="rntp-checkbox-<?php echo esc_attr($opt_select_a_day_by_default)?>" name="<?php echo esc_attr($opt_select_a_day_by_default); ?>" type="checkbox" value="true" <?php if( esc_attr( $val_select_a_day_by_default )):?>checked="checked"<?php endif?> />
                                                <span></span>
                                            </label>
                                        </div>
                                    </div>
                                    <div class="rntp-help-block">
                                        <div class="rntp-help-block-content">
                                            <?php _e('If checked, the calendar will have the current(or specified) day selected by default.', 'rentopian-sync')?>
                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                </div>
                                <div class="rental-form-group rental-hide" id="<?php echo esc_attr($opt_selected_default_day). "_wrapper" ?>">
                                    <div class="rntp-sync-form-title">
                                        <label class="rental-label" for="rntp-selectbox-<?php echo esc_attr($opt_selected_default_day)?>">
                                            <?php _e('Select a specific day by default', 'rentopian-sync')?>
                                        </label>
                                    </div>
                                    <div class="rntp-sync-field">
                                        <div class="rntp-selectbox">
                                            <select id="<?php echo esc_attr($opt_selected_default_day)."-select" ?>">
                                                <?php 
                                                    $selected_default_days_options = [
                                                        [
                                                            'name' => 'Today',
                                                            'value' => 1,
                                                        ],
                                                        [
                                                            'name' => '+1 day',
                                                            'value' => 2,
                                                        ],
                                                        [
                                                            'name' => '+2 days',
                                                            'value' => 3,
                                                        ],
                                                        [
                                                            'name' => '+3 days',
                                                            'value' => 4,
                                                        ],
                                                        [
                                                            'name' => '+4 days',
                                                            'value' => 5,
                                                        ],
                                                        [
                                                            'name' => '+5 days',
                                                            'value' => 6,
                                                        ],
                                                        [
                                                            'name' => '+6 days',
                                                            'value' => 7,
                                                        ],
                                                        [
                                                            'name' => '+7 days',
                                                            'value' => 8,
                                                        ]
                                                    ];
                                                    if (empty($val_selected_default_day)) {
                                                        $val_selected_default_day = 1;
                                                    }

                                                    foreach($selected_default_days_options as $day_option) {
                                                        $selected = $val_selected_default_day == $day_option['value'] ? 'selected' : '';
                                                        echo '<option '.$selected.'  value="'.$day_option['value'].'"> '.$day_option['name'].' </option>';
                                                    }
                                                ?>
                                            </select>

                                            <input type="hidden" class="rental-disapper" id="rntp-input-<?php echo esc_attr($opt_selected_default_day) ?>"
                                                name="<?php echo esc_attr($opt_selected_default_day); ?>"
                                                value="<?php echo esc_attr($val_selected_default_day); ?>"/>
                                        </div>
                                    </div>
                                    <div class="rntp-help-block">
                                        <div class="rntp-help-block-content">
                                            <?php _e('If an option is selected, the calendar will have the chosen day selected and will show available products (of that day) by default.', 'rentopian-sync')?>
                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                </div>

                                <?php /* if(get_option('rental_form_layout') === "in-cart") :?>

                                    <div class="rental-form-group rental-hide" id="<?php echo esc_attr($opt_selected_default_day_automate). "_wrapper" ?>">
                                        <div class="rntp-sync-form-title">
                                            <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_selected_default_day_automate)?>">
                                                <?php _e('Automate default date selection/filter products action', 'rentopian-sync')?>
                                            </label>
                                        </div>
                                        <div class="rntp-sync-field">
                                            <div class="rntp-checkbox inline">
                                                <label>
                                                    <input id="rntp-checkbox-<?php echo esc_attr($opt_selected_default_day_automate)?>" name="<?php echo esc_attr($opt_selected_default_day_automate); ?>" type="checkbox" value="true" <?php if( esc_attr( $val_selected_default_day_automate )):?>checked="checked"<?php endif?> />
                                                    <span></span>
                                                </label>
                                            </div>
                                        </div>
                                        <div class="rntp-help-block">
                                            <div class="rntp-help-block-content">
                                                <?php _e('If checked, the calendar will automate the default date selection and products filter action.', 'rentopian-sync')?>
                                            </div>
                                        </div>
                                        <div class="clearfix"></div>
                                    </div>

                                <?php endif; */ ?>

                                <div class="rental-form-group">
                                    <div class="rntp-sync-form-title">
                                        <label class="rental-label" for="rental_default_start_time">
                                            <?php _e('Default Start Time', 'rentopian-sync')?>
                                        </label>
                                    </div>
                                    <div class="rntp-sync-field">
                                        <div class="rntp-input-text">
                                            <input type="text" id="rental_default_start_time"
                                                name="<?php echo esc_attr($opt_default_start_time); ?>"
                                                value="<?php echo esc_attr($val_default_start_time); ?>"
                                            />
                                        </div>
                                    </div>
                                    <div class="rntp-help-block">
                                        <div class="rntp-help-block-content">
                                            <?php _e('Set/Modify Default Start Time', 'rentopian-sync')?>
                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                </div>
                                <div class="rental-form-group">
                                    <div class="rntp-sync-form-title">
                                        <label class="rental-label" for="rental_default_end_time">
                                            <?php _e('Default End Time', 'rentopian-sync')?>
                                        </label>
                                    </div>
                                    <div class="rntp-sync-field">
                                        <div class="rntp-input-text">
                                            <input type="text" id="rental_default_end_time"
                                                name="<?php echo esc_attr($opt_default_end_time); ?>"
                                                value="<?php echo esc_attr($val_default_end_time); ?>"
                                            />
                                        </div>
                                    </div>
                                    <div class="rntp-help-block">
                                        <div class="rntp-help-block-content">
                                            <?php _e('Set/Modify Default End Time', 'rentopian-sync')?>
                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                </div>
                                
                            <?php endif; ?>
                            <div class="rental-inner-title">
                                <h3>Prices Visibility</h3>
                            </div>
                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_hide_product_price)?>">
                                        <?php _e('Hide Product Price', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-checkbox inline">
                                        <label>
                                            <input id="rntp-checkbox-<?php echo esc_attr($opt_hide_product_price)?>"
                                                   name="<?php echo esc_attr($opt_hide_product_price); ?>"
                                                   type="checkbox"
                                                   value="true"
                                                <?php echo $val_hide_product_price ? 'checked="checked"': ''; echo $val_direct_only_bookings? ' disabled': '' ?>/>
                                            <span></span>
                                        </label>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('Hide product prices from visitors, unless direct checkout is enabled, in which case the visitors will still be able to see the products\' prices.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>
                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_show_product_price_only_in_cart)?>">
                                        <?php _e('Show Prices only when items are in cart', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-checkbox inline">
                                        <label>
                                            <input id="rntp-checkbox-<?php echo esc_attr($opt_show_product_price_only_in_cart)?>"
                                                   name="<?php echo esc_attr($opt_show_product_price_only_in_cart); ?>"
                                                   type="checkbox"
                                                   value="true"
                                                <?php echo $val_show_product_price_only_in_cart ? 'checked="checked"': ''; echo $val_hide_product_price? ' disabled': '' ?>/>
                                            <span></span>
                                        </label>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('Show products prices only when items are in cart, unless hide product price is enabled, in which case the visitors will not still be able to see the products\' prices anywhere.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>
                            <?php if ($not_only_sale_products && $not_only_hourly_products) : ?>
                                <div class="rental-form-group">
                                    <div class="rntp-sync-form-title">
                                        <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_hide_damage_waiver)?>">
                                            <?php _e('Hide Damage Waiver', 'rentopian-sync')?>
                                        </label>
                                    </div>
                                    <div class="rntp-sync-field">
                                        <div class="rntp-checkbox inline">
                                            <label>
                                                <input id="rntp-checkbox-<?php echo esc_attr($opt_hide_damage_waiver) ?>" name="<?php echo esc_attr($opt_hide_damage_waiver); ?>" type="checkbox" value="true" <?php if ($val_hide_damage_waiver): ?>checked="checked"<?php endif ?> />
                                                <span></span>
                                            </label>
                                        </div>
                                    </div>
                                    <div class="rntp-help-block">
                                        <div class="rntp-help-block-content">
                                            <?php _e('Hide Damage Waiver block from checkout page and place an order without damage waiver.', 'rentopian-sync')?>
                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                </div>
                                <div class="rental-form-group">
                                    <div class="rntp-sync-form-title">
                                        <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_buy_damage_waiver_by_default); ?>">
                                            <?php _e('Charge the Damage Waiver by Default', 'rentopian-sync')?>
                                        </label>
                                    </div>
                                    <div class="rntp-sync-field">
                                        <div class="rntp-checkbox inline">
                                            <label>
                                                <input id="rntp-checkbox-<?php echo esc_attr($opt_buy_damage_waiver_by_default) ?>" name="<?php echo esc_attr($opt_buy_damage_waiver_by_default); ?>" type="checkbox" value="true" <?php if ($val_buy_damage_waiver_by_default): ?>checked="checked"<?php endif ?> />
                                                <span></span>
                                            </label>
                                        </div>
                                    </div>
                                    <div class="rntp-help-block">
                                        <div class="rntp-help-block-content">
                                            <?php _e('The damage waiver option on the checkout page will be set to "Charge" by default.', 'rentopian-sync'); ?>
                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                </div>
                                <div class="rental-form-group">
                                    <div class="rntp-sync-form-title">
                                        <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_hide_and_buy_damage_waiver_by_default); ?>">
                                            <?php _e('Hide the Damage Waiver and apply by default', 'rentopian-sync')?>
                                        </label>
                                    </div>
                                    <div class="rntp-sync-field">
                                        <div class="rntp-checkbox inline">
                                            <label>
                                                <input id="rntp-checkbox-<?php echo esc_attr($opt_hide_and_buy_damage_waiver_by_default) ?>" name="<?php echo esc_attr($opt_hide_and_buy_damage_waiver_by_default); ?>" type="checkbox" value="true" <?php if ($val_hide_and_buy_damage_waiver_by_default): ?>checked="checked"<?php endif ?> />
                                                <span></span>
                                            </label>
                                        </div>
                                    </div>
                                    <div class="rntp-help-block">
                                        <div class="rntp-help-block-content">
                                            <?php _e('The damage waiver option on the checkout page will be set to "Charge" by default and it will be hidden.', 'rentopian-sync'); ?>
                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                </div>
                            <?php endif; ?>
                            <div class="rental-inner-title">
                                <h3>Delivery</h3>
                            </div>
                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_do_not_use_rentopian_shipping)?>">
                                        <?php _e('Do not use Rentopian shipping', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-checkbox inline">
                                        <label>
                                            <input id="rntp-checkbox-<?php echo esc_attr($opt_do_not_use_rentopian_shipping)?>"
                                                   name="<?php echo esc_attr($opt_do_not_use_rentopian_shipping); ?>"
                                                   type="checkbox"
                                                   value="true"
                                                <?php echo $val_do_not_use_rentopian_shipping ? 'checked="checked"': ''; ?>/>
                                            <span></span>
                                        </label>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('Enable to use an alternative solution to Rentopian shipping, for example use woocommerce shipping or a third party shipping plugin instead.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>
                            <!-- <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php //echo esc_attr($opt_disable_pick_up_option) ?>">
                                        <?php //_e('Disable pick up option', 'rentopian-sync') ?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-checkbox inline">
                                        <label>
                                            <input id="rntp-checkbox-<?php //echo esc_attr($opt_disable_pick_up_option) ?>"
                                                   name="<?php //echo esc_attr($opt_disable_pick_up_option); ?>"
                                                   type="checkbox"
                                                   value="true"
                                                <?php //echo $val_disable_pick_up_option ? 'checked="checked"': ''; ?>/>
                                            <span></span>
                                        </label>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php // _e('Do not allow the customer to choose pick up.', 'rentopian-sync') ?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div> -->
                            <div class="rental-form-group rental-delivery-form-group only-pickup-hide">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_different_pick_up_addresses) ?>">
                                        <?php _e('Different pick up and delivery addresses', 'rentopian-sync') ?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-checkbox inline">
                                        <label>
                                            <input id="rntp-checkbox-<?php echo esc_attr($opt_different_pick_up_addresses) ?>"
                                                   name="<?php echo esc_attr($opt_different_pick_up_addresses); ?>"
                                                   type="checkbox"
                                                   value="true"
                                                <?php echo $val_different_pick_up_addresses ? 'checked="checked"': ''; echo $val_do_not_use_rentopian_shipping? ' disabled': '' ?>/>
                                            <span></span>
                                        </label>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('Enable if you allow rented items delivery address differ from the pick up address.', 'rentopian-sync') ?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>
                            <div class="rental-form-group rental-delivery-form-group only-pickup-hide">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_double_shipping_fee) ?>">
                                        <?php _e('Charge Double the price for delivery', 'rentopian-sync') ?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-checkbox inline">
                                        <label>
                                            <input id="rntp-checkbox-<?php echo esc_attr($opt_double_shipping_fee) ?>"
                                                   name="<?php echo esc_attr($opt_double_shipping_fee); ?>"
                                                   type="checkbox"
                                                   value="true"
                                                <?php echo $val_double_shipping_fee ? 'checked="checked"': ''; echo $val_do_not_use_rentopian_shipping? ' disabled': '' ?>/>
                                            <span></span>
                                        </label>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('Turn on if you want to charge the same fee both for delivery and pickup.', 'rentopian-sync') ?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>
                            <div class="rental-form-group rental-delivery-form-group only-pickup-hide">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_combine_shipping_tax); ?>">
                                        <?php _e('Combined shipping tax', 'rentopian-sync'); ?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-checkbox inline">
                                        <label>
                                            <input id="rntp-checkbox-<?php echo esc_attr($opt_combine_shipping_tax); ?>"
                                                   name="<?php echo esc_attr($opt_combine_shipping_tax); ?>"
                                                   type="checkbox"
                                                   value="true"
                                                <?php echo $val_combine_shipping_tax ? 'checked="checked"': ''; ?>/>
                                            <span></span>
                                        </label>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('Include the shipping tax in the main tax.', 'rentopian-sync'); ?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>
                            <?php

                                // TODO : must be commented out after client websites settings moved to system side

                                $shipping_settings = get_option('rental_shipping_settings', false);
                                if ( $shipping_settings === false ) {
                                    $shipping_settings = rental_curl('shipping/settings', get_option('rental_api_key'));
                                }
                            ?>

                            <div class="rental-form-group rental-delivery-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_google_distance_key)?>">
                                        <?php _e('Google Distance API Key', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-input-text">
                                        <input data-is-mile-based="<?php echo ($shipping_settings->shipping_by === 'mile' || $shipping_settings->shipping_by === 'kilometre') ? 1 : 0; ?>" type="text" id="rntp-checkbox-<?php echo esc_attr($opt_google_distance_key)?>"
                                            name="<?php echo esc_attr($opt_google_distance_key); ?>"
                                            value="<?php echo esc_attr($val_google_distance_key); ?>"/>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php
                                            $gmap_docs = RENTOPIAN_SYNC_DOCUMENTATION_URL.'#google-api-key';
                                            echo sprintf(__( 'Must be specified if you use mileage based delivery option. Detailed instructions for retrieving a key are provided ', 'rentopian-sync').wp_kses( '<a href="%1s" target="_blank">%2s</a>.', array(  'a' => array( 'href' => array(), 'target' => array() ) ) ), esc_url( $gmap_docs ), __( 'here', 'rentopian-sync'));
                                        ?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>

                            <div class="rental-form-group rental-delivery-form-group only-pickup-hide">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_free_shipping_amount)?>">
                                        <?php _e('Free shipping amount', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-input-text">
                                        <input type="number" id="rntp-input-<?php echo esc_attr($opt_free_shipping_amount)?>"
                                               min="0.01" step="0.01"
                                               name="<?php echo esc_attr($opt_free_shipping_amount); ?>"
                                               value="<?php echo esc_attr($val_free_shipping_amount); ?>"/>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('Add an option for free shipping if the order equals or exceeds the sum specified here.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>
                            <div class="rental-form-group rental-delivery-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label">
                                        <?php _e('Pickup / Delivery options', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-radio inline">
                                        <input id="rntp-company-delivery-return"
                                               name="<?php echo esc_attr($opt_pickup_delivery); ?>"
                                               required="required"
                                               type="radio"
                                               value="company_delivery_return"
                                               <?php if( esc_attr( $val_pickup_delivery )  === 'company_delivery_return' ):?>checked="checked"<?php endif?>
                                        />
                                        <label for="rntp-company-delivery-return" class="radio-label">Allow Company Delivery & return only</label>
                                    </div>
                                    <div class="rntp-radio inline">
                                        <input id="rntp-client-pickup-return"
                                               required="required"
                                               name="<?php echo esc_attr($opt_pickup_delivery); ?>"
                                               type="radio"
                                               value="client_pickup_return"
                                               <?php if( esc_attr( $val_pickup_delivery ) === 'client_pickup_return'):?>checked="checked"<?php endif?>
                                        />
                                        <label for="rntp-client-pickup-return" class="radio-label">Allow Client Pickup & return only</label>
                                    </div>
                                    <div class="rntp-radio inline">
                                        <input id="rntp-company-client-delivery-return"
                                               required="required"
                                               name="<?php echo esc_attr($opt_pickup_delivery); ?>"
                                               type="radio"
                                               value="company_client_delivery_return"
                                               <?php if( esc_attr( $val_pickup_delivery ) === 'company_client_delivery_return'):?>checked="checked"<?php endif?>
                                        />
                                        <label for="rntp-company-client-delivery-return" class="radio-label">Allow Both</label>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('Multiple Delivery/Pick Up options for company and clients.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>

                            <?php //if (get_option($opt_do_not_use_rentopian_shipping) == 1): ?>
                                <div class="rental-form-group track-wc-shipping">
                                    <div class="rntp-sync-form-title">
                                        <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_track_wc_shipping)?>">
                                            <?php _e('Track WooCommerce shipping methods', 'rentopian-sync')?>
                                        </label>
                                    </div>
                                    <div class="rntp-sync-field">
                                        <div class="rntp-checkbox inline">
                                            <label>
                                                <input id="rntp-checkbox-<?php echo esc_attr($opt_track_wc_shipping)?>"
                                                    name="<?php echo esc_attr($opt_track_wc_shipping); ?>"
                                                    type="checkbox"
                                                    value="true"
                                                    <?php echo $val_track_wc_shipping ? 'checked="checked"': ''; ?>/>
                                                <span></span>
                                            </label>
                                        </div>
                                    </div>
                                    <div class="rntp-help-block">
                                        <div class="rntp-help-block-content">
                                            <?php _e('Track WooCommerce shipping methods and send them through to Rentopian system. (Only works if "Do not use Rentopian shipping" is enabled.)', 'rentopian-sync')?>
                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                </div>
                            <?php //endif; ?>


                            <div class="rental-inner-title">
                                <h3>Terms and Messages</h3>
                            </div>
                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="special_terms">
                                        <?php _e('Special Terms', 'rentopian-sync'); ?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <?php 
                                        $content = $val_special_terms ? $val_special_terms : '';
                                        $editor_id = 'special_terms';
                                        $settings = array(
                                            'textarea_name' => $opt_special_terms,
                                            'editor_class'  => 'rental-special-terms-editor',
                                            'media_buttons' => false
                                        );
                                        wp_editor( $content, $editor_id, $settings );
                                    ?>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('Text for special terms, appears on checkout page.', 'rentopian-sync'); ?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>

                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label">
                                        <?php _e('Special Terms placement on checkout page', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-radio inline">
                                        <input id="rntp-special-terms-top"
                                               name="<?php echo esc_attr($opt_special_terms_placement); ?>"
                                               required="required"
                                               type="radio"
                                               value="special_terms_on_top"
                                               <?php if( esc_attr( $val_special_terms_placement )  === 'special_terms_on_top' ):?>checked="checked"<?php endif?>
                                        />
                                        <label for="rntp-special-terms-top" class="radio-label"> On the top of checkout page </label>
                                    </div>
                                    <div class="rntp-radio inline">
                                        <input id="rntp-special-terms-bottom"
                                               required="required"
                                               name="<?php echo esc_attr($opt_special_terms_placement); ?>"
                                               type="radio"
                                               value="special_terms_on_bottom"
                                               <?php if( esc_attr( $val_special_terms_placement ) === 'special_terms_on_bottom'):?>checked="checked"<?php endif?>
                                        />
                                        <label for="rntp-special-terms-bottom" class="radio-label"> On the bottom of checkout page </label>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('Special Terms placement on checkout page. <br/> 
                                                - On the top of checkout page (before customer details) <br/>
                                                - On the bottom of checkout page (after customer details)
                                            ', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>


                            <?php if (!get_option('rental_allow_overbook', 1)): ?>
                                <div class="rental-form-group">
                                    <div class="rntp-sync-form-title">
                                        <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_overbook_text)?>">
                                            <?php _e('Overbooked product message', 'rentopian-sync')?>
                                        </label>
                                    </div>
                                    <div class="rntp-sync-field">
                                        <div class="rntp-input-text">
                                            <input type="text" id="rntp-checkbox-<?php echo esc_attr($opt_overbook_text)?>"
                                                   name="<?php echo esc_attr($opt_overbook_text); ?>"
                                                   value="<?php echo esc_attr($val_overbook_text); ?>"/>
                                        </div>
                                    </div>
                                    <div class="rntp-help-block">
                                        <div class="rntp-help-block-content">
                                            <?php _e('Set custom text for an overbooked product.', 'rentopian-sync')?>
                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                </div>
                            <?php endif; ?>

                            <div class="rental-inner-title">
                                <h3><?php _e('Sets', 'rentopian-sync')?></h3>
                            </div>
                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label">
                                        <?php _e('Component Listing Style', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-radio inline">
                                        <input id="rntp-set-listing-standard"
                                               name="<?php echo esc_attr($opt_set_listing_style); ?>"
                                               required="required"
                                               type="radio"
                                               value="standard"
                                               <?php if( esc_attr( $val_set_listing_style )  === 'standard' ):?>checked="checked"<?php endif?>
                                        />
                                        <label for="rntp-set-listing-standard" class="radio-label">Standard</label>
                                    </div>
                                    <div class="rntp-radio inline">
                                        <input id="rntp-set-listing-minimal"
                                               required="required"
                                               name="<?php echo esc_attr($opt_set_listing_style); ?>"
                                               type="radio"
                                               value="minimal"
                                               <?php if( esc_attr( $val_set_listing_style ) === 'minimal'):?>checked="checked"<?php endif?>
                                        />
                                        <label for="rntp-set-listing-minimal" class="radio-label">Minimal</label>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('The standard option displays the image, title and quantity of each set item. The minimal option just the title and quantity right after the title, inside a bracket.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>

                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_hide_set_items)?>">
                                        <?php _e('Hide Set Items', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-checkbox inline">
                                        <label>
                                            <input id="rntp-checkbox-<?php echo esc_attr($opt_hide_set_items)?>"
                                                    name="<?php echo esc_attr($opt_hide_set_items); ?>"
                                                    type="checkbox"
                                                    value="true"
                                                <?php echo $val_hide_set_items? 'checked="checked"': ''; ?>/>
                                            <span></span>
                                        </label>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('If enabled Set Items will be hidden in product single page and cart modal/page.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>


                            <div class="rental-inner-title">
                                <h3><?php _e('Products', 'rentopian-sync')?></h3>
                            </div>
                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_filter_unavailable_products)?>">
                                        <?php _e('Filter unavailable products/variants listing', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-checkbox inline">
                                        <label>
                                            <input id="rntp-checkbox-<?php echo esc_attr($opt_filter_unavailable_products)?>"
                                                    name="<?php echo esc_attr($opt_filter_unavailable_products); ?>"
                                                    type="checkbox"
                                                    value="true"
                                                <?php echo $val_filter_unavailable_products? 'checked="checked"': ''; ?>/>
                                            <span></span>
                                        </label>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('If enabled, unavailable products ,inventory blocked and duplicated products will be filtered in shop/search/category pages.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>

                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_display_sale_products_page)?>">
                                        <?php _e('Display Sale Products page', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-checkbox inline">
                                        <label>
                                            <input id="rntp-checkbox-<?php echo esc_attr($opt_display_sale_products_page)?>"
                                                    name="<?php echo esc_attr($opt_display_sale_products_page); ?>"
                                                    type="checkbox"
                                                    value="true"
                                                <?php echo $val_display_sale_products_page ? 'checked="checked"' : ''; ?>/>
                                            <span></span>
                                        </label>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('If enabled sale products page will be available (/rntp-sale-products/) .', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>

                            <div class="rental-inner-title">
                                <h3>Visual Components</h3>
                            </div>
                            <?php if ($not_only_sale_products && $not_only_hourly_products) : ?>
                                <div class="rental-form-group">
                                    <div class="rntp-sync-form-title">
                                        <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_hide_product_type_label)?>">
                                            <?php _e('Hide Product Type Label', 'rentopian-sync')?>
                                        </label>
                                    </div>
                                    <div class="rntp-sync-field">
                                        <div class="rntp-checkbox inline">
                                            <label>
                                                <input id="rntp-checkbox-<?php echo esc_attr($opt_hide_product_type_label)?>"
                                                       name="<?php echo esc_attr($opt_hide_product_type_label); ?>"
                                                       type="checkbox"
                                                       value="true"
                                                    <?php echo $val_hide_product_type_label? 'checked="checked"': ''; ?>/>
                                                <span></span>
                                            </label>
                                        </div>
                                    </div>
                                    <div class="rntp-help-block">
                                        <div class="rntp-help-block-content">
                                            <?php _e('The label specifying if a product is rented or sold will not be shown.', 'rentopian-sync')?>
                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                </div>
                            <?php endif?>

                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_select_division)?>">
                                        <?php _e('Enable Location selection', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-checkbox inline">
                                        <label>
                                            <input id="rntp-checkbox-<?php echo esc_attr($opt_select_division); ?>"
                                                   name="<?php echo esc_attr($opt_select_division); ?>" type="checkbox"
                                                   <?php if ($val_select_division): ?>checked="checked"<?php endif ?>
                                                   value="true"/>
                                            <span></span>
                                        </label>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('Enable shortcode for location selection.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>

                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_not_open_dates_form)?>">
                                        <?php _e('Do not auto pull the fly-in form', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-checkbox inline">
                                        <label>
                                            <input id="rntp-checkbox-<?php echo esc_attr($opt_not_open_dates_form); ?>"
                                                   name="<?php echo esc_attr($opt_not_open_dates_form); ?>" type="checkbox"
                                                   <?php if ($val_not_open_dates_form): ?>checked="checked"<?php endif ?>
                                                   value="true"/>
                                            <span></span>
                                        </label>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e("Don't pull up the dates form automatically in product page if rental dates are not selected.", 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>
                        </div>

                        <div class="rental-tab">
                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_cart_button_text)?>">
                                        <?php _e('"Cart" alternative label', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-input-text">
                                        <input type="text" id="rntp-checkbox-<?php echo esc_attr($opt_cart_button_text)?>"
                                               name="<?php echo esc_attr($opt_cart_button_text); ?>"
                                               value="<?php echo esc_attr($val_cart_button_text); ?>"/>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('You can set custom text for "Add to cart" button', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>

                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_order_text)?>">
                                        <?php _e('"Order" alternative label', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-input-text">
                                        <input type="text" id="rntp-checkbox-<?php echo esc_attr($opt_order_text)?>"
                                               name="<?php echo esc_attr($opt_order_text); ?>"
                                               value="<?php echo esc_attr($val_order_text); ?>"/>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('Replace the word "Order" anywhere in the website with a custom word.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>

                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_read_more_text)?>">
                                        <?php _e('"Read More" alternative label', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-input-text">
                                        <input type="text" id="rntp-checkbox-<?php echo esc_attr($opt_read_more_text)?>"
                                               name="<?php echo esc_attr($opt_read_more_text); ?>"
                                               value="<?php echo esc_attr($val_read_more_text); ?>"/>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('Replace all occurrences of the button with label "Read More" that shows for products with more than 1 variation or more than 1 option. If nothing is set, "Select Options" will be set.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>

                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_checkout_button_text)?>">
                                        <?php _e('Proceed to checkout button text', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-input-text">
                                        <input type="text" id="rntp-checkbox-<?php echo esc_attr($opt_checkout_button_text)?>"
                                               name="<?php echo esc_attr($opt_checkout_button_text); ?>"
                                               value="<?php echo esc_attr($val_checkout_button_text); ?>"/>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('You can set custom text for "Proceed to checkout" button', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>
                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_order_button_text)?>">
                                        <?php _e('Place order button text', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-input-text">
                                        <input type="text" id="rntp-checkbox-<?php echo esc_attr($opt_order_button_text)?>"
                                               name="<?php echo esc_attr($opt_order_button_text); ?>"
                                               value="<?php echo esc_attr($val_order_button_text); ?>"/>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('You can set custom text for "Place order" button', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>

                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_daily_fee_text)?>">
                                        <?php _e('"Daily Fee" Alternative text', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-input-text">
                                        <input type="text" id="rntp-checkbox-<?php echo esc_attr($opt_daily_fee_text)?>"
                                               name="<?php echo esc_attr($opt_daily_fee_text); ?>"
                                               value="<?php echo isset($val_daily_fee_text) ? esc_attr($val_daily_fee_text) :  __('Daily fee', 'rentopian-sync'); ?>"/>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('Replace the text of the "Daily fee" label with a custom one.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>
                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_tax_text)?>">
                                        <?php _e('"Tax" Alternative text', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-input-text">
                                        <input type="text" id="rntp-checkbox-<?php echo esc_attr($opt_tax_text)?>"
                                               name="<?php echo esc_attr($opt_tax_text); ?>"
                                               value="<?php echo isset($val_tax_text) ? esc_attr($val_tax_text) :  __('Tax', 'rentopian-sync'); ?>"/>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('You can set custom text for "Tax" label', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>
                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_shipping_text)?>">
                                        <?php _e('"Shipping" Alternative text', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-input-text">
                                        <input type="text" id="rntp-checkbox-<?php echo esc_attr($opt_shipping_text)?>"
                                               name="<?php echo esc_attr($opt_shipping_text); ?>"
                                               value="<?php echo isset($val_shipping_text) ? esc_attr($val_shipping_text) :  __('Shipping', 'rentopian-sync'); ?>"/>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('You can set custom text for "Shipping" label', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>
                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_ship_to_dif_adrs_text)?>">
                                        <?php _e('"Ship to a different address?" Alternative text', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-input-text">
                                        <input type="text" id="rntp-checkbox-<?php echo esc_attr($opt_ship_to_dif_adrs_text)?>"
                                               name="<?php echo esc_attr($opt_ship_to_dif_adrs_text); ?>"
                                               value="<?php echo isset($val_ship_to_dif_adrs_text) ? esc_attr($val_ship_to_dif_adrs_text) : ''; ?>"/>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('You can set custom text for "Ship to a different address?" label in Checkout page', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>
                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_select_option_text)?>">
                                        <?php _e('"Please select an option" Alternative text', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-input-text">
                                        <input type="text" id="rntp-checkbox-<?php echo esc_attr($opt_select_option_text)?>"
                                               name="<?php echo esc_attr($opt_select_option_text); ?>"
                                               value="<?php echo isset($val_select_option_text) ? esc_attr($val_select_option_text) :  __('Please select an option', 'rentopian-sync'); ?>"/>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('You can set custom text for "Please select an option" label', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>
                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_start_date_text)?>">
                                        <?php _e('"Start Date" Alternative text', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-input-text">
                                        <input type="text" id="rntp-checkbox-<?php echo esc_attr($opt_start_date_text)?>"
                                               name="<?php echo esc_attr($opt_start_date_text); ?>"
                                               value="<?php echo isset($val_start_date_text) ? esc_attr($val_start_date_text) :  __('Start Date', 'rentopian-sync'); ?>"/>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('You can set custom text for "Start Date" label', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>

                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_end_date_text)?>">
                                        <?php _e('"Return Date" Alternative text', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-input-text">
                                        <input type="text" id="rntp-checkbox-<?php echo esc_attr($opt_end_date_text)?>"
                                               name="<?php echo esc_attr($opt_end_date_text); ?>"
                                               value="<?php echo isset($val_end_date_text) ? esc_attr($val_end_date_text) :  __('Return Date', 'rentopian-sync'); ?>"/>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('You can set custom text for "Return Date" label', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>

                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_proceed_text)?>">
                                        <?php _e('"Proceed" Alternative text', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-input-text">
                                        <input type="text" id="rntp-checkbox-<?php echo esc_attr($opt_proceed_text)?>"
                                               name="<?php echo esc_attr($opt_proceed_text); ?>"
                                               value="<?php echo isset($val_proceed_text) ? esc_attr($val_proceed_text) : ""; ?>"/>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('You can set custom text for "Proceed" label of horizontal form in Checkout page.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>

                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_set_components_text)?>">
                                        <?php _e('"Sets Components" Alternative text', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-input-text">
                                        <input type="text" id="rntp-checkbox-<?php echo esc_attr($opt_set_components_text)?>"
                                               name="<?php echo esc_attr($opt_set_components_text); ?>"
                                               value="<?php echo isset($val_set_components_text) ? esc_attr($val_set_components_text) : "Set Components"; ?>"/>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('If set to blank, the set components table header will not be generated.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>

                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_referral_sources_text)?>">
                                        <?php _e('"Referral Sources" alternative text', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-input-text">
                                        <input type="text" id="rntp-checkbox-<?php echo esc_attr($opt_referral_sources_text)?>"
                                               name="<?php echo esc_attr($opt_referral_sources_text); ?>"
                                               value="<?php echo isset($val_referral_sources_text) ? esc_attr($val_referral_sources_text) : ""; ?>"/>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('You can set custom text for "Referral Sources" label of dropdown list in Checkout page.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>

                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_event_types_text)?>">
                                        <?php _e('"Event Types" alternative text', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-input-text">
                                        <input type="text" id="rntp-checkbox-<?php echo esc_attr($opt_event_types_text)?>"
                                               name="<?php echo esc_attr($opt_event_types_text); ?>"
                                               value="<?php echo isset($val_event_types_text) ? esc_attr($val_event_types_text) : ""; ?>"/>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('You can set custom text for "Event Types" label of dropdown list in Checkout page.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>

                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_miles_text)?>">
                                        <?php _e('"Miles Bases Shipping" alternative text', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-input-text">
                                        <input type="text" id="rntp-checkbox-<?php echo esc_attr($opt_miles_text)?>"
                                               name="<?php echo esc_attr($opt_miles_text); ?>"
                                               value="<?php echo isset($val_miles_text) ? esc_attr($val_miles_text) : ""; ?>"/>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('You can set custom text for "Miles Bases Shipping" label of delivery/shipping section.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>

                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_thank_you_message)?>">
                                        <?php _e('"Order received / Thank You page " alternative message', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-input-text">
                                        <input type="text" id="rntp-checkbox-<?php echo esc_attr($opt_thank_you_message)?>"
                                               name="<?php echo esc_attr($opt_thank_you_message); ?>"
                                               value="<?php echo isset($val_thank_you_message) ? esc_attr($val_thank_you_message) : ""; ?>"/>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('You can set custom text for "Thank You message" in Order received page.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>

                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_payment_tips_text)?>">
                                        <?php _e('"Tip" alternative message', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-input-text">
                                        <input type="text" id="rntp-checkbox-<?php echo esc_attr($opt_payment_tips_text)?>"
                                               name="<?php echo esc_attr($opt_payment_tips_text); ?>"
                                               value="<?php echo isset($val_payment_tips_text) ? esc_attr($val_payment_tips_text) : ""; ?>"/>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('You can set custom text for "Payment Tips" label of quote/order checkout section.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>

                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_billing_details_text)?>">
                                        <?php _e('"Billing Details" alternative message', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-input-text">
                                        <input type="text" id="rntp-checkbox-<?php echo esc_attr($opt_billing_details_text)?>"
                                               name="<?php echo esc_attr($opt_billing_details_text); ?>"
                                               value="<?php echo isset($val_billing_details_text) ? esc_attr($val_billing_details_text) : ""; ?>"/>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('You can set custom text for "Billing Details" label of quote/order checkout section.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>

                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_coupon_label_text)?>">
                                        <?php _e('"Coupon" label alternative text', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-input-text">
                                        <input type="text" id="rntp-checkbox-<?php echo esc_attr($opt_coupon_label_text)?>"
                                               name="<?php echo esc_attr($opt_coupon_label_text); ?>"
                                               value="<?php echo isset($val_coupon_label_text) ? esc_attr($val_coupon_label_text) : ""; ?>"/>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('You can set custom text for "Coupon" label.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>

                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label" for="rntp-checkbox-<?php echo esc_attr($opt_street_address_label_text)?>">
                                        <?php _e('"Street Address" label alternative text', 'rentopian-sync')?>
                                    </label>
                                </div>
                                <div class="rntp-sync-field">
                                    <div class="rntp-input-text">
                                        <input type="text" id="rntp-checkbox-<?php echo esc_attr($opt_street_address_label_text)?>"
                                               name="<?php echo esc_attr($opt_street_address_label_text); ?>"
                                               value="<?php echo isset($val_street_address_label_text) ? esc_attr($val_street_address_label_text) : ""; ?>"/>
                                    </div>
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('You can set custom text for "Street Address" label in Checkout page.', 'rentopian-sync')?>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>

                            
                            
                            
                            
                        </div>

                        <!-- Tab: Calculation Tiers-->
                        <div class="rental-tab">
                            <div class="rental-form-group">
                                <div class="rntp-sync-form-title">
                                    <label class="rental-label">
                                        Days Calculation Tiers
                                    </label>
                                </div>
                                <div class="rntp-sync-field tier-field">
                                    <table id="rental_tiers" class="table table-hover table-bordered rental-log-table">
                                        <thead>
                                        <tr>
                                            <th><?php _e('Minimum Hours', 'rentopian-sync'); ?></th>
                                            <th><?php _e('Maximum Hours', 'rentopian-sync'); ?></th>
                                            <th><?php _e('Days', 'rentopian-sync'); ?></th>
                                            <th><?php _e('Action', 'rentopian-sync'); ?></th>
                                        </tr>
                                        </thead>
                                        <tbody id="rental_tiers_container"></tbody>
                                        <tfoot>
                                        <tr>
                                            <td colspan="4">
                                                <button id="rental_add_tier" type="button" class="btn btn-sm btn-inline-success"><?php _e('Add Another Tier', 'rentopian-sync')?></button>
                                            </td>
                                        </tr>
                                        </tfoot>
                                    </table>
                                    <input type="hidden" name="rental_day_tiers" id="rental_day_tiers" value="<?php echo htmlspecialchars(json_encode($tiers)); ?>">
                                </div>
                                <div class="rntp-help-block">
                                    <div class="rntp-help-block-content">
                                        <?php _e('Please Refer to documentation for this setting\'s usage information: ', 'rentopian-sync')?>
                                        <a href="https://rentopian.com/system-assets/rentopian-sync-documentation#days-calculation-tiers"><?php _e('Days calculation tiers', 'rentopian-sync')?></a>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>
                        </div>

                    </div>
                </div>

                <div class="panel-footer settings-panel-footer">
                    <div class="submit">
                        <button type="submit" id="rental_save_settings" name="submit" class="btn btn-success">
                            <span class="dashicons dashicons-yes"></span><?php _e('Save settings', 'rentopian-sync') ?>
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
    <?php
}

// rental_log_page() displays the page content for the second submenu of the custom Rentopian Log menu
function rental_log_page() {
    global $wpdb, $rental_tables;
    $rental_error_log = $wpdb->prefix . $rental_tables["error_log"];

    $opt_rental_runtime_log = "rental_runtime_log_setting";
    $val_rental_runtime_log = get_option("rental_runtime_log_setting", 2); // 1:enable, 2:disable

    ?>
    <div class="wrap">
        <h2 class="rental-title"><?php _e("Synchronization Results Log", 'rentopian-sync'); ?></h2>
        <hr/>

        <?php
        $log = $wpdb->get_results("SELECT * FROM $rental_error_log WHERE `sync_time` IS NOT NULL ORDER BY `register_time` DESC");
        $sync = [];
        foreach ($log as $l) {
            $sync[$l->sync_time][] = $l;
        }
        ?>
        <div class="rental-sync-log rntp-sync-panel panel-default">
            <div class="panel-heading">
                <h3><?php _e("Synchronization Log", 'rentopian-sync'); ?></h3>
            </div>
            <div class="panel-body">
                <ul>
                    <?php
                    foreach ($sync as $time => $s) {
                        ?>
                        <li data-sync_time="<?php echo $time; ?>">
                            <div class="rental-log-item">
                                <div class="rental-log-title">
                                    <h4><?php _e('Synchronization Run On:', 'rentopian-sync'); ?> <?php echo date('M jS Y, g:i:s A', $time); ?></h4>
                                    <button class="btn btn-icon-fixed btn-inline-danger rental-btn-delete">
                                        <span class="dashicons dashicons-trash"></span>
                                        <?php _e('Delete', 'rentopian-sync'); ?>
                                    </button>
                                    <button class="btn btn-icon-fixed btn-inline-info rental-btn-details">
                                        <span class="dashicons dashicons-visibility"></span>
                                        <?php _e('Details', 'rentopian-sync'); ?>
                                    </button>
                                    <div class="clear-both"></div>
                                </div>
                                <div class="rental-log-details" style="display: none">
                                    <table class="table table-bordered rental-log-table">
                                        <thead>
                                            <tr>
                                                <th><?php _e('Status', 'rentopian-sync'); ?></th>
                                                <th><?php _e('File', 'rentopian-sync'); ?></th>
                                                <th><?php _e('Line', 'rentopian-sync'); ?></th>
                                                <th><?php _e('Message', 'rentopian-sync'); ?></th>
                                                <th><?php _e('Time', 'rentopian-sync'); ?></th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                        <?php
                                        foreach ($s as $item) {
                                            $message = $item->message;
                                            if ($item->data) {
                                                $data = unserialize($item->data);
                                                if (isset($data['start']) && isset($data['limit'])) {
                                                    $message .= "<p>Could not load $data[start]-" . ($data['start'] + $data['limit'])
                                                        . "images, <a class='rental-btn-try-again'>try again!</a></p>";
                                                }
                                            }
                                            echo "<tr data-id='$item->id'>
                                                <td>$item->status</td>
                                                <td>$item->file</td>
                                                <td>$item->line</td>
                                                <td>$message</td>
                                                <td>" . date('M jS Y, g:i:s A', $item->register_time) . "</td>
                                            </tr>";
                                        }
                                        ?>
                                        </tbody>
                                    </table>
                                    <hr/>
                                    <p>
                                        <span class="dashicons dashicons-info"></span>
                                        <?php _e('Total import time:', 'rentopian-sync'); ?>
                                        <?php echo ($s[0]->register_time - $time)?> second(s)
                                    </p>
                                </div>
                            </div>
                        </li>
                        <?php
                    } ?>
                </ul>
            </div>
        </div>
        <div id="rental_orders_log_panel" data-action="rental_paginate_orders_log"  class="rntp-sync-panel panel-default">
            <div class="panel-heading">
                <h3><?php _e('Unregistered Orders', 'rentopian-sync'); ?></h3>
            </div>
            <div class="panel-body">
                <table id="rental_orders_log_table" class="table table-hover table-bordered rental-log-table">
                    <thead>
                    <tr>
                        <th><?php _e('Order Id', 'rentopian-sync'); ?></th>
                        <th><?php _e('Status', 'rentopian-sync'); ?></th>
                        <th><?php _e('Message', 'rentopian-sync'); ?></th>
                        <th><?php _e('Time', 'rentopian-sync'); ?></th>
                        <th><?php _e('Action', 'rentopian-sync'); ?></th>
                    </tr>
                    </thead>
                    <tbody>

                    </tbody>
                </table>
                <div class="rental-pagination"></div>
            </div>
        </div>

        <div id="rntp-log-settings" class="rntp-sync-panel">

            <div class="ajax-alert">
                <strong></strong>
            </div>

            <div class="panel-heading">
                <h3> <?php _e('Runtime Log Settings', 'rentopian-sync')?> </h3>
            </div>

            <div class="panel-body">
                <div class="rental-form-group">
                    <div class="rntp-sync-form-title">
                        <label class="rental-label">
                            <?php _e('Register runtime errors', 'rentopian-sync')?>
                        </label>
                    </div>
                    <div class="rntp-sync-field">
                        <div class="rntp-radio inline">
                            <input id="rntp-form-runtime-log-enable"
                                   name="<?php echo esc_attr($opt_rental_runtime_log); ?>"
                                   required="required"
                                   type="radio"
                                   value="1"
                                   <?php if( esc_attr( $val_rental_runtime_log ) == 1):?>checked="checked"<?php endif?>
                            />
                            <label for="rntp-form-runtime-log-enable" class="radio-label">Enable</label>
                        </div>
                        <div class="rntp-radio inline">
                            <input id="rntp-form-runtime-log-disable"
                                   required="required"
                                   name="<?php echo esc_attr($opt_rental_runtime_log); ?>"
                                   type="radio"
                                   value="0"
                                   <?php if( esc_attr( $val_rental_runtime_log ) == 0):?>checked="checked"<?php endif?>
                            />
                            <label for="rntp-form-runtime-log-disable" class="radio-label">Disable</label>
                        </div>
                    </div>
                    <div class="rntp-help-block">
                        <div class="rntp-help-block-content">
                            <?php _e('Enable this option to log all the systems runtime errors except deprecated errors.', 'rentopian-sync')?>
                        </div>
                    </div>
                    <div class="clearfix"></div>
                </div>
            </div>
            <div class="panel-footer settings-panel-footer log-settings-footer">
                <div class="submit">
                    <button type="submit" id="rental_save_log_settings" name="submit" class="btn btn-success">
                        <span class="dashicons dashicons-yes"></span><?php _e('Save Log settings', 'rentopian-sync') ?>
                    </button>
                </div>
            </div>
        </div>

        <div id="rental_runtime_log_panel" data-action="rental_paginate_runtime_log" class="rntp-sync-panel panel-default">
            <div class="panel-heading">
                <h3><?php _e('Runtime Log', 'rentopian-sync'); ?></h3>
                <button id="rental_delete_runtime_log" class="btn btn-danger" disabled="disabled">
                    <?php _e('Clear Log', 'rentopian-sync'); ?>
                </button>
            </div>
            <div class="panel-body">
                <table id="rental_runtime_log_table" class="table table-hover table-bordered rental-log-table">
                    <thead>
                        <tr>
                            <th><?php _e('Status', 'rentopian-sync'); ?></th>
                            <th><?php _e('File', 'rentopian-sync'); ?></th>
                            <th><?php _e('Line', 'rentopian-sync'); ?></th>
                            <th><?php _e('Message', 'rentopian-sync'); ?></th>
                            <th><?php _e('Time', 'rentopian-sync'); ?></th>
                        </tr>
                    </thead>
                    <tbody>

                    </tbody>
                </table>
                <div class="rental-pagination"></div>
            </div>
        </div>
    </div>
    <?php
}

// function ajax to delete log item
function wp_ajax_rental_delete_log_item() {
    global $wpdb, $rental_tables;
    $rental_error_log = $wpdb->prefix . $rental_tables["error_log"];

    if (isset($_POST['sync_time']) && $_POST['sync_time']) {
        $wpdb->delete($rental_error_log, ['sync_time' => $_POST['sync_time']]);

        if ($wpdb->last_error !== '') {
            throw new RentalException("SQL_ERROR: $wpdb->last_error (SQL: $wpdb->last_query)");
        }

        wp_send_json(true, 200);
    }
    wp_die();
}

// function ajax to delete runtime log
function wp_ajax_rental_delete_runtime_log() {
    global $wpdb, $rental_tables;
    $rental_error_log = $wpdb->prefix . $rental_tables["error_log"];

    if (isset($_POST['delete']) && $_POST['delete']) {
        $wpdb->query("DELETE FROM $rental_error_log WHERE `type` = 0 OR `sync_time` IS NULL");

        if ($wpdb->last_error !== '') {
            throw new RentalException("SQL_ERROR: $wpdb->last_error (SQL: $wpdb->last_query)");
        }

        wp_send_json(true, 200);
    }
    wp_die();
}

// function ajax to delete runtime log
function wp_ajax_rental_save_log_settings() {
    if (isset($_POST['rental_runtime_log_setting'])) {
        update_option('rental_runtime_log_setting', intval($_POST['rental_runtime_log_setting']));
        wp_send_json(true, 200);
    }
    wp_die();
}

function wp_ajax_rental_change_file_sync_type() {
    if (isset($_POST['file_sync_type'])) {

        // 1: base 64 method (old method), 2: nginx method (new method)
        $fileSyncType = $_POST['file_sync_type'] === 'nginx' ? 2 : 1;
        update_option('rental_file_sync_method', $fileSyncType); 

        $deleted_files_result = rental_delete_dynamic_images_batch();

        wp_send_json(["data" => $deleted_files_result, "count" => isset($deleted_files_result['deleted']) ? count($deleted_files_result['deleted']) : 0], 200);
    }
    wp_die();
}

function wp_ajax_rental_delete_orphaned_files() {
    $deleted_files_result = rental_delete_orphaned_files();
    wp_send_json(["data" => $deleted_files_result, "count" => isset($deleted_files_result['deleted']) ? count($deleted_files_result['deleted']) : 0], 200);
    wp_die();
}



// function ajax to pagination runtime log
function wp_ajax_rental_paginate_runtime_log() {
    global $wpdb, $rental_tables;
    $rental_error_log = $wpdb->prefix . $rental_tables["error_log"];

    if (isset($_GET['page'])) {

        $limit = 15;
        $start = ($_GET['page'] - 1) * $limit;
        $row_count = $wpdb->get_var("SELECT COUNT(`id`) FROM $rental_error_log WHERE `type` = 0 OR `sync_time` IS NULL");
        $page_count = ceil($row_count / $limit);
        $log = $wpdb->get_results("SELECT * FROM $rental_error_log WHERE `type` = 0 OR `sync_time` IS NULL ORDER BY `register_time` DESC LIMIT $start, $limit");

        if ($wpdb->last_error !== '') {

            throw new RentalException("SQL_ERROR: $wpdb->last_error (SQL: $wpdb->last_query)");
        }

        wp_send_json(['log' => $log, 'count' => $page_count], 200);
    }

    wp_die();
}

// function ajax to pagination runtime log
function wp_ajax_rental_paginate_orders_log() {
    global $wpdb, $rental_tables;
    $rental_order_relations = $wpdb->prefix . $rental_tables["order_relations"];

    if (isset($_GET['page'])) {

        $limit = 15;
        $start = ($_GET['page'] - 1) * $limit;
        $row_count = $wpdb->get_var("SELECT COUNT(`id`) FROM $rental_order_relations WHERE `rental_id` = 0");
        $page_count = ceil($row_count / $limit);
        $log = $wpdb->get_results("SELECT `id`, `http_code`, `message`, `register_time` FROM $rental_order_relations WHERE `rental_id` = 0 ORDER BY `id` DESC LIMIT $start, $limit");

        if ($wpdb->last_error !== '') {

            throw new RentalException("SQL_ERROR: $wpdb->last_error (SQL: $wpdb->last_query)");
        }

        wp_send_json(['log' => $log, 'count' => $page_count], 200);
    }

    wp_die();
}

// function ajax to resend unregistered order
function wp_ajax_rental_resend_order() {
    global $wpdb, $rental_tables;
    $rental_order_relations = $wpdb->prefix . $rental_tables["order_relations"];

    if ( !isset($_POST["order_id"]) || !$order_id = $_POST["order_id"]) {
        wp_send_json(["message" => "order_id is required"], 400);
        wp_die();
    }

    $data = unserialize($wpdb->get_var("SELECT `data` FROM $rental_order_relations WHERE `id` = $order_id"));
    if (empty($data)) {
        wp_send_json(["message" => "record with id $order_id not found"], 404);
        wp_die();
    }

    $log = rental_send_order($order_id, $data, true);
    if ($log["rental_id"]) {
        rental_pay_order($order_id);
    }

    $log["id"] = $order_id;
    wp_send_json(["log" => $log], 200);
    wp_die();
}

// function ajax which is assigned to try again to upload images that failed to load
function wp_ajax_rental_upload_images_try_again() {
    global $wpdb, $rental_tables;
    $rental_error_log = $wpdb->prefix . $rental_tables["error_log"];

    if (isset($_GET['id']) && ($data = $wpdb->get_var("SELECT data FROM $rental_error_log WHERE `id` = $_GET[id]"))) {
        $data = unserialize($data);
        if (isset($data['start']) && isset($data['limit'])) {
            try {

                rental_upload_images($data['start'], $data['limit']);

                $updated = [
                    'status' => 200,
                    'message' => "Import of images $data[start]-" . ($data['start'] + $data['limit']) . " is completed!",
                    'data' => null
                ];
                $wpdb->update($rental_error_log, $updated, ['id' => $_GET['id']]);
                wp_send_json($updated, 200);

            } catch (RentalException $e) {
                $updated = [
                    'status' => $e->getStatusCode(),
                    'file' => $e->getFile(),
                    'line' => $e->getLine(),
                    'message' => $e->getMessage(),
                ];
                $wpdb->update($rental_error_log, $updated, ['id' => $_GET['id']]);
                wp_send_json($updated, $e->getStatusCode());
            }
        }
    }
    wp_send_json(['message' => 'chka'], 500);

    wp_die();
}

$GlobalFileHandle = null;
// function for send curl
function rental_curl($url, $api_key, $decode = true, $body = null, $write_to_file = null, $check_url_existance = false) {

    if ($check_url_existance) {
        if (!url_exists(rental_url($url))) {
            return false; // Return false instead of stopping execution
        }
    }
   

    if ($write_to_file) {
        global $GlobalFileHandle;
        $GlobalFileHandle = fopen('curl_response.txt', 'w+');
    }
    

    if ($curl = curl_init()) {
        $url = rental_url($url);
        curl_setopt($curl, CURLOPT_URL, $url);
        if ($write_to_file) {
            curl_setopt($curl, CURLOPT_FILE, $GlobalFileHandle);
        }
        

        if ($body) {
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        $domain = get_option('siteurl');
        curl_setopt($curl, CURLOPT_HTTPHEADER, [
            "Accept: application/json",
            "Authorization: bearer $api_key",
            //            "Domain: http://$_SERVER[HTTP_HOST]"
            "Domain: $domain"
        ]);

        if ($write_to_file) {
            curl_setopt($curl, CURLOPT_WRITEFUNCTION, 'curlWriteFile');
        }
        

        $out = curl_exec($curl);
        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);

        if ($write_to_file) {
            fclose($GlobalFileHandle);
        }

        if ($decode) {
            $out = json_decode($out);
        }

        if ($statusCode != 200) {
            if ( !$decode) {
                $out = json_decode($out);
            }
            $message = isset($out->message)? (is_string($out->message)? $out->message: json_encode($out->message)): "status: $statusCode";
            throw new RentalException($message, RentalException::TYPE_SYNC_GLOBAL, $statusCode);
        }

        
        return $out;
    }

    return false;
}

function curlWriteFile($cp, $data) {
    global $GlobalFileHandle;
    $len = fwrite($GlobalFileHandle, $data);
    return $len;
}

// Function to check if a URL exists
function url_exists($url) {
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_NOBODY, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 5); // Set a timeout to prevent long delays
    curl_exec($curl);
    $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);

    return $statusCode >= 200 && $statusCode < 400; // Return true only if the URL responds with a valid status code
}

// function for create rentopian api url
function rental_url($url) {
    global $rental_api_url;

    return $rental_api_url . '/' . $url;
}

// function for removing all products
function rental_empty_products() {
    global $wpdb, $rental_tables;
    $rental_product_relations = $wpdb->prefix . $rental_tables["product_relations"];
    $rental_variant_relations = $wpdb->prefix . $rental_tables["variant_relations"];
    $rental_set_relations = $wpdb->prefix . $rental_tables["set_relations"];
    $rental_category_relations = $wpdb->prefix . $rental_tables["category_relations"];
    $rental_tag_relations = $wpdb->prefix . $rental_tables["tag_relations"];
    $rental_sets_tag_relations = $wpdb->prefix . $rental_tables["sets_tag_relations"];
    $rental_attribute_relations = $wpdb->prefix . $rental_tables["attribute_relations"];
    $rental_brand_relations = $wpdb->prefix . $rental_tables["brand_relations"];
    $rental_image_relations = $wpdb->prefix . $rental_tables["image_relations"];

    $wpdb->query("DELETE FROM $wpdb->terms WHERE term_id IN (SELECT term_id FROM $wpdb->term_taxonomy WHERE taxonomy LIKE 'pa_%' OR taxonomy IN ('product_cat', 'product_tag'))");
    $wpdb->query("DELETE FROM $wpdb->term_taxonomy WHERE taxonomy LIKE 'pa_%' OR taxonomy IN ('product_cat', 'product_tag', 'product_brand')");
    $wpdb->query("DELETE FROM $wpdb->termmeta WHERE term_id NOT IN (SELECT term_id FROM $wpdb->terms)");
    $wpdb->query("DELETE FROM $wpdb->term_relationships WHERE object_id IN (SELECT ID FROM $wpdb->posts WHERE post_type IN ('product','product_variation')) OR
        term_taxonomy_id NOT IN (SELECT term_taxonomy_id FROM $wpdb->term_taxonomy) OR term_taxonomy_id IN (SELECT term_taxonomy_id FROM $wpdb->term_taxonomy WHERE taxonomy IN ('product_type', 'product_visibility'))");
    $wpdb->query("DELETE FROM $wpdb->postmeta WHERE post_id IN (SELECT ID FROM $wpdb->posts WHERE post_type IN ('product','product_variation'))");
    $wpdb->query("DELETE FROM $wpdb->posts WHERE post_type IN ('product','product_variation')");
    //    $wpdb->query("DELETE pm FROM $wpdb->postmeta AS pm LEFT JOIN $wpdb->posts AS wp ON wp.ID = pm.post_id WHERE wp.ID IS NULL");
    $wpdb->query("TRUNCATE TABLE " . $wpdb->prefix . "woocommerce_attribute_taxonomies");
    if (isset($wpdb->wc_product_meta_lookup)) {
        $wpdb->query("TRUNCATE TABLE $wpdb->wc_product_meta_lookup");
    }
    if (defined('ZOO_CW_VERSION')) {
        $wpdb->query("TRUNCATE TABLE " . $wpdb->prefix . "zoo_cw_product_attribute_swatch_type");
    }
    $wpdb->query("TRUNCATE TABLE $rental_product_relations");
    $wpdb->query("TRUNCATE TABLE $rental_variant_relations");
    $wpdb->query("TRUNCATE TABLE $rental_set_relations");
    $wpdb->query("TRUNCATE TABLE $rental_category_relations");
    $wpdb->query("TRUNCATE TABLE $rental_tag_relations");
    $wpdb->query("TRUNCATE TABLE $rental_sets_tag_relations");
    $wpdb->query("TRUNCATE TABLE $rental_attribute_relations");
    $wpdb->query("TRUNCATE TABLE $rental_brand_relations");

    if (get_option('rental_file_sync_method', 1) == 1) {
        // base 64 method
        $wpdb->query("DELETE FROM $rental_image_relations WHERE id NOT IN (SELECT ID FROM $wpdb->posts WHERE post_type = 'attachment')");
    } else {
        // nginx method
        $wpdb->query("TRUNCATE TABLE $rental_image_relations");
    }
    
    $wpdb->query("DELETE FROM $wpdb->options WHERE
        option_name IN ('wc_products_onsale', 'wc_featured_products', 'wc_outofstock_count', 'wc_low_stock_count',
         '_transient_product-transient-version', '_transient_wc_attribute_taxonomies', 'product_cat_children') OR
        option_name LIKE '_transient_timeout_wc_product_children_%' OR
        option_name LIKE '_transient_wc_product_children_%' OR
        option_name LIKE '_transient_timeout_wc_var_prices_%' OR
        option_name LIKE '_transient_wc_var_prices_%' OR
        option_name LIKE '_transient_timeout_wc_child_has_weight_%' OR
        option_name LIKE '_transient_wc_child_has_weight_%' OR
        option_name LIKE '_transient_timeout_wc_child_has_dimensions_%' OR
        option_name LIKE '_transient_wc_child_has_dimensions_%' OR
        option_name LIKE '_transient_timeout_wc_related_%' OR
        option_name LIKE '_transient_wc_related_%'");

    //    update_option('_transient_wc_attribute_taxonomies', []);
    //    update_option('product_cat_children', '');

    if ($wpdb->last_error !== '') {
        throw new RentalException("SQL_ERROR: $wpdb->last_error (SQL: $wpdb->last_query)", RentalException::TYPE_SYNC_GLOBAL);
    }

    return true;
}


function rental_delete_orphaned_files($batch_size = 50, $exclude_ids = []) {
    $deleted = [];
    $failed  = [];

    //
    //  Delete “Unattached” media in batches of 50 
    //
    $paged = 1;
    do {
        $unattached = new WP_Query([
            'post_type'      => 'attachment',
            'post_status'    => 'inherit',
            'posts_per_page' => $batch_size,
            'paged'          => $paged,
            'post_parent'    => 0,
            'fields'         => 'ids',
        ]);
        if (empty($unattached->posts)) {
            break;
        }
        foreach ($unattached->posts as $aid) {
            if (in_array($aid, $exclude_ids, true)) {
                continue;
            }
            if (wp_delete_attachment($aid, true)) {
                $deleted[] = $aid;
            } else {
                $failed[] = $aid;
            }
        }
        wp_reset_postdata();
        $paged++;
    } while ($paged <= $unattached->max_num_pages);

    return [
        'deleted' => $deleted,
        'failed'  => $failed,
    ];
}

function rental_delete_dynamic_images_batch($batch_size = 200, $exclude_ids = []) {
    $deleted = [];
    $failed  = [];
    global $wpdb, $rental_tables;

    //
    //  Delete images attached to products + variations**
    //
    $paged = 1;
    do {
        $products = new WP_Query([
            'post_type'      => ['product','product_variation'],
            'posts_per_page' => $batch_size,
            'paged'          => $paged,
            'fields'         => 'ids',
        ]);
        if (empty($products->posts)) {
            break;
        }
        $att_ids = [];
        foreach ($products->posts as $pid) {
            if (in_array($pid, $exclude_ids, true)) {
                continue;
            }
            // featured
            if ($thumb = get_post_meta($pid, '_thumbnail_id', true)) {
                $att_ids[] = (int)$thumb;
            }
            // WC gallery
            if ($gal = get_post_meta($pid, '_product_image_gallery', true)) {
                foreach (explode(',', $gal) as $aid) {
                    $att_ids[] = (int)$aid;
                }
            }
            // zoo-cw gallery
            if ($zoo = get_post_meta($pid, 'zoo-cw-variation-gallery', true)) {
                foreach (explode(',', $zoo) as $aid) {
                    $att_ids[] = (int)$aid;
                }
            }
        }
        // attachments by post_parent
        $ids_list = implode(',', array_map('intval', $products->posts));
        $parent_atts = $wpdb->get_col("
            SELECT ID
            FROM {$wpdb->posts}
            WHERE post_parent IN ({$ids_list})
              AND post_type = 'attachment'
        ");
        $att_ids = array_filter(array_unique(array_merge($att_ids, $parent_atts)), function($aid) use ($exclude_ids) {
            return $aid && !in_array($aid, $exclude_ids, true);
        });
        foreach ($att_ids as $aid) {
            if (wp_delete_attachment($aid, true)) {
                $deleted[] = $aid;
            } else {
                $failed[] = $aid;
            }
        }
        wp_reset_postdata();
        $paged++;
    } while ($paged <= $products->max_num_pages);

    // Helper for the rest of the relations
    $try_delete = function($aid) use ($exclude_ids, &$deleted, &$failed) {
        if (! $aid || in_array($aid, $exclude_ids, true)) {
            return;
        }
        if (wp_attachment_is_image($aid) && wp_delete_attachment($aid, true)) {
            $deleted[] = $aid;
        } else {
            $failed[] = $aid;
        }
    };

    //
    // rental_image_relations cleanup
    //
    $rel_table = $wpdb->prefix . $rental_tables['image_relations'];
    $offset = 0;
    do {
        $rows = $wpdb->get_results($wpdb->prepare("
            SELECT id FROM {$rel_table}
            LIMIT %d OFFSET %d
        ", $batch_size, $offset));
        if (empty($rows)) {
            break;
        }
        foreach ($rows as $row) {
            $pid = (int)$row->id;
            if ($thumb = get_post_meta($pid, '_thumbnail_id', true)) {
                $try_delete((int)$thumb);
            }
            $atts = get_posts([
                'post_type'      => 'attachment',
                'post_status'    => 'inherit',
                'posts_per_page' => -1,
                'post_parent'    => $pid,
                'fields'         => 'ids',
            ]);
            foreach ($atts as $aid) {
                $try_delete((int)$aid);
            }
        }
        $offset += $batch_size;
    } while (count($rows) === $batch_size);

    //
    //  Term meta cleanup (thumbnails, banners, swatches)
    //
    $taxonomies = ['product_cat','pa_brand','pa_color','pa_size'];
    $meta_keys  = ['thumbnail_id','banner_id','sw_image','slctd_img'];
    foreach ($taxonomies as $tax) {
        $offset = 0;
        do {
            $terms = get_terms([
                'taxonomy'   => $tax,
                'hide_empty' => false,
                'fields'     => 'ids',
                'number'     => $batch_size,
                'offset'     => $offset,
            ]);
            if (is_wp_error($terms) || empty($terms)) {
                break;
            }
            foreach ($terms as $tid) {
                foreach ($meta_keys as $key) {
                    if ($val = get_term_meta($tid, $key, true)) {
                        $try_delete((int)$val);
                    }
                }
            }
            $offset += $batch_size;
        } while (count($terms) === $batch_size);
    }

    //
    //  rental_img_brand_rel OPTION cleanup
    //
    $rel = get_option('rental_img_brand_rel', []);
    if (is_array($rel)) {
        foreach ($rel as $orig => $brands) {
            foreach ((array)$brands as $term_id) {
                $try_delete(get_term_meta($term_id, 'thumbnail_id', true));
            }
        }
    }

    return [
        'deleted' => $deleted,
        'failed'  => $failed,
    ];
}



function rental_empty_yoast() {
    global $wpdb;

    update_option('rental_sync_yoast_seo_plugin_finished', 0);

    $yoast_indexable = $wpdb->prefix . 'yoast_indexable';
    $yoast_indexable_hierarchy = $wpdb->prefix . 'yoast_indexable_hierarchy';
    $yoast_migrations = $wpdb->prefix . 'yoast_migrations';
    $yoast_primary_term = $wpdb->prefix . 'yoast_primary_term';
    $yoast_seo_links = $wpdb->prefix . 'yoast_seo_links';

    $wpdb->query("TRUNCATE TABLE $yoast_indexable");
    $wpdb->query("TRUNCATE TABLE $yoast_indexable_hierarchy");
    $wpdb->query("TRUNCATE TABLE $yoast_migrations");
    $wpdb->query("TRUNCATE TABLE $yoast_primary_term");
    $wpdb->query("TRUNCATE TABLE $yoast_seo_links");

    if ($wpdb->last_error !== '') {
        throw new RentalException("SQL_ERROR: $wpdb->last_error (SQL: $wpdb->last_query)", RentalException::TYPE_SYNC_GLOBAL);
    }

    return true;
}

// function for removing all shipping zones
function rental_empty_shipping_zones() {
    global $wpdb, $rental_tables;
    $woocommerce_shipping_zones = $wpdb->prefix . 'woocommerce_shipping_zones';
    $woocommerce_shipping_zone_locations = $wpdb->prefix . 'woocommerce_shipping_zone_locations';
    $woocommerce_shipping_zone_methods = $wpdb->prefix . 'woocommerce_shipping_zone_methods';
    $rental_shipping_zone_relations = $wpdb->prefix . $rental_tables["shipping_zone_relations"];
    
    $wpdb->query("TRUNCATE TABLE $woocommerce_shipping_zones");
    $wpdb->query("TRUNCATE TABLE $woocommerce_shipping_zone_locations");
    $wpdb->query("TRUNCATE TABLE $woocommerce_shipping_zone_methods");
    $wpdb->query("TRUNCATE TABLE $rental_shipping_zone_relations");

    $wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE 'woocommerce_reduced_rate_%_settings'");

    if ($wpdb->last_error !== '') {
        throw new RentalException("SQL_ERROR: $wpdb->last_error (SQL: $wpdb->last_query)", RentalException::TYPE_SYNC_GLOBAL);
    }

    return true;
}

function rental_empty_inventory_blocks() {
    global $wpdb, $rental_tables;
    $rental_inventory_blocks = $wpdb->prefix . $rental_tables["inventory_blocks"];
    $rental_inventory_block_relations = $wpdb->prefix . $rental_tables["inventory_block_relations"];
   
    if ($wpdb->get_var("show tables like '$rental_inventory_blocks'") == $rental_inventory_blocks) {
        // delete rental_inventory_blocks data
        $wpdb->query("TRUNCATE TABLE $rental_inventory_blocks");
        $wpdb->query("TRUNCATE TABLE $rental_inventory_block_relations");
    }

    if ($wpdb->last_error !== '') {
        throw new RentalException("SQL_ERROR: $wpdb->last_error (SQL: $wpdb->last_query)", RentalException::TYPE_SYNC_GLOBAL);
    }

    return true;
}

function rental_add_inventory_blocks() {
    global $wpdb, $rental_tables;
    $rental_inventory_blocks = $wpdb->prefix . $rental_tables["inventory_blocks"];
    $rental_inventory_block_relations = $wpdb->prefix . $rental_tables["inventory_block_relations"];
    $rental_product_relations = $wpdb->prefix . $rental_tables["product_relations"];
    $rental_variant_relations = $wpdb->prefix . $rental_tables["variant_relations"];

    if ($wpdb->get_var("show tables like '$rental_inventory_blocks'") == $rental_inventory_blocks) {
        $rental_inventory_blocks_sql = '';
        $rental_inventory_block_relations_sql = [];
        $inventory_blocks = json_decode(rental_curl('inventories/blocked', get_option('rental_api_key'), false), true);
        
        if (!empty($inventory_blocks)) {
            // all inventories blocked within date/time rages
            if (!empty($inventory_blocks["all"])) {
                foreach($inventory_blocks["all"] as $key => $inv_block) {
                    $id = $inv_block['id'];
                    $division_id = $inv_block['division_id'];
                    $start_date = $inv_block['start_date'];
                    $end_date = $inv_block['end_date'];
                    $type = $inv_block['type'];

                    $rental_inventory_blocks_sql .= $key == 0 ? "($id, $division_id, $start_date, $end_date, $type)" : ",($id, $division_id, $start_date, $end_date, $type)";
                }
            }

            // specific inventories blocked within date/time rages
            if (!empty($inventory_blocks["specific"])) {
                $wp_product_ids_pack = [];
                $wp_product_variant_ids_pack = [];
                foreach($inventory_blocks["specific"] as $key => $inv_block) {
                    $id = $inv_block['id'];
                    $inventory_id = $inv_block['inventory_id'];
                    $product_id = $inv_block['product_id'];
                    $product_variant_id = $inv_block['product_variant_id'];

                    $sql = "SELECT id FROM {$rental_product_relations} WHERE rental_id = %d";
                    $wp_product_ids = $wpdb->get_col($wpdb->prepare($sql, $product_id));
                    if ($wp_product_ids) {
                        $wp_product_ids_pack[$product_id] = [
                            'block_id' => $id,
                            'wp_product_ids' => $wp_product_ids
                        ];
                    }
                    
                    $sql = "SELECT id FROM {$rental_variant_relations} WHERE rental_id = %d";
                    $wp_variant_ids = $wpdb->get_col($wpdb->prepare($sql, $product_variant_id));
                    if ($wp_variant_ids) {
                        $wp_product_variant_ids_pack[$product_variant_id] = [
                            'block_id' => $id,
                            'wp_variant_ids' => $wp_variant_ids
                        ];
                    }
                    
                }

                if ($wp_product_ids_pack) {
                    foreach($wp_product_ids_pack as $rental_product_id => $data) {
                        $block_id = $data["block_id"];
                        $rental_id = $rental_product_id;
                        $ids = $data["wp_product_ids"];
                        if ($ids) {
                            foreach($ids as $id) {
                                $rental_inventory_block_relations_sql[] = "($block_id, $rental_id, $id)";
                            }
                        }
                    }
                }
                
                if ($wp_product_variant_ids_pack) {
                    foreach($wp_product_variant_ids_pack as $rental_variant_id => $data) {
                        $block_id = $data["block_id"];
                        $rental_id = $rental_variant_id;
                        $ids = $data["wp_variant_ids"];
                        if ($ids) {
                            foreach($ids as $id) {
                                $rental_inventory_block_relations_sql[] = "($block_id, $rental_id, $id)";
                            }
                        }
                    }
                }
                
                if ($rental_inventory_block_relations_sql) {
                    $rental_inventory_block_relations_sql_str = implode(", ", $rental_inventory_block_relations_sql);
                    $wpdb->query("INSERT INTO `$rental_inventory_block_relations` (`block_id`, `rental_id`, `id`) VALUES " . $rental_inventory_block_relations_sql_str);
                }
               
            }

            // rental inventory blocks
            if($rental_inventory_blocks_sql){
                $wpdb->query("INSERT INTO `$rental_inventory_blocks` (`id`, `division_id`, `start_date`, `end_date`, `type`) VALUES " . $rental_inventory_blocks_sql);
            }
       }

        if ($wpdb->last_error !== '') {
            throw new RentalException("SQL_ERROR: $wpdb->last_error (SQL: $wpdb->last_query)", RentalException::TYPE_SYNC_GLOBAL);
        }
    }
    return true;
}

function rental_empty_set_options() {
    global $wpdb, $rental_tables;
    $rental_set_options = $wpdb->prefix . $rental_tables["set_options"];
    $rental_set_option_relations = $wpdb->prefix . $rental_tables["set_option_relations"];
   
    if ($wpdb->get_var("show tables like '$rental_set_option_relations'") == $rental_set_option_relations) {
        // delete rental_product_options data
        $wpdb->query("TRUNCATE TABLE $rental_set_options");
        $wpdb->query("TRUNCATE TABLE $rental_set_option_relations");
    }

    if ($wpdb->last_error !== '') {
        throw new RentalException("SQL_ERROR: $wpdb->last_error (SQL: $wpdb->last_query)", RentalException::TYPE_SYNC_GLOBAL);
    }

    return true;
}

function rental_add_set_options() {
    global $wpdb, $rental_tables;
    $rental_set_options = $wpdb->prefix . $rental_tables["set_options"];
    $rental_set_option_relations = $wpdb->prefix . $rental_tables["set_option_relations"];
    $rental_set_relations = $wpdb->prefix . $rental_tables["set_relations"];
    $rental_set_options_sql = '';
    $rental_set_option_relations_sql = '';
    $setmeta_sql = [];

    if ($wpdb->get_var("show tables like '$rental_set_option_relations'") == $rental_set_option_relations) {
        $sets_options = json_decode(rental_curl('inventories/sets/options', get_option('rental_api_key'), false), true);

        if ($sets_options) {

            // collect every division's rental product ids
            $sql = "SELECT id, rental_id FROM {$rental_set_relations}";
            $set_ids = $wpdb->get_results($sql, ARRAY_A);

            $attached_items_grouped = [];
            foreach($sets_options as $key=>$option) {

                $id = $option["id"];
                // grouping attached sets based on option id
                $attached_sets = isset($option["attached_sets"]) ? json_decode($option["attached_sets"]) : '';

                $attached_items_grouped[$id] = [
                    'sets' => $attached_sets,
                ];

                $title = $option["title"];
                $once_per_order = $option["once_per_order"];
                $values = $option["values"];
                $values_encoded = json_encode($values);

                // rental_set_options sql values (insert each row into rental_set_options table)
                $rental_set_options_sql .= $key == 0 ? "($id, '$title', '$once_per_order', '$values_encoded')" : ",($id, '$title', '$once_per_order', '$values_encoded')";
            }

            // each option's attached sets relation
            $_option_ids = [];
            foreach($attached_items_grouped as $option_id=>$items) {
                
                $set_wp_id_collection = [];
                // collecting wp product ids related to rental product ids for the current option
                if (!empty($items['sets'])) {
                    foreach($set_ids as $sid) {
                        if (in_array($sid["rental_id"], $items['sets'])) {
                            // supporting all divisions
                            $set_wp_id_collection[$sid["rental_id"]][] = $sid["id"];
                        }
                    }
                }

                if (!empty($set_wp_id_collection)) {
                    // sql values of the option sets
                    foreach ($set_wp_id_collection as $rental_set_id => $wp_id_list) {
                        foreach($wp_id_list as $wp_id) {
                            $_option_ids[$wp_id][] = $option_id;

                            // set option relation sql
                            $rental_set_option_relations_sql .= empty($rental_set_option_relations_sql) ? "('$option_id', '$rental_set_id', '$wp_id')" : ",('$option_id', '$rental_set_id', '$wp_id')";
                        }
                    }
                }

            }

            $wpdb->query("INSERT INTO `$rental_set_options` (`id`, `title`, `once_per_order`, `option_values`) VALUES " . $rental_set_options_sql);
            if ($rental_set_option_relations_sql) {
                $wpdb->query("INSERT INTO `$rental_set_option_relations` (`set_option_id`, `rental_id`, `wp_id`) VALUES " . $rental_set_option_relations_sql);
            
                foreach($_option_ids as $wp_id => $option_ids) {
                    $option_ids_rearranged = array_values(array_unique($option_ids));
                    $option_ids = json_encode($option_ids_rearranged);
                    $setmeta_sql[$wp_id] = "($wp_id, '_set_options', '$option_ids')";
                }
                rental_insert("INSERT INTO `$wpdb->postmeta` (`post_id`, `meta_key`, `meta_value`) VALUES", $setmeta_sql);
            }

            if ($wpdb->last_error !== '') {
                throw new RentalException("SQL_ERROR: $wpdb->last_error (SQL: $wpdb->last_query)", RentalException::TYPE_SYNC_GLOBAL);
            }
        }
    }
    return true;

}

function rental_empty_product_options() {
    global $wpdb, $rental_tables;
    $rental_product_options = $wpdb->prefix . $rental_tables["product_options"];
    $rental_product_option_relations = $wpdb->prefix . $rental_tables["product_option_relations"];
   
    if ($wpdb->get_var("show tables like '$rental_product_option_relations'") == $rental_product_option_relations) {
        // delete rental_product_options data
        $wpdb->query("TRUNCATE TABLE $rental_product_options");
        $wpdb->query("TRUNCATE TABLE $rental_product_option_relations");
    }

    if ($wpdb->last_error !== '') {
        throw new RentalException("SQL_ERROR: $wpdb->last_error (SQL: $wpdb->last_query)", RentalException::TYPE_SYNC_GLOBAL);
    }

    return true;
}

function rental_add_product_options() {
    global $wpdb, $rental_tables;
    $rental_product_options = $wpdb->prefix . $rental_tables["product_options"];
    $rental_product_option_relations = $wpdb->prefix . $rental_tables["product_option_relations"];
    $rental_product_relations = $wpdb->prefix . $rental_tables["product_relations"];
    $rental_category_relations = $wpdb->prefix . $rental_tables["category_relations"];
    $rental_product_options_sql = '';
    $rental_product_option_relations_sql = '';
    $productmeta_sql = [];

    if ($wpdb->get_var("show tables like '$rental_product_option_relations'") == $rental_product_option_relations) {
        $product_options = json_decode(rental_curl('products/options', get_option('rental_api_key'), false), true);

        if (!empty($product_options)) {

            // collect every division's rental product ids
            $sql = "SELECT id, rental_id FROM {$rental_product_relations}";
            $product_ids = $wpdb->get_results($sql, ARRAY_A);
            // collect rental category ids
            $sql2 = "SELECT id, rental_id FROM {$rental_category_relations}";
            $category_ids = $wpdb->get_results($sql2, ARRAY_A);

            $attached_items_grouped = [];
            // $values_grouped = [];
            foreach($product_options as $key=>$option) {

                $id = $option["id"];
                // grouping attached products and categories based on option id
                $attached_products = isset($option["attached_products"]) ? json_decode($option["attached_products"]) : '';
                $attached_categories = isset($option["attached_cats"]) ? json_decode($option["attached_cats"]) : '';


                $attached_items_grouped[$id] = [
                    'products' => $attached_products,
                    'cats' => $attached_categories,
                ];


                $title = $option["title"];
                $once_per_order = $option["once_per_order"];
                $values = $option["values"];
                $values_encoded = json_encode($values);

                // rental_product_options sql values (insert each row into rental_product_options table)
                $rental_product_options_sql .= $key == 0 ? "($id, '$title', '$once_per_order', '$values_encoded')" : ",($id, '$title', '$once_per_order', '$values_encoded')";
            }


            // each option's attached products and categories relation
            $_option_ids = [];
            foreach($attached_items_grouped as $option_id=>$items) {
                
                $cats_wp_id_collection = [];
                $cats_rental_wp_id_collection = [];
                $product_wp_id_collection = [];
                // collecting wp product ids related to rental product ids for the current option
                if (!empty($items['products'])) {
                    foreach($product_ids as $pid) {
                        if (in_array($pid["rental_id"], $items['products'])) {
                            // suporting all divisions
                            $product_wp_id_collection[$pid["rental_id"]][] = $pid["id"];
                        }
                    }
                }

                $category_product_ids=[];
                // collecting wp cat ids related to rental cat ids for the current option
                if (!empty($items['cats'])) {
                    // group wp products by rental category id
                    foreach($category_ids as $cid) {
                        if ( in_array($cid["rental_id"], $items['cats']) ) {
                            $cats_rental_wp_id_collection[$cid["rental_id"]] = $cid["id"];
                            $cats_wp_id_collection[] = $cid["id"];
                        }
                    }

                    if ($cats_wp_id_collection) {
                        $placeholders = array_fill(0, count($cats_wp_id_collection), '%d');
                        $placeholders_format = implode(', ', $placeholders);
                        $sql = "
                            SELECT 
                                object_id
                            FROM 
                                {$wpdb->term_relationships} terms
                            LEFT JOIN {$wpdb->posts} posts ON posts.id = terms.object_id
                            WHERE
                                term_taxonomy_id IN ({$placeholders_format})
                                AND posts.post_type = 'product'
                                AND posts.post_status = 'publish'
                        ";
                        $product_ids_by_category_ids = $wpdb->get_results($wpdb->prepare($sql, $cats_wp_id_collection), ARRAY_A);
        
                        if ($product_ids_by_category_ids) {
                            foreach($product_ids_by_category_ids as $pid) {
                                $category_product_ids[] = $pid["object_id"];
                            }
                        }
                    }
                }


                if (!empty($product_wp_id_collection)) {
                    // sql values of the option products (type 1 = product)
                    foreach ($product_wp_id_collection as $rental_product_id => $wp_id_list) {
                        foreach($wp_id_list as $wp_id) {
                            $_option_ids[$wp_id][] = $option_id;

                            // product option relation sql
                            $rental_product_option_relations_sql .= empty($rental_product_option_relations_sql) ? "('$option_id', '$rental_product_id', '$wp_id', '1')" : ",('$option_id', '$rental_product_id', '$wp_id', '1')";
                        }
                    }
                }

            
                if (!empty($category_product_ids)) {
                    foreach ($category_product_ids as $wp_id) {
                        $_option_ids[$wp_id][] = $option_id;
                    }
                }

                if (!empty($cats_rental_wp_id_collection)) {
                    // sql values of the option categories (type 2 = category)
                    foreach ($cats_rental_wp_id_collection as $rental_cat_id => $wp_cat_id) {
                        $rental_product_option_relations_sql .= empty($rental_product_option_relations_sql) ? "('$option_id', '$rental_cat_id', '$wp_cat_id', '2')" : ",('$option_id', '$rental_cat_id', '$wp_cat_id', '2')";
                    }
                }
            }

            $wpdb->query("INSERT INTO `$rental_product_options` (`id`, `title`, `once_per_order`, `option_values`) VALUES " . $rental_product_options_sql);
            if ($rental_product_option_relations_sql) {
                $wpdb->query("INSERT INTO `$rental_product_option_relations` (`po_id`, `rental_id`, `wp_id`, `type`) VALUES " . $rental_product_option_relations_sql);
            
                foreach($_option_ids as $wp_id => $option_ids) {
                    $option_ids_rearranged = array_values(array_unique($option_ids));
                    $option_ids = json_encode($option_ids_rearranged);
                    $productmeta_sql[$wp_id] = "($wp_id, '_product_options', '$option_ids')";
                }
                rental_insert("INSERT INTO `$wpdb->postmeta` (`post_id`, `meta_key`, `meta_value`) VALUES", $productmeta_sql);
            }

            if ($wpdb->last_error !== '') {
                throw new RentalException("SQL_ERROR: $wpdb->last_error (SQL: $wpdb->last_query)", RentalException::TYPE_SYNC_GLOBAL);
            }
        }
    }
    return true;
}

function rental_set_no_customer_pickup_items($shipping_settings) {

    update_option('no_customer_pickup_products_list', []);
    
    if ($shipping_settings && isset($shipping_settings->no_customer_pickup)) {

        global $wpdb, $rental_tables;
        $rental_product_relations = $wpdb->prefix . $rental_tables["product_relations"];
        $rental_category_relations = $wpdb->prefix . $rental_tables["category_relations"];

        $rental_no_customer_pickup_product_ids = $shipping_settings->no_customer_pickup_products;
        $rental_no_customer_pickup_category_ids = $shipping_settings->no_customer_pickup_categories;

        // collect every division's rental product ids
        $sql = "SELECT id, rental_id FROM {$rental_product_relations}";
        $product_ids = $wpdb->get_results($sql, ARRAY_A);
        // collect rental category ids
        $sql2 = "SELECT id, rental_id FROM {$rental_category_relations}";
        $category_ids = $wpdb->get_results($sql2, ARRAY_A);


        if (
            $shipping_settings->no_customer_pickup == 1
            && (
                $rental_no_customer_pickup_product_ids 
                || $rental_no_customer_pickup_category_ids
            )
        ) {

            $cats_wp_id_collection = [];
            $cats_rental_id_mapper_collection = [];
            $product_wp_id_collection = [];
            
            if ($rental_no_customer_pickup_product_ids) {
                // collecting wp product ids related to rental product ids for the current option
                foreach($product_ids as $pid) {
                    if (in_array($pid["rental_id"], $rental_no_customer_pickup_product_ids)) {
                        // suporting all divisions
                        $product_wp_id_collection[$pid["rental_id"]][] = $pid["id"];
                    }
                }
            }


            $category_product_ids = [];
            
            if ($rental_no_customer_pickup_category_ids) {

                // collecting wp cat ids related to rental cat ids for the current option
                // group wp products by rental category id
                foreach($category_ids as $cid) {
                    if ( in_array($cid["rental_id"], $rental_no_customer_pickup_category_ids) ) {
                        
                        $cats_rental_id_mapper_collection[$cid["id"]] = $cid["rental_id"];

                        $cats_wp_id_collection[] = $cid["id"];
                    }
                }

                if ($cats_wp_id_collection) {
                    $placeholders = array_fill(0, count($cats_wp_id_collection), '%d');
                    $placeholders_format = implode(', ', $placeholders);
                    $sql = "
                        SELECT 
                            object_id
                        FROM 
                            {$wpdb->term_relationships} terms
                        LEFT JOIN {$wpdb->posts} posts ON posts.id = terms.object_id
                        WHERE
                            term_taxonomy_id IN ({$placeholders_format})
                            AND posts.post_type = 'product'
                            AND posts.post_status = 'publish'
                    ";
                    $product_ids_by_category_ids = $wpdb->get_results($wpdb->prepare($sql, $cats_wp_id_collection), ARRAY_A);

                    if ($product_ids_by_category_ids) {
                        foreach($product_ids_by_category_ids as $pid) {
                            $category_product_ids[] = $pid["object_id"];
                        }
                    }
                }
            }

            $wp_no_customer_pickup_products = [];
            if ($product_wp_id_collection) {
                foreach ($product_wp_id_collection as $rental_product_id => $wp_id_list) {
                    foreach($wp_id_list as $wp_id) {

                        $wp_no_customer_pickup_products[] = $wp_id;
                    }
                }
            }

            if ($category_product_ids) {
                foreach ($category_product_ids as $wp_id) {

                    $wp_no_customer_pickup_products[] = $wp_id;
                }
            }
                
            
            if ($wp_no_customer_pickup_products) {

                update_option('no_customer_pickup_products_list', $wp_no_customer_pickup_products);
            }
            
        } 

        // exclude the rest of the products
        if ($shipping_settings->no_customer_pickup == 0 && !$rental_no_customer_pickup_product_ids && !$rental_no_customer_pickup_category_ids) {
            update_option('no_customer_pickup_products_list', []);
        }
        
    }
}

function rental_empty_price_multipliers() {
    global $wpdb, $rental_tables;
    $rental_price_multipliers = $wpdb->prefix . $rental_tables["price_multipliers"];
   
    // delete rental_price_multipliers data
    $wpdb->query("TRUNCATE TABLE $rental_price_multipliers");

    // delete _price_multiplier_id (from wp_postmeta)
    $delete_query = "
        DELETE 
            pm
        FROM
            $wpdb->postmeta pm
        WHERE
            pm.meta_key = '_price_multiplier_id'
    ";
    $wpdb->query($delete_query);

    if ($wpdb->last_error !== '') {
        throw new RentalException("SQL_ERROR: $wpdb->last_error (SQL: $wpdb->last_query)", RentalException::TYPE_SYNC_GLOBAL);
    }

    return true;
}

function rental_add_price_multipliers() {
    global $wpdb, $rental_tables;
    $rental_price_multipliers = $wpdb->prefix . $rental_tables["price_multipliers"];
    $rental_price_multipliers_sql = '';

    if ($wpdb->get_var("show tables like '$rental_price_multipliers'") == $rental_price_multipliers) {
        $price_multipliers = json_decode(rental_curl('price_multipliers', get_option('rental_api_key'), false), true);
        if (!empty($price_multipliers)) {
    
            foreach($price_multipliers as $key=>$price_multiplier) {
    
                $id = $price_multiplier["id"];
                $title = $price_multiplier["title"];
                $slug = $price_multiplier["slug"];
                $is_monthly = isset($price_multiplier["is_monthly"]) ? $price_multiplier["is_monthly"] : 0;
                $is_repeat = isset($price_multiplier["is_repeat"]) ? $price_multiplier["is_repeat"] : 0;
                // $items = addslashes(serialize($price_multiplier["items"]));
                $items = serialize($price_multiplier["items"]);
                // rental price_multipliers sql values (insert each row into rental_price_multipliers table)
                if ($key == 0) {
                    $rental_price_multipliers_sql .= "($id, '$title', '$slug', '$is_monthly', '$is_repeat', '$items')";
                    continue;
                }
                $rental_price_multipliers_sql .= ",($id, '$title', '$slug', '$is_monthly', '$is_repeat', '$items')";
            }
    
            // rental price multipliers sql (insert into rental_price_multipliers table)
            $wpdb->query("INSERT INTO `$rental_price_multipliers` (`id`, `title`, `slug`, `is_monthly`, `is_repeat`, `items`) VALUES " . $rental_price_multipliers_sql);
        
            if ($wpdb->last_error !== '') {
                throw new RentalException("SQL_ERROR: $wpdb->last_error (SQL: $wpdb->last_query)", RentalException::TYPE_SYNC_GLOBAL);
            }
        }
    }
    return true;
}

// function for removing all coupons/rental_coupon_relations
function rental_empty_coupons() {
    global $wpdb, $rental_tables;
    $rental_coupon_relations = $wpdb->prefix . $rental_tables["coupon_relations"];
   
    // delete coupon rental relation
    $wpdb->query("TRUNCATE TABLE $rental_coupon_relations");

    // delete coupon (from wp_posts)
    $delete_query = "
        DELETE 
            p, pm
        FROM
            $wpdb->posts p
        LEFT JOIN $wpdb->postmeta pm ON pm.post_id = p.ID
        WHERE
            p.post_type = 'shop_coupon'
    ";
    $wpdb->query($delete_query);

    if ($wpdb->last_error !== '') {
        throw new RentalException("SQL_ERROR: $wpdb->last_error (SQL: $wpdb->last_query)", RentalException::TYPE_SYNC_GLOBAL);
    }

    return true;
}

function rental_add_coupons($last_insert_id, $exclude_product_ids = '') {
    global $wpdb, $rental_tables;
    $rental_coupon_relations = $wpdb->prefix . $rental_tables["coupon_relations"];
    $api_key = get_option('rental_api_key');
    $coupons_wp_posts_sql = [];
    $coupons_wp_postmeta_sql = [];
    $rental_coupon_relations_sql = [];

    $domain = get_option('siteurl');
    $date = date('Y-m-d H:i:s');
    $gmdate = gmdate('Y-m-d H:i:s');

    // add WP tables coupons data
    $rental_coupons = rental_curl('coupons', $api_key);

    if (!empty($rental_coupons)) {

        foreach($rental_coupons as $coupon) {
            $last_insert_id++;
    
            $slug = addslashes($coupon->coupon_id);
            $description = isset($coupon->description) ? esc_sql($coupon->description) : '';
    
            $post_status = $coupon->status == 1 ? 'publish' : 'trash';
            // rental coupons sql values (insert into wp_posts)
            $coupons_wp_posts_sql[$last_insert_id] = "($last_insert_id, 1, '$date', '$gmdate', '" . addslashes($coupon->coupon_id) . "',
            ' ', '$description', '$post_status', 'closed', 'closed',
            '$slug', '', '', '$date', '$gmdate', '', 0, '$domain/?post_type=shop_coupon&p=$last_insert_id', 'shop_coupon')";
    
            
            $discount_type = ($coupon->unit == 1) ? 'percent' : (($coupon->unit == 2) ? 'fixed_cart' : 'percent');
            $coupon_amount = $coupon->target;
            $usage_limit = !empty($coupon->unlimited_qty) ? '99999' : $coupon->quantity;
            $usage_limit_per_user = (!empty($coupon->coupon_use) && $coupon->coupon_use != 1) ? '99999' : 1;
            $date_expires = !empty($coupon->no_expiry) ? strtotime(date('Y-m-d', strtotime('+10 years'))) : $coupon->end_date;
    
            // rental coupons sql values (insert into wp_postmeta)
            $coupons_wp_postmeta_sql[$last_insert_id] = "($last_insert_id, 'discount_type', '$discount_type' ),
                ($last_insert_id, 'coupon_amount', '$coupon_amount'),
                ($last_insert_id, 'usage_limit', '$usage_limit'),
                ($last_insert_id, 'usage_limit_per_user', '$usage_limit_per_user'),
                ($last_insert_id, 'limit_usage_to_x_items', 0),
                ($last_insert_id, 'date_expires', '$date_expires'),
                ($last_insert_id, 'individual_use', 'yes'),
                ($last_insert_id, 'usage_count', 0),
                ($last_insert_id, 'free_shipping', 'no'),
                ($last_insert_id, 'exclude_sale_items', 'no')";

                if (!empty($exclude_product_ids)) {
                    $coupons_wp_postmeta_sql[$last_insert_id] .= ",($last_insert_id, 'exclude_product_ids', '$exclude_product_ids')";  
                }
    
                 
            $divisions = '';
            if (!empty($coupon->divisions) && !$coupon->all_divisions) {
                $divisions = $coupon->divisions;
            } else if ($coupon->all_divisions) {
                $divisions = 'all';
            }
            // rental coupon relations sql values (insert each row into rental relations table)
            $rental_coupon_relations_sql[] = "($last_insert_id, $coupon->id, '$divisions')";
        }
        
    
        // rental coupons sql (insert into wp_posts)
        rental_insert("INSERT INTO `$wpdb->posts` (`id`, `post_author`, `post_date`,
                    `post_date_gmt`, `post_title`, `post_content`, `post_excerpt`, `post_status`,
                    `comment_status`, `ping_status`, `post_name`, `to_ping`, `pinged`, `post_modified`,
                    `post_modified_gmt`, `post_content_filtered`, `post_parent`, `guid`,`post_type`) VALUES ", $coupons_wp_posts_sql);
        
        // rental coupons sql (insert into wp_postmeta)
        rental_insert("INSERT INTO `$wpdb->postmeta` (`post_id`, `meta_key`, `meta_value`) VALUES", $coupons_wp_postmeta_sql);
    
        // rental coupon relations sql (insert into rental_coupon_relations table)
        $wpdb->query("INSERT INTO `$rental_coupon_relations` (`id`, `rental_id`, `rental_coupon_divisions`) VALUES " . implode(", ", $rental_coupon_relations_sql));
    

        // enable coupon options (link : root/wp-admin/admin.php?page=wc-settings -> Enable coupons)
        update_option('woocommerce_enable_coupons', 'yes');
        update_option('woocommerce_calc_discounts_sequentially', 'no');
        
    
        if ($wpdb->last_error !== '') {
            throw new RentalException("SQL_ERROR: $wpdb->last_error (SQL: $wpdb->last_query)", RentalException::TYPE_SYNC_GLOBAL);
        }
    }

    return $last_insert_id;
}

// function for sync company settings
function rental_sync_company_settings($api_key) {
    $settings = rental_curl('settings/company', $api_key);

    //Check if overbooks are allowed and save right away. Then compare before any availability checks.
    //If allowed, do not check for availability.
    update_option('rental_allow_overbook', $settings->allow_overbook);

    if (isset($settings->product_type)) {
        update_option('rental_synchronized_product_type', $settings->product_type);
        if (
            $settings->product_type == 'sale'
            || $settings->product_type == 'hourly'
        ) {
            update_option('rental_hide_zip', 1);
            update_option('rental_event_start_time', 0);
            update_option('rental_hide_end_date', 1);
            update_option('rental_hide_time_pickers', 1);
            update_option('rental_min_start_date', '');
            update_option('rental_min_dates_range', '');
            update_option('rental_max_dates_range', '');
            update_option('rental_hide_damage_waiver', 1);
            update_option('rental_buy_damage_waiver_by_default', 0);

            // unset cookies related to daily rental
            if (isset($_COOKIE['rental_start_date'])) {
                unset($_COOKIE['rental_start_date']);
                setcookie('rental_start_date', '', time() - (31556952), "/", "", false, true);
            }

            if (isset($_COOKIE['rental_end_date'])) {
                unset($_COOKIE['rental_end_date']);
                setcookie('rental_end_date', '', time() - (31556952), "/", "", false, true);
            }

            $start_end_date_expire_time = time() + RENTOPIAN_DATE_EXPIRE_TIME;

            $encrypted_rental_zip = encrypt_data(true, get_option('rental_encryption_key'));
            $_COOKIE['rental_zip'] = $encrypted_rental_zip;
            setcookie('rental_zip', $encrypted_rental_zip, $start_end_date_expire_time, "/", "", false, false);

            // $_COOKIE['rental_zip'] = true;
            // setcookie('rental_zip', true, time() + (10800), "/", "", false, false);

        } else {
            // rental type
            if (isset($_COOKIE['rental_hourly_mode'])) {
                unset($_COOKIE['rental_hourly_mode']);
                setcookie('rental_hourly_mode', false, time() - (31556952), "/", "", false, false);
            }
        }

    } else {
        // all type
        if (isset($_COOKIE['rental_hourly_mode'])) {
            unset($_COOKIE['rental_hourly_mode']);
            setcookie('rental_hourly_mode', false, time() - (31556952), "/", "", false, false);
        }
        update_option('rental_synchronized_product_type', 'all');
    }
    update_option('rental_inactive_inv_by_quantity', !empty($settings->inactive_inv_by_quantity));
    if (isset($settings->theme_options)) {
        rental_set_theme_options($settings->theme_options);
    }

    if (isset($settings->auto_tax)) {
        // rental_tax_type : 1 = manual, 2 = auto tax  
        update_option('rental_tax_type', $settings->auto_tax == 1 ? 2 : 1);
    }

    return $settings;
}

// function for sync company divisions
function rental_sync_divisions($api_key) {
    $divisions = rental_curl('divisions', $api_key);
    update_option('rental_divisions', $divisions);

    // if (count($divisions) < 2) {
    //     $division = $divisions[0];

    //     update_option('rental_system_main_division', $division);

    // } else {

    //     foreach($divisions as $division) {

    //         if ($division->main_division == 1) {

    //             update_option('rental_system_main_division', $division);
    //         }
    //     }
    // }

}

// sync company main division address into woocommerce->settings->general section
function rental_sync_main_division_address($divisions) {
    
    if (count($divisions) < 2) {
        $division = $divisions[0];

        $address =  $division->address;
        update_option('woocommerce_store_address', $address->address);
        update_option('woocommerce_store_address_2', $address->address_2);
        update_option('woocommerce_store_city', $address->city);

        $country = empty($address->country) ? 'US' : $address->country;
        if (!empty($address->state)) {
            update_option('woocommerce_default_country', $country.':'.$address->state);
        } else {
            update_option('woocommerce_default_country', $country);
        }

        update_option('woocommerce_store_postcode', $address->zip);

    } else {
        foreach($divisions as $division) {
            if ($division->main_division == 1) {
                $address = $division->address;
                update_option('woocommerce_store_address', $address->address);
                update_option('woocommerce_store_address_2', $address->address_2);
                update_option('woocommerce_store_city', $address->city);

                $country = empty($address->country) ? 'US' : $address->country;
                if (!empty($address->state)) {
                    $country_state = $country.':'.$address->state;
                    update_option('woocommerce_default_country', $country_state);
                } else {
                    update_option('woocommerce_default_country', $country);
                }

                update_option('woocommerce_store_postcode', $address->zip);
            }
        }
    }

}

function rental_set_filter_duplicate_products_options($divisions_synced, $settings_location_based_filter) {
    $location_based_filter_division_id = 0;
    $location_based_filter = 0;
    if (count($divisions_synced) > 1) {
        $location_based_filter = $settings_location_based_filter;
        foreach($divisions_synced as $division) {
            if ($division->main_division == 1) {
                $location_based_filter_division_id = $division->id;
            }
        }
    }
    update_option('rental_location_based_duplicate_filter', $location_based_filter);
    update_option('rental_location_based_duplicate_filter_division_id', $location_based_filter_division_id);
}

// function for set theme options
function rental_set_theme_options($theme_options) {
    if ( !empty($theme_options)) {
        $theme_options_key = 'theme_' . strtolower(str_replace(" ", "_", 'eventorian')) . '_options';
        if($options = get_option($theme_options_key)) {
            $options['accent-color'] = isset($theme_options->primary_color)? $theme_options->primary_color: '';
            $options['highlight-color'] = isset($theme_options->secondary_color)? $theme_options->secondary_color: '';
            if (isset($theme_options->logo) && $theme_options->logo && isset($theme_options->logo->img_content)) {
                $upload = wp_upload_bits($theme_options->logo->filename, null, base64_decode($theme_options->logo->img_content));
                $options['logo'] = $upload['url'];
            } else {
                $options['logo'] = '';
            }
            update_option($theme_options_key, $options);
        }
    }

//    $theme = wp_get_theme('twentyfifteen');
//    $theme_options_key = 'theme_' . strtolower(str_replace(" ", "_", $theme->get('Name'))) . '_options';
}

// function for insert records
function rental_insert($query, array $records, $limit = null) {
    global $wpdb;

    if ($count = count($records)) {
        $offset = 0;
        do {
            if ($limit) {
                $data = array_slice($records, $offset, $limit);
                $data = implode(", ", $data);
            } else {
                $data = implode(", ", $records);
            }
            $wpdb->query($query . " " . $data);
            if ($wpdb->last_error !== '') {
                throw new RentalException("SQL_ERROR: $wpdb->last_error (SQL: $wpdb->last_query)", RentalException::TYPE_SYNC_GLOBAL);
            }
            $offset += $limit;
        } while ($limit && $count > $offset);
    }
}

// function for sync (adding products, variants, categories, tags)
function rental_synchronization($api_key) {
    global $wpdb, $rental_tables;
    $rental_product_relations = $wpdb->prefix . $rental_tables["product_relations"];
    $rental_variant_relations = $wpdb->prefix . $rental_tables["variant_relations"];
    $rental_set_relations = $wpdb->prefix . $rental_tables["set_relations"];
    $rental_category_relations = $wpdb->prefix . $rental_tables["category_relations"];
    $rental_tag_relations = $wpdb->prefix . $rental_tables["tag_relations"];
    $rental_sets_tag_relations = $wpdb->prefix . $rental_tables["sets_tag_relations"];
    $rental_attribute_relations = $wpdb->prefix . $rental_tables["attribute_relations"];
    $rental_brand_relations = $wpdb->prefix . $rental_tables["brand_relations"];
    // $rental_shipping_zone_relations = $wpdb->prefix . $rental_tables["shipping_zone_relations"];

    // set max_execution_time
    set_time_limit(800);

    rental_clear_cache();

    // sync company settings
    $settings = rental_sync_company_settings($api_key);
    $stock_status_despite_quantity = empty($settings->inactive_inv_by_quantity);

    set_default_settings();
    // removing filter on synchronization so the new products listing loads correctly
    update_option('rental_filter_unavailable_products', 0);

    // sync company divisions
    rental_sync_divisions($api_key);
    // $main_system_division = get_option('rental_system_main_division', 0);

    // sync company main division address
    $divisions_synced = get_option('rental_divisions');

    $settings_location_based_filter = isset($settings->location_based_filter) ? $settings->location_based_filter : 0;
    rental_set_filter_duplicate_products_options($divisions_synced, $settings_location_based_filter);
    
    if (isset($settings->api_seo_no_index_filter)) {
        update_option('rental_do_not_index_hidden_duplicate_products_for_seo', $settings->api_seo_no_index_filter);
    }
    $do_not_index_hidden_duplicate_products_for_seo = get_option('rental_do_not_index_hidden_duplicate_products_for_seo', 0);

    rental_sync_main_division_address($divisions_synced);

    // delivery/pickup option defaults to company deliver/return
    update_option("rental_pickup_delivery", "company_delivery_return");

    $referral_sources = rental_curl('referral_sources', $api_key);
    update_option('rental_referral_sources', $referral_sources);

    $event_types = rental_curl('event_types', $api_key);
    update_option('rental_event_types', $event_types);

    $payment_tips = rental_curl('payment_tips', $api_key, true, null, null, true);
    if ($payment_tips) {

        update_option('rental_payment_tips', $payment_tips);
    } else {

        ErrorHandler::registerErrorInLog("Failed to fetch payment tips: URL (payment_tips) not reachable.", "functions.php", "5443", RentalException::TYPE_SYNC_RUNTIME, null, "500");
    }


    $limit = 300;
    $start = 0;
    $products = [];
    do {
        $data = rental_curl('products', $api_key, true, [
            'start' => $start,
            'limit' => $limit,
        ]);
        $start += $limit;
        $products = array_merge($products, $data);
    } while (count($data) >= $limit);

    $start = 0;
    $product_variants = [];
    do {
        $data = rental_curl('products/variants', $api_key, true, [
            'start' => $start,
            'limit' => $limit,
        ]);
        $start += $limit;
        $product_variants = array_merge($product_variants, $data);
    } while (count($data) >= $limit);


    $sets = rental_curl('inventories/sets', $api_key);
    $sets_tags = rental_curl('inventories/sets/tags', $api_key);
    
    $attributes = rental_curl('products/attributes', $api_key);

    $attribute_values = rental_curl('products/attributes/values', $api_key);

    $categories = rental_curl('products/categories', $api_key);

    $product_tags = rental_curl('products/tags', $api_key);

    $brands = rental_curl('products/brands', $api_key);

    $img_count = rental_curl('files/images/count', $api_key);

    $shipping_settings = '';
    if (!get_option('rental_do_not_use_rentopian_shipping')) {
        /**
         * Shipping settings
         */
        
        $shipping_settings = rental_curl('shipping/settings', $api_key);
        update_option('rental_shipping_settings', $shipping_settings);
    }
    

    // set plugin path
    rental_curl('settings/plugin_path/update', $api_key, false, [
        'plugin_path' => substr(RENTOPIAN_SYNC_PATH, strlen(ABSPATH))
    ]);


    // delete all the files before sync/re-sync only when the nginx signed URL method is active
    // if (get_option('rental_file_sync_method', 1) == 2) {
    //     $deleted_files_result = rental_delete_dynamic_images_batch();
    //     if (isset($deleted_files_result['deleted'])) {
    //         perf_point("Deleted files from file system count : " . count($deleted_files_result['deleted']) );
    //         perf_point("Deleted files from file system ids : " . implode( ',', $deleted_files_result['deleted'] ) );

    //         ErrorHandler::registerErrorInLog( __('Deleted files from file system count : '. count($deleted_files_result['deleted']), 'rentopian-sync'), __FILE__, __LINE__, RentalException::TYPE_SYNC_GLOBAL, time(), 200);
    //     }
    // }

    // remove all the inventory blocks data
    rental_empty_inventory_blocks();

    // remove all the product options data
    rental_empty_product_options();

    // remove all the set options data
    rental_empty_set_options();

    // remove all the coupons/rental_coupon_relations
    rental_empty_coupons();

    // remove all the rental_price_multipliers
    rental_empty_price_multipliers();

    // removing all products
    rental_empty_products();

    if (!get_option('rental_do_not_use_rentopian_shipping')) {
        // removing all shipping zones
        rental_empty_shipping_zones();
    }

    if (defined('WPSEO_VERSION')) {
        rental_empty_yoast();
    }
    
    

    // save images count
    update_option('rental_products_img_count', $img_count);
    update_option('rental_sync_files_count', $img_count);

    $product_sql = [];
    $productmeta_sql = [];
    $variant_sql = [];
    $variantmeta_sql = [];
    $attribute_sql = [];
    $terms_sql = [];
    $termmeta_sql = [];
    $term_taxonomy_sql = [];
    $term_relation_sql = [];
    $product_relations_sql = [];
    $variant_relations_sql = [];
    $set_relations_sql = [];
    $category_relations_sql = [];
    $tag_relations_sql = [];
    $sets_tag_relations_sql = [];
    $attribute_relations_sql = [];
    $brand_relations_sql = [];
    if (isset($wpdb->wc_product_meta_lookup)) {
        $product_meta_lookup_sql = [];
    }
    $coupons_excluded_product_ids = [];

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
// lock tables
    dbDelta("LOCK TABLE $wpdb->terms WRITE;
        LOCK TABLE $wpdb->term_taxonomy WRITE;
        LOCK TABLE $wpdb->term_relationships WRITE;
        LOCK TABLE $wpdb->posts WRITE;
        LOCK TABLE $wpdb->prefix . 'woocommerce_shipping_zones' WRITE;
        LOCK TABLE $wpdb->prefix . 'woocommerce_shipping_zone_locations' WRITE;
        LOCK TABLE $wpdb->prefix . 'woocommerce_shipping_zone_methods' WRITE;");
    if ($wpdb->last_error !== '') {
        throw new RentalException("SQL_ERROR: $wpdb->last_error (SQL: $wpdb->last_query)", RentalException::TYPE_SYNC_GLOBAL);
    }

// insert test product
    $new_product_id = wp_insert_post(['post_author' => '1', 'post_title' => "Rentopian", 'post_content' => "",
        'post_excerpt' => "", 'post_status' => 'trash', 'comment_status' => 'closed', 'post_type' => 'product',]);
    if ( !$new_product_id) {
        throw new RentalException(__('Failed to insert test product', 'rentopian-sync'), RentalException::TYPE_SYNC_GLOBAL);
    }

    $max_term_taxonomy_id = $wpdb->get_var("SELECT max(term_taxonomy_id) FROM $wpdb->term_taxonomy");
    $max_term_id = $wpdb->get_var("SELECT max(term_id) FROM $wpdb->terms");
    if ($max_term_id > $max_term_taxonomy_id) {
        $max_term_taxonomy_id = $max_term_id;
    }
    $simple = $wpdb->get_var("SELECT `term_id` FROM $wpdb->terms WHERE `name` = 'simple' AND `slug` = 'simple'");
    $variable = $wpdb->get_var("SELECT `term_id` FROM $wpdb->terms WHERE `name` = 'variable' AND `slug` = 'variable'");
    $outofstock = $wpdb->get_var("SELECT `term_id` FROM $wpdb->terms WHERE `name` = 'outofstock' AND `slug` = 'outofstock'");
    $featured = $wpdb->get_var("SELECT `term_id` FROM $wpdb->terms WHERE `name` = 'featured' AND `slug` = 'featured'");

//    $domain = $_SERVER['HTTP_HOST'];
    $domain = get_option('siteurl');
    $date = date('Y-m-d H:i:s');
    $gmdate = gmdate('Y-m-d H:i:s');

    $attribute_types = [];
    $swatch_types = [
        1 =>'select',
        2 => 'color',
        3 => 'image',
        4 => 'text',
    ];
    $attr = [];
    $wc_attribute_taxonomies = [];
    $attr_id = 0;
    foreach ($attributes as $attribute) {
        $attr_id++;
        $attribute_type = isset($swatch_types[$attribute->type])? $swatch_types[$attribute->type]: $swatch_types[1];
        $attribute_type_to_assign = 'select';
        if (defined('RENTPRO_SWATCHES_PATH') || defined('ZOO_CW_VERSION') || defined('WOOF_PATH')) {
            $attribute_type_to_assign = $attribute_type;
        }
        $attribute_sql[] = "($attr_id, '" . $attribute->slug . "', '" . addslashes($attribute->title) . "', '$attribute_type_to_assign', 'menu_order', 0)";
        $attribute_relations_sql[] = "($attr_id, $attribute->id)";
        // collect attributes data for _transient_wc_attribute_taxonomies option
        $wc_attribute_taxonomies[] = (object) [
            "attribute_id" => $attr_id,
            "attribute_name" => $attribute->slug,
            "attribute_label" => $attribute->title,
            "attribute_type" => $attribute_type_to_assign,
            // "attribute_type" => "select",
            "attribute_orderby" => "menu_order",
            "attribute_public" => 0
        ];
        $attribute->new_id = $attr_id;
        $attr[$attribute->id] = [
            "new_id" => $attr_id,
            "id" => $attribute->id,
            "title" => $attribute->title,
            "slug" => $attribute->slug,
            "type" => $attribute_type,
        ];
        $attribute_types[] = "($attr_id, '$attribute_type')";
    }
    unset($attributes);
    if ( !empty($attribute_sql)) {
        rental_insert("INSERT INTO `" . $wpdb->prefix . "woocommerce_attribute_taxonomies`  (`attribute_id`, `attribute_name`, `attribute_label`, `attribute_type`, `attribute_orderby`, `attribute_public`) VALUES", $attribute_sql);
    }
    unset($attribute_sql);
    if ( !empty($attribute_relations_sql)) {
        $wpdb->query("INSERT INTO `$rental_attribute_relations` (`id`, `rental_id`) VALUES " . implode(", ", $attribute_relations_sql));
    }
    unset($attribute_relations_sql);
    update_option('_transient_wc_attribute_taxonomies', $wc_attribute_taxonomies);
    unset($wc_attribute_taxonomies);
    if (defined('ZOO_CW_VERSION') && !empty($attribute_types)) {
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "zoo_cw_product_attribute_swatch_type` (`attribute_id`, `swatch_type`) VALUES " . implode(", ", $attribute_types));
    }
    unset($attribute_types);

    $attr_val = [];
    $tt_id = $max_term_taxonomy_id;
    foreach ($attribute_values as $attribute_value) {
        if ( !isset($attr[$attribute_value->attribute_id])) {
            continue;
        }
        $tt_id++;
        $attribute_type = $attr[$attribute_value->attribute_id]["type"];
        $attr_val[$attribute_value->id] = [
            "term_taxonomy_id" => $tt_id,
            "id" => $attribute_value->id,
            "attribute_id" => $attribute_value->attribute_id,
            "attribute_slug" => $attr[$attribute_value->attribute_id]["slug"],
            "attribute_type" => $attribute_type,
            "title" => $attribute_value->title,
            "slug" => $attribute_value->slug,
            "color" => $attribute_type == "color"? $attribute_value->color: "",
            "img_id" => $attribute_type == "image"? $attribute_value->img_id: 0,
            "object_id" => [],
        ];
    }
    unset($attribute_values);

    $brand_ids = [];
    $rental_img_brand_rel = [];
    foreach ($brands as $brand) {
        $tt_id++;
        $brand->title;
        $terms_sql[] = "($tt_id, '" . addslashes($brand->title) . "', '" . sanitize_title($brand->title) . "', 0)";
        $term_taxonomy_sql[] = "($tt_id, $tt_id, 'product_brand', '', 0, 0)";
        $brand_relations_sql[] = "($tt_id, $brand->id)";
        $brand_ids[$brand->id] = $tt_id;
        if ($brand->logo_id) {
            if (isset($rental_img_brand_rel[$brand->logo_id])) {
                $rental_img_brand_rel[$brand->logo_id][] = $tt_id;
            } else {
                $rental_img_brand_rel[$brand->logo_id] = [$tt_id];
            }
        }
    }
    unset($brands);
    // save image brand relation in session
    update_option('rental_img_brand_rel', $rental_img_brand_rel);

    $products_data = [];
    $products_slug = [];
    $product_up_sells = [];
    $product_cross_sells = [];
    $product_ids_for_up_cross_sells = [];
    $product_attributes_count = []; 
    $products_to_hide = [];
    // $products_to_update_qty = [];
    $variants_to_update_qty = [];
    $has_duplicates_by_pid = [];
    $duplicate_product_ids = [];
    foreach ($products as $prod_key => $product) {

        $is_add_on = $product->is_add_on || $product->hidden_from_api? 1: 0;
        
        $products_data[$product->id] = [
            'ids' => [],
            'img_id' => $product->img_id ? $product->img_id : (isset($product->variant_img_id) && $product->variant_img_id ? $product->variant_img_id : ''),
            'exempt_waiver' => $product->exempt_waiver,
            'is_sale' => $product->is_sale,
            'is_add_on' => $is_add_on,
            'add_ons' => $product->add_ons,
        ];

        $divisions = json_decode($product->divisions);

        $possible_duplicate = false;
        foreach($divisions_synced as $div_sync) {
            if ($div_sync->main_division == 1) {
                
                if (count($divisions) > 1) {
                    foreach($divisions as $prod_div) {
                    
                        if ($prod_div == $div_sync->id) {
                            $possible_duplicate = true;
                        }
                    }
                }
            }
        }

        $has_duplicates = $divisions && count($divisions) > 1 && $possible_duplicate ? 1 : 0;
        foreach ($divisions as $division_id) {
            $new_product_id++;
            $products_data[$product->id]['ids'][$division_id] = $new_product_id;

            $has_duplicates_by_pid[$new_product_id] = $has_duplicates;
            

            if ($has_duplicates && $division_id != get_option('rental_location_based_duplicate_filter_division_id', 0)) {
                $duplicate_product_ids[] = $new_product_id;
            }
            

            if ($product->hidden_from_api || $product->is_add_on) {
                $products_to_hide[] = $new_product_id;
            }

            
            // collecting rental upsell product ids grouped by WP product id
            $product_up_sells[$new_product_id] = (isset($product->up_sells) && !empty($product->up_sells)) ? json_decode($product->up_sells, true) : [];
            // collecting rental crosssell product ids grouped by WP product id
            $product_cross_sells[$new_product_id] = (isset($product->cross_sells) && !empty($product->cross_sells)) ? json_decode($product->cross_sells, true) : [];

            $product_ids_for_up_cross_sells[$product->id][] = $new_product_id;

            $slug = sanitize_title($product->name);
            if (isset($products_slug[$slug])) {
                $products_slug[$slug]++;
                $prod_key++;
                $slug .= "-$products_slug[$slug]-" . $prod_key;
                // $slug .= "-$products_slug[$slug]";
            } else {
                $products_slug[$slug] = 1;
            }

            // add product data for insert in posts table
            $full_description = isset($product->full_description) ? addslashes($product->full_description) : '';
            $short_description = isset($product->description) ? addslashes($product->description) : '';

            $product_sql[$new_product_id] = "($new_product_id, 1, '$date', '$gmdate', '" . addslashes($product->name) . "',
            '" . $full_description . "', '" . $short_description . "', 'publish', 'open', 'closed',
            '$slug', '', '', '$date', '$gmdate', '', 0, '$domain/?post_type=product&p=$new_product_id', 'product')";

            $product_relations_sql[] = "($new_product_id, $product->id, $division_id)";

            
            $product_attributes = [];
            if ($product->attributes) {
                $attr_ids = json_decode($product->attributes);
                $product_attributes_count[$product->id] = count($attr_ids);

                $i = 0;
                foreach ($attr_ids as $attr_id) {
                    if ( !isset($attr[$attr_id])) {
                        continue;
                    }
                    // collect data for postmeta _product_attributes
                    $attribute = $attr[$attr_id]["slug"];
                    $product_attributes["pa_$attribute"] = [
                        "name" => "pa_$attribute",
                        "value" => "",
                        "position" => $i,
                        "is_visible" => 1,
                        "is_variation" => 1,
                        "is_taxonomy" => 1
                    ];
                    $i++;
                }
                $product_attributes = serialize($product_attributes);

                $img_id = '';
                if ($product->img_id) {
                    $img_id = $product->img_id;
                }

                $product_sku = '';
                if (isset($product->SKUs) && $product->SKUs) {
                    $SKUs = json_decode($product->SKUs);
                    $product_sku = isset($SKUs[0]) ? addslashes($SKUs[0]) : '';
                }

                $product_weight = $product_length = $product_width = $product_height = '';
                if (isset($product->dimensions) && $product->dimensions) {
                    $product_dimensions = json_decode($product->dimensions);

                    $product_weight = $product_dimensions->weight;
                    $product_length = $product_dimensions->length;
                    $product_width = $product_dimensions->width;
                    $product_height = $product_dimensions->height;
                }

                // add product data for insert in postmeta table
                $productmeta_sql[$new_product_id] = "($new_product_id, '_wc_review_count', '0' ),
                ($new_product_id, '_wc_rating_count', 'a:0:{}'),
                ($new_product_id, '_wc_average_rating', '0'),
                ($new_product_id, '_edit_last', ''),
                ($new_product_id, '_edit_lock', ''),
                ($new_product_id, '_sku', '$product_sku' ),
                ($new_product_id, '_regular_price', ''),
                ($new_product_id, '_sale_price', '' ),
                ($new_product_id, '_sale_price_dates_from', '' ),
                ($new_product_id, '_sale_price_dates_to', '' ),
                ($new_product_id, 'total_sales', '0' ),
                ($new_product_id, '_tax_status', 'taxable' ),
                ($new_product_id, '_tax_class', '' ),
                ($new_product_id, '_manage_stock', 'no' ),
                ($new_product_id, '_backorders', 'yes' ),
                ($new_product_id, '_sold_individually', 'no' ),
                ($new_product_id, '_weight', '$product_weight' ),
                ($new_product_id, '_length', '$product_length' ),
                ($new_product_id, '_width', '$product_width' ),
                ($new_product_id, '_height', '$product_height' ),
                ($new_product_id, '_upsell_ids', 'a:0:{}' ),
                ($new_product_id, '_crosssell_ids', 'a:0:{}' ),
                ($new_product_id, '_purchase_note', '' ),
                ($new_product_id, '_virtual', 'no' ),
                ($new_product_id, '_downloadable', 'no' ),
                ($new_product_id, '_product_image_gallery', '' ),
                ($new_product_id, '_download_limit', '-1' ),
                ($new_product_id, '_download_expiry', '-1' ),
                ($new_product_id, '_stock', '1' ),
                ($new_product_id, '_stock_status', 'instock'),
                ($new_product_id, '_product_version', '3.2.3'),
                ($new_product_id, '_price', ''),
                ($new_product_id, 'zoo_cw_product_swatch_data', 'a:0:{}'),
                ($new_product_id, '_thumbnail_id', '$img_id'),
                ($new_product_id, '_product_attributes', '$product_attributes'),
                ($new_product_id, '_rental_exempt_waiver', '$product->exempt_waiver'),
                ($new_product_id, '_rental_is_sale', '$product->is_sale'),
                ($new_product_id, '_rental_by_interval', '$product->rental_by_interval'),
                ($new_product_id, '_rental_by_slot', '$product->rental_by_slot'),
                ($new_product_id, '_rental_is_add_on', '$is_add_on')";
                // ($new_product_id, '_manage_stock', 'yes' ),

                $productmeta_sql[$new_product_id] .= ",($new_product_id, '_rental_is_duplicate', '$has_duplicates')";

                $term_relation_sql[] = "($new_product_id, $variable, 0)";
            } else {
                $term_relation_sql[] = "($new_product_id, $simple, 0)";
            }

            if ($product->is_featured) {
                $term_relation_sql[] = "($new_product_id, $featured, 0)";
            }

            if ($product->brand_id && isset($brand_ids[$product->brand_id])) {
                $term_relation_sql[] = "($new_product_id, " . $brand_ids[$product->brand_id] . ", 0)";
            }
        }
    }

    $product_prices = [];
    $rental_img_variant_rel = [];
    $variant_id = $new_product_id;
    $variant_ids = [];
    foreach ($product_variants as $var_key => $variant) {
        $product_id = $products_data[$variant->product_id]['ids'][$variant->division_id];

        $variant_has_duplicates = 0;
        $variant_stock = $variant->quantity;

        if (isset($variant->divisions)) {

            $variant_divisions = json_decode($variant->divisions);
            $variant_has_duplicates = $variant_divisions && count($variant_divisions) > 1 ? 1 : 0;

            if (
                $variant_has_duplicates 
                && get_option('rental_location_based_duplicate_filter', 0) == 1 
                && isset($variant->product_summed_qty)
            ) {
                $variant_stock = $variant->product_summed_qty;
            }


            if ($variant_has_duplicates && $variant->division_id != get_option('rental_location_based_duplicate_filter_division_id', 0)) {
                $duplicate_product_ids[] = $variant_id;
            }
        }

        // collecting non-discountable product ids for coupons 
        if ($variant->discountable == 0) {
            $coupons_excluded_product_ids[] = $product_id;
        }

        $stock_status = $variant->inventory && ($stock_status_despite_quantity || $variant->quantity)? 'instock': 'outofstock';

        $tax_status = $variant->taxable? 'taxable': 'none';

        $job_cost = $variant->job_cost? $variant->job_cost: 0;

        $sku = isset($variant->sku) ? addslashes($variant->sku) : '';

        $price = $variant->rental_price;
        $sale_price = '';
        if ($variant->sale_price > 0) {
            $price = $sale_price = $variant->sale_price;
        }

        if ($variant->attribute_values) {
            $variant_id++;

            if (get_option('rental_location_based_duplicate_filter', 0)) {
                $variants_to_update_qty[] = [
                    'division_id' => $variant->division_id,
                    'variant_id' => $variant_id,
                    'rental_product_id' => $variant->product_id,
                    'qty' => $variant_stock,
                ];
            }
            

            if (isset($variant_ids[$variant->id])) {
                $variant_ids[$variant->id][$variant->division_id] = $variant_id;
            } else {
                $variant_ids[$variant->id] = [$variant->division_id => $variant_id];
            }


            $variant_relations_sql[$variant_id] = "($variant_id, $variant->id, $variant->division_id)";

            if ($variant->img_id) {
                if (isset($rental_img_variant_rel[$variant->img_id])) {
                    $rental_img_variant_rel[$variant->img_id][] = $variant_id;
                } else {
                    $rental_img_variant_rel[$variant->img_id] = [$variant_id];
                }
            }

            $variantmeta_sql[$variant_id] = "";
            $default_attributes = [];
            $attr_val_ids = json_decode($variant->attribute_values);
            foreach ($attr_val_ids as $attr_val_id) {
                if ( !isset($attr_val[$attr_val_id])) {
                    continue;
                }
                $attribute = $attr_val[$attr_val_id]["attribute_slug"];
                $default_attributes["pa_$attribute"] = $attr_val[$attr_val_id]["slug"];
                $variantmeta_sql[$variant_id] .= "($variant_id, 'attribute_pa_$attribute', '" . $attr_val[$attr_val_id]["slug"] . "'),";
                $attr_val[$attr_val_id]["object_id"][$product_id] = $product_id;
            }
            if (isset($product_attributes_count) && $product_attributes_count && !empty($product_attributes_count[$variant->product_id]) && $product_attributes_count[$variant->product_id] < 2) {
                if ($variant->default) {
                    $productmeta_sql[$product_id] .= ",($product_id, '_default_attributes', '" . addslashes(serialize($default_attributes)) . "')";
                }
            }
            $attr_val_title = implode(", ", $default_attributes);
            $attr_val_name = implode("-", $default_attributes);

            // add variant data for insert in posts table
            $variant_sql[$variant_id] = "($variant_id, 1, '$date', '$gmdate', '" . addslashes($variant->name) . " - $attr_val_title',
            '', '', 'publish', 'closed', 'closed', '" . sanitize_title($variant->name) . "-$attr_val_name-$product_id-$var_key',
            '', '', '$date', '$gmdate', '', '$product_id', '$domain/?post_type=product&p=$product_id', 'product_variation')";

            if ( !$variant->inventory) {
                $term_relation_sql[] = "($variant_id, $outofstock, 0)";
            }

            $variant_description = isset($variant->description) ? addslashes($variant->description) : '';

            // get variant price multiplier
            $price_multiplier_id = empty($variant->price_multiplier_id) ? 0 : $variant->price_multiplier_id;
            $replacement_price = empty($variant->rep_price) ? 0 : $variant->rep_price;

            // rental by interval/rental by time slot data
            $rental_interval = empty($variant->rental_interval) ? 0 : $variant->rental_interval;
            $interval_steps = empty($variant->interval_steps) ? 0 : $variant->interval_steps;
            $rental_time_slots = empty($variant->rental_time_slots) ? "" : $variant->rental_time_slots;

            // ($variant_id, '_stock', '$variant->quantity' ),

            // add variant data for insert in postmeta table
            $variantmeta_sql[$variant_id] .= "($variant_id, '_variation_description', '" . $variant_description . "'),
            ($variant_id, '_wc_rating_count', 'a:0:{}'),
            ($variant_id, '_wc_review_count', '0'),
            ($variant_id, '_wc_average_rating', '0'),
            ($variant_id, '_sku', '$sku'),
            ($variant_id, '_regular_price', '$variant->rental_price'),
            ($variant_id, '_rental_replacement_price', '$replacement_price'),
            ($variant_id, '_job_cost', '$job_cost'),
            ($variant_id, '_price_multiplier_id', '$price_multiplier_id'),
            ($variant_id, '_sale_price', '$sale_price'),
            ($variant_id, '_sale_price_dates_from', ''),
            ($variant_id, '_sale_price_dates_to', ''),
            ($variant_id, 'total_sales', '0' ),
            ($variant_id, '_tax_status', '$tax_status'),
            ($variant_id, '_tax_class', '' ),
            ($variant_id, '_manage_stock', 'no' ),
            ($variant_id, '_backorders', 'yes' ),
            ($variant_id, '_sold_individually', 'no' ),
            ($variant_id, '_weight', '$variant->weight'),
            ($variant_id, '_length', '$variant->length'),
            ($variant_id, '_width', '$variant->width'),
            ($variant_id, '_height', '$variant->height'),
            ($variant_id, '_upsell_ids', 'a:0:{}' ),
            ($variant_id, '_crosssell_ids', 'a:0:{}' ),
            ($variant_id, '_purchase_note', '' ),
            ($variant_id, '_virtual', 'no' ),
            ($variant_id, '_downloadable', 'no' ),
            ($variant_id, '_product_image_gallery', '' ),
            ($variant_id, '_download_limit', '-1' ),
            ($variant_id, '_download_expiry', '-1' ),
            ($variant_id, '_stock', '$variant_stock' ),
            ($variant_id, '_stock_status', '$stock_status'),
            ($variant_id, '_product_version', '3.2.3'),
            ($variant_id, '_price', '$price'),
            ($variant_id, '_rental_inventory_id', '$variant->inventory_id'),
            ($variant_id, '_thumbnail_id', ''),
            ($variant_id, '_rental_by_interval', '$variant->rental_by_interval'),
            ($variant_id, '_rental_by_slot', '$variant->rental_by_slot'),
            ($variant_id, '_rental_interval', '$rental_interval'),
            ($variant_id, '_rental_interval_steps', '$interval_steps'),
            ($variant_id, '_rental_interval_price', '$variant->rental_interval_price'),
            ($variant_id, '_rental_interval_sale_price', '$variant->rental_interval_sale_price'),
            ($variant_id, '_rental_additional_hourly_price', '$variant->additional_hourly_price'),
            ($variant_id, '_rental_time_slots', '$rental_time_slots'),
            ($variant_id, '_downloadable_files', 'a:0:{}')";

            $variantmeta_sql[$variant_id] .= ",($variant_id, '_rental_is_duplicate', '$variant_has_duplicates')";

            // ($variant_id, '_manage_stock', 'yes' ),
            if (isset($product_meta_lookup_sql)) {
                $on_sale = $sale_price? 1: 0;
                // $product_meta_lookup_sql[$variant_id] = "($variant_id, '$sku', 0, 0, $price, $price, $on_sale, $variant->quantity, '$stock_status', '$tax_status')";
                $product_meta_lookup_sql[$variant_id] = "($variant_id, '$sku', 0, 0, $price, $price, $on_sale, $variant_stock, '$stock_status', '$tax_status')";
                if (isset($product_prices[$product_id])) {
                    if ($price < $product_prices[$product_id]['min']) {
                        $product_prices[$product_id]['min'] = $price;
                    } elseif ($price > $product_prices[$product_id]['max']) {
                        $product_prices[$product_id]['max'] = $price;
                    }
                } else {
                    $product_prices[$product_id] = ['min' => $price, 'max' => $price];
                }
                $product_meta_lookup_sql[$product_id] = "($product_id, '$sku', 0, 0, " . $product_prices[$product_id]['min'] .
                    ", " . $product_prices[$product_id]['max'] . ", 0, $variant_stock, '$stock_status', '$tax_status')";
                    // ", " . $product_prices[$product_id]['max'] . ", 0, $variant->quantity, '$stock_status', '$tax_status')";
            }
        } else {

            // $products_to_update_qty[] = [
            //     'product_id' => $new_product_id,
            //     'qty' => $variant->quantity,
            // ];

            if ( !$variant->inventory) {
                // key = [$product_id ."_". $outofstock] because there are product variants that do not have custom fields
                $term_relation_sql[$product_id ."_". $outofstock] = "($product_id, $outofstock, 0)";
            }


            // get variant price multiplier
            $price_multiplier_id = empty($variant->price_multiplier_id) ? 0 : $variant->price_multiplier_id;
            $replacement_price = empty($variant->rep_price) ? 0 : $variant->rep_price;

            // rental by interval/rental by time slot data
            $rental_interval = empty($variant->rental_interval) ? 0 : $variant->rental_interval;
            $interval_steps = empty($variant->interval_steps) ? 0 : $variant->interval_steps;
            $rental_time_slots = empty($variant->rental_time_slots) ? "" : $variant->rental_time_slots;

            $productmeta_sql[$product_id] = "($product_id, '_wc_review_count', '0' ),
            ($product_id, '_wc_rating_count', 'a:0:{}'),
            ($product_id, '_wc_average_rating', '0'),
            ($product_id, '_edit_last', ''),
            ($product_id, '_edit_lock', ''),
            ($product_id, '_sku', '$sku'),
            ($product_id, '_regular_price', '$variant->rental_price'),
            ($product_id, '_rental_replacement_price', '$replacement_price'),
            ($product_id, '_job_cost', '$job_cost'),
            ($product_id, '_price_multiplier_id', '$price_multiplier_id'),
            ($product_id, '_sale_price', '$sale_price'),
            ($product_id, '_sale_price_dates_from', ''),
            ($product_id, '_sale_price_dates_to', ''),
            ($product_id, 'total_sales', '0'),
            ($product_id, '_tax_status', '$tax_status'),
            ($product_id, '_tax_class', '' ),
            ($product_id, '_manage_stock', 'no' ),
            ($product_id, '_backorders', 'yes' ),
            ($product_id, '_sold_individually', 'no' ),
            ($product_id, '_weight', '$variant->weight'),
            ($product_id, '_length', '$variant->length'),
            ($product_id, '_width', '$variant->width'),
            ($product_id, '_height', '$variant->height'),
            ($product_id, '_upsell_ids', 'a:0:{}' ),
            ($product_id, '_crosssell_ids', 'a:0:{}' ),
            ($product_id, '_purchase_note', '' ),
            ($product_id, '_default_attributes', 'a:0:{}' ),
            ($product_id, '_virtual', 'no' ),
            ($product_id, '_downloadable', 'no' ),
            ($product_id, '_product_image_gallery', '' ),
            ($product_id, '_download_limit', '-1' ),
            ($product_id, '_download_expiry', '-1' ),
            ($product_id, '_stock', '$variant_stock' ),
            ($product_id, '_stock_status', '$stock_status'),
            ($product_id, '_product_version', '3.2.3'),
            ($product_id, '_price', '$price'),
            ($product_id, '_rental_inventory_id', '$variant->inventory_id'),
            ($product_id, 'zoo_cw_product_swatch_data', 'a:0:{}'),
            ($product_id, '_thumbnail_id', '" . $products_data[$variant->product_id]['img_id'] . "'),
            ($product_id, '_rental_exempt_waiver', '" . $products_data[$variant->product_id]['exempt_waiver'] . "'),
            ($product_id, '_rental_is_sale', '" . $products_data[$variant->product_id]['is_sale'] . "'),
            ($product_id, '_rental_by_interval', '$variant->rental_by_interval'),
            ($product_id, '_rental_by_slot', '$variant->rental_by_slot'),
            ($product_id, '_rental_interval', '$rental_interval'),
            ($product_id, '_rental_interval_steps', '$interval_steps'),
            ($product_id, '_rental_interval_price', '$variant->rental_interval_price'),
            ($product_id, '_rental_interval_sale_price', '$variant->rental_interval_sale_price'),
            ($product_id, '_rental_additional_hourly_price', '$variant->additional_hourly_price'),
            ($product_id, '_rental_time_slots', '$rental_time_slots'),
            ($product_id, '_rental_is_add_on', '" . $products_data[$variant->product_id]['is_add_on'] . "')";

            $product_without_variants_has_duplicate = isset($has_duplicates_by_pid[$product_id]) ? $has_duplicates_by_pid[$product_id] : 0;
            $productmeta_sql[$product_id] .= ",($product_id, '_rental_is_duplicate', '$product_without_variants_has_duplicate')";

            if ($product_without_variants_has_duplicate && $variant->division_id != get_option('rental_location_based_duplicate_filter_division_id', 0)) {
                $duplicate_product_ids[] = $product_id;
            }

            //            ($product_id, '_manage_stock', 'yes' ),
            if (isset($product_meta_lookup_sql)) {
                $on_sale = $sale_price? 1: 0;
                $product_meta_lookup_sql[$product_id] = "($product_id, '$sku', 0, 0, $price" .
                    ", $price, $on_sale, $variant_stock, '$stock_status', '$tax_status')";
                    // ", $price, $on_sale, $variant->quantity, '$stock_status', '$tax_status')";
            }
        }

    }

    foreach ($products_data as $product) {

        if ($product['add_ons']) {
            
            foreach ($product['ids'] as $division_id => $product_id) {
                
                $product_add_ons = [];
                $add_ons = json_decode($product['add_ons']);

                foreach ($add_ons as $add_on) {
                    if (isset($products_data[$add_on->product_id]) && isset($products_data[$add_on->product_id]['ids'][$division_id])) {
                        
                        $add_on_id = $products_data[$add_on->product_id]['ids'][$division_id];
                        
                        $add_on_variant_id = 0;
                        if ($add_on->variant_id && isset($variant_ids[$add_on->variant_id]) && isset($variant_ids[$add_on->variant_id][$division_id])) {
                            $add_on_variant_id = $variant_ids[$add_on->variant_id][$division_id];
                        }

                        $product_add_ons[$add_on_variant_id ?: $add_on_id] = [
                            'product_id' => $add_on_id,
                            'variant_id' => $add_on_variant_id,
                            'rental_variant_id' => $add_on->variant_id,
                            'quantity' => $add_on->quantity,
                            'price' => $add_on->price,
                            'required' => $add_on->required,
                            'hidden' => isset($add_on->hidden) ? $add_on->hidden : 0,
                            'product_price' => isset($add_on->product_price) ? $add_on->product_price : 0,
                            'inherit_price' => isset($add_on->inherit_price) ? $add_on->inherit_price : 0,
                        ];
                    }
                }

                if ($product_add_ons) {
                    $productmeta_sql[$product_id] .= ",($product_id, '_rental_add_ons', '" . addslashes(serialize($product_add_ons)) . "')";
                }
            }
        }
    }


    
    $set_id = $variant_id;
    $set_ids = [];
    $set_items_collection = [];
    $set_up_sells_from_sets = $set_up_sells_from_products = $set_cross_sells_from_sets = $set_cross_sells_from_products = [];
    update_option('rental_set_items_have_addons', false);
    foreach ($sets as $set) {
        $set_id++;
        $set_ids[$set->id] = $set_id;

        $set_up_sells_from_sets[$set_id] = (isset($set->up_sells_sets) && !empty($set->up_sells_sets)) ? json_decode($set->up_sells_sets, true) : [];
        $set_up_sells_from_products[$set_id] = (isset($set->up_sells_products) && !empty($set->up_sells_products)) ? json_decode($set->up_sells_products, true) : [];

        $set_cross_sells_from_sets[$set_id] = (isset($set->cross_sells_sets) && !empty($set->cross_sells_sets)) ? json_decode($set->cross_sells_sets, true) : [];
        $set_cross_sells_from_products[$set_id] = (isset($set->cross_sells_products) && !empty($set->cross_sells_products)) ? json_decode($set->cross_sells_products, true) : [];

        // get set's price multiplier
        $price_multiplier_id = empty($set->price_multiplier_id) ? 0 : $set->price_multiplier_id;

        // collecting non-discountable product(set) ids for coupons 
        if ($set->discountable == 0) {
            $coupons_excluded_product_ids[] = $set_id;
        }

        $slug = sanitize_title($set->title);
        if (isset($products_slug[$slug])) {
            $products_slug[$slug]++;
            $slug .= "-$products_slug[$slug]";
        } else {
            $products_slug[$slug] = 1;
        }

        // add set data for insert in posts table
        $set_full_description = isset($set->full_description) ? addslashes($set->full_description) : '';
        $set_short_description = isset($set->description) ? addslashes($set->description) : '';

        $product_sql[$set_id] = "($set_id, 1, '$date', '$gmdate', '" . addslashes($set->title) . "',
            '" . $set_full_description . "', '" . $set_short_description . "', 'publish', 'open', 'closed',
            '$slug', '', '', '$date', '$gmdate', '', 0, '$domain/?post_type=product&p=$set_id', 'product')";

        $set_relations_sql[] = "($set_id, $set->id, $set->division_id)";
        $term_relation_sql[] = "($set_id, $simple, 0)";

        if ($set->img_id) {
            if (isset($rental_img_variant_rel[$set->img_id])) {
                $rental_img_variant_rel[$set->img_id][] = $set_id;
            } else {
                $rental_img_variant_rel[$set->img_id] = [$set_id];
            }
        }

        $set_items = [];
        $set_items_have_optional_items = false;
        $set_items_have_some_hidden_items = false;
        $items = json_decode($set->items);
        if($items){
            foreach ($items as $item) {

                if (
                    (isset($products_data[$item->product_id]) && isset($products_data[$item->product_id]['ids'][$item->division_id]))
                    || (isset($item->optional_items) && $item->product_id)
                ) {

                    $set_item_product_id = isset($products_data[$item->product_id]) && isset($products_data[$item->product_id]['ids'][$item->division_id]) ? $products_data[$item->product_id]['ids'][$item->division_id] : ($item->product_id ? $item->product_id : 0);
                    $set_item_variant_id = isset($item->optional_items) ? 0 : (isset($variant_ids[$item->variant_id][$item->division_id])? $variant_ids[$item->variant_id][$item->division_id]: null);
                    if (isset($item->has_selected) && $item->has_selected && $item->variant_id) {
                        $set_item_variant_id = isset($variant_ids[$item->variant_id][$item->division_id])? $variant_ids[$item->variant_id][$item->division_id]: null;
                    }

                    $optional_items = [];
                    if (isset($item->optional_items)) {
                        foreach ($item->optional_items as $optional_item) {

                            $optional_items[] = [
                                'rental_product_id' => $optional_item->product_id,
                                'rental_variant_id' => $optional_item->variant_id,
                                'product_id' => $products_data[$optional_item->product_id]['ids'][$optional_item->division_id],
                                'variant_id' => isset($variant_ids[$optional_item->variant_id][$optional_item->division_id]) ? $variant_ids[$optional_item->variant_id][$optional_item->division_id]: null,
                                'quantity' => $optional_item->quantity,
                                'is_selected' => isset($optional_item->is_selected) && $optional_item->is_selected ? 1 : 0,
                            ];
                        }


                        if ($optional_items) {
                            $set_items_have_optional_items = true;
                        }
                    }


                    $set_item_addons = [];
                    if (isset($item->addons) && $item->addons) {

                        // $set_item_product_id = isset($products_data[$item->product_id]) && isset($products_data[$item->product_id]['ids'][$item->division_id]) ? $products_data[$item->product_id]['ids'][$item->division_id] : 0;
                        foreach ($item->addons as $item_addon) {


                            // if ($item_addon->division_id == get_option('rental_system_main_division', 0)) {

                                $addon_variants_optional = [];
                                if (isset($item_addon->variants_optional) && $item_addon->variants_optional) {

                                    foreach ($item_addon->variants_optional as $addon_variant) {
                                        
                                        $optional_variant_product_id = isset($products_data[$addon_variant->product_id]) && isset($products_data[$addon_variant->product_id]['ids'][$addon_variant->division_id]) ? $products_data[$addon_variant->product_id]['ids'][$addon_variant->division_id] : 0;
                                        $optional_variant_variant_id = $addon_variant->variant_id && isset($variant_ids[$addon_variant->variant_id]) && isset($variant_ids[$addon_variant->variant_id][$addon_variant->division_id]) ? $variant_ids[$addon_variant->variant_id][$addon_variant->division_id] : 0;
                                        
                                        $addon_variants_optional[] = [
                                            'product_id' => $optional_variant_product_id,
                                            'rental_product_id' => $addon_variant->product_id,
                                            'variant_id' => $optional_variant_variant_id,
                                            'rental_variant_id' => $addon_variant->variant_id,
                                            'quantity' => $addon_variant->quantity,
                                            'default' => $addon_variant->default,
                                        ];
                                    }
                                }

                                $add_on_id = isset($products_data[$item_addon->product_id]) && isset($products_data[$item_addon->product_id]['ids'][$item_addon->division_id]) ? $products_data[$item_addon->product_id]['ids'][$item_addon->division_id] : 0;
                                $add_on_variant_id = $item_addon->add_on_variant_id && isset($variant_ids[$item_addon->add_on_variant_id]) && isset($variant_ids[$item_addon->add_on_variant_id][$item_addon->division_id]) ? $variant_ids[$item_addon->add_on_variant_id][$item_addon->division_id] : 0;
    
                                $set_item_addons[] = [
                                    'parent_set_id' => $set_id,
                                    'parent_set_product_id' => $set_item_product_id,
                                    'parent_set_variant_id' => $set_item_variant_id,
                                    'rental_inv_id' => $item_addon->id,
                                    'product_id' => $add_on_id,
                                    'rental_product_id' => $item_addon->product_id,
                                    'variant_id' => $add_on_variant_id,
                                    'rental_variant_id' => $item_addon->add_on_variant_id,
                                    'quantity' => $item_addon->add_on_quantity,
                                    'price' => $item_addon->price,
                                    'required' => $item_addon->required,
                                    'hidden' => isset($item_addon->hidden) ? $item_addon->hidden : 0,
                                    'product_price' => isset($item_addon->product_price) ? $item_addon->product_price : 0,
                                    'inherit_price' => isset($item_addon->inherit_price) ? $item_addon->inherit_price : 0,
                                    'variants_optional' => $addon_variants_optional,
                                ];
                            // }

                            
                        }


                        if ($set_item_addons && !get_option('rental_set_items_have_addons', false)) {
                            update_option('rental_set_items_have_addons', true);
                        }
                    }


                    // $set_item_variant_id = isset($item->optional_items) ? 0 : (isset($variant_ids[$item->variant_id][$item->division_id])? $variant_ids[$item->variant_id][$item->division_id]: null);
                    // if (isset($item->has_selected) && $item->has_selected && $item->variant_id) {
                    //     $set_item_variant_id = isset($variant_ids[$item->variant_id][$item->division_id])? $variant_ids[$item->variant_id][$item->division_id]: null;
                    // }
                    

                    if (isset($item->hidden) && $item->hidden) {
                        $set_items_have_some_hidden_items = true;
                    }

                    $optional_item_price_update_needed = (isset($item->has_selected) && $item->has_selected) || (count($optional_items) < 2) ? 1 : 0;
                    $set_items[] = [
                        // 'product_id' => $products_data[$item->product_id]['ids'][$item->division_id],
                        'rental_variant_id' => $item->variant_id ?? 0,
                        'rental_product_id' => $item->product_id ?? 0,
                        'parent_set_id' => $set_id,
                        'product_id' => $set_item_product_id,
                        'variant_id' => $set_item_variant_id,
                        'quantity' => $item->quantity,
                        'optional_items' => $optional_items,
                        'has_selected' => isset($item->has_selected) && $item->has_selected ? 1 : 0,
                        'optional_item_price_update_needed' => $optional_item_price_update_needed, // 0: no need to update, 1: needs update, 2: is updated
                        'hidden' => isset($item->hidden) && $item->hidden ? 1 : 0,
                        'price' => $item->price ?? 0,
                        'separate_price' => $item->separate_price ?? 0,
                        'required' => $item->required ?? 0,
                        'addons' => $set_item_addons,
                    ];


                    if (!isset($item->optional_items)) {
                        $set_items_collection[$products_data[$item->product_id]['ids'][$item->division_id]] = true;

                        if (isset($variant_ids[$item->variant_id][$item->division_id])) {
                            $set_items_collection[$variant_ids[$item->variant_id][$item->division_id]] = true;
                        }
                    }
                    
                }
            }
        }

        $sku = addslashes($set->number);
        $tax_status = $set->taxable? 'taxable': 'none';
        $hide_items_on_website = isset($set->hide_items_on_website) ? $set->hide_items_on_website : 0;
        $item_based_total = isset($set->item_based_total) ? $set->item_based_total : 0;

        $productmeta_sql[$set_id] = "($set_id, '_wc_review_count', '0' ),
            ($set_id, '_wc_rating_count', 'a:0:{}'),
            ($set_id, '_wc_average_rating', '0'),
            ($set_id, '_edit_last', ''),
            ($set_id, '_edit_lock', ''),
            ($set_id, '_sku', '$sku'),
            ($set_id, '_regular_price', '$set->rental_price'),
            ($set_id, '_job_cost', '$set->job_cost'),
            ($set_id, '_price_multiplier_id', '$price_multiplier_id'),
            ($set_id, '_sale_price', '' ),
            ($set_id, '_sale_price_dates_from', '' ),
            ($set_id, '_sale_price_dates_to', '' ),
            ($set_id, 'total_sales', '0' ),
            ($set_id, '_tax_status', '$tax_status'),
            ($set_id, '_tax_class', '' ),
            ($set_id, '_manage_stock', 'no' ),
            ($set_id, '_backorders', 'yes' ),
            ($set_id, '_sold_individually', 'no' ),
            ($set_id, '_weight', '' ),
            ($set_id, '_length', '' ),
            ($set_id, '_width', '' ),
            ($set_id, '_height', '' ),
            ($set_id, '_upsell_ids', 'a:0:{}' ),
            ($set_id, '_crosssell_ids', 'a:0:{}' ),
            ($set_id, '_purchase_note', '' ),
            ($set_id, '_default_attributes', 'a:0:{}' ),
            ($set_id, '_virtual', 'no' ),
            ($set_id, '_downloadable', 'no' ),
            ($set_id, '_product_image_gallery', '' ),
            ($set_id, '_download_limit', '-1' ),
            ($set_id, '_download_expiry', '-1' ),
            ($set_id, '_stock', '1' ),
            ($set_id, '_stock_status', 'instock'),
            ($set_id, '_product_version', '3.2.3'),
            ($set_id, '_price', '$set->rental_price'),
            ($set_id, '_price_default', '$set->rental_price'),
            ($set_id, 'zoo_cw_product_swatch_data', 'a:0:{}'),
            ($set_id, '_thumbnail_id', ''),
            ($set_id, '_rental_exempt_waiver', '$set->exempt_waiver'),
            ($set_id, '_rental_is_sale', '$set->is_sale'),
            ($set_id, '_rental_is_add_on', '0'),
            ($set_id, '_rental_set_items_have_optional_items', '" . $set_items_have_optional_items . "'),
            ($set_id, '_rental_set_items', '" . addslashes(serialize($set_items)) . "'),
            ($set_id, '_rental_set_items_default', '" . addslashes(serialize($set_items)) . "'),
            ($set_id, '_rental_item_based_total', '$item_based_total'),
            ($set_id, '_rental_hide_items_on_website', '$hide_items_on_website'),
            ($set_id, '_rental_some_hidden_items', '$set_items_have_some_hidden_items'),
            ($set_id, '_rental_is_set', '1')";
        if (isset($product_meta_lookup_sql)) {
            $product_meta_lookup_sql[$set_id] = "($set_id, '$sku', 0, 0, $set->rental_price" .
                ", $set->rental_price, 0, 1, 'instock', '$tax_status')";
        }
    }

    // save image variant relation in session
    update_option('rental_img_variant_rel', $rental_img_variant_rel);

    $category_products = [];
    $rental_img_category_rel = [];
    $rental_banner_img_category_rel = [];
    $cat_id = $tt_id;

    // add the category data to the variables to insert to the required tables(terms, term_taxonomy)
    foreach ($categories as $category) {
        $cat_id = $tt_id + $category->id;

        $terms_sql[] = "($cat_id, '" . addslashes($category->title) . "', '" . sanitize_title($category->title) . "', 0)";

        $parent_cat_id = 0;
        if ($category->parent_id) {
            $parent_cat_id = $category->parent_id + $tt_id;
            if ( !isset($category_products[$parent_cat_id])) {
                $category_products[$parent_cat_id] = [];
            }
        }
        if ( !isset($category_products[$cat_id])) {
            $category_products[$cat_id] = [];
        }

        $cat_products_count = 0;
        // relate products and categories with term_relation table
        if ($category->products && !empty($cat_products = explode(",", $category->products))) {
            foreach ($cat_products as $cat_product_id) {
                if (isset($products_data[$cat_product_id])) {
                    foreach ($products_data[$cat_product_id]['ids'] as $product_id) {
                        $term_relation_sql[] = "($product_id, $cat_id, 0)";
                        $cat_products_count++;
                        if ( !in_array($product_id, $category_products[$cat_id])) {
                            $category_products[$cat_id][] = $product_id;
                        }
                        if ($parent_cat_id && !in_array($product_id, $category_products[$parent_cat_id])) {
                            $category_products[$parent_cat_id][] = $product_id;
                        }
                    }
                }
            }
        }

        // relate sets and categories with term_relation table
        if ($category->sets && !empty($cat_sets = explode(",", $category->sets))) {
            foreach ($cat_sets as $cat_set_id) {
                if (isset($set_ids[$cat_set_id])) {
                    $term_relation_sql[] = "(" . $set_ids[$cat_set_id] . ", $cat_id, 0)";
                    $cat_products_count++;
                    if ( !in_array($set_ids[$cat_set_id], $category_products[$cat_id])) {
                        $category_products[$cat_id][] = $set_ids[$cat_set_id];
                    }
                    if ($parent_cat_id && !in_array($set_ids[$cat_set_id], $category_products[$parent_cat_id])) {
                        $category_products[$parent_cat_id][] = $set_ids[$cat_set_id];
                    }
                }
            }
        }

        $category_description = isset($category->description) ? addslashes($category->description) : '';
        $category_icon = isset($category->icon) ? addslashes($category->icon) : "";

        $term_taxonomy_sql[] = "($cat_id, $cat_id, 'product_cat', '" . $category_description . "', $parent_cat_id, $cat_products_count)";

        // add the category data to the variables to insert to the required tables(termmeta)
        $termmeta_sql[] = "($cat_id, 'order', 0)," .
            "($cat_id, 'display_type', '')," .
            "($cat_id, 'thumbnail_id', 0)," .
            "($cat_id, 'rental_icon', '" . $category_icon . "')";

        $category_relations_sql[] = "($cat_id, $category->id)";

        if ($category->img_id) {
            if (isset($rental_img_category_rel[$category->img_id])) {
                $rental_img_category_rel[$category->img_id][] = $cat_id;
            } else {
                $rental_img_category_rel[$category->img_id] = [$cat_id];
            }
        }

        if (isset($category->banner_img_id) && $category->banner_img_id) {
            if (isset($rental_banner_img_category_rel[$category->banner_img_id])) {
                $rental_banner_img_category_rel[$category->banner_img_id][] = $cat_id;
            } else {
                $rental_banner_img_category_rel[$category->banner_img_id] = [$cat_id];
            }
        }
    }

    // save image category relation in session
    update_option('rental_img_category_rel', $rental_img_category_rel);
    update_option('rental_banner_img_category_rel', $rental_banner_img_category_rel);

    // add products count for each category
    foreach ($category_products as $term_id => $objects) {
        $termmeta_sql[] = "($term_id, 'product_count_product_cat', " . count($objects) . ")";
    }

    $tags_slug = [];
    $similar_tags = [];
    // add the tag data to the variables to insert to the required table(termmeta)
    foreach ($product_tags as $product_tag) {
        $tag_id = $cat_id + $product_tag->id;

        $slug_tag = sanitize_title($product_tag->title);

        if ($sets_tags) {
            foreach ($sets_tags as $set_tag) {
                $set_slug_tag = sanitize_title($set_tag->title);
    
                if ($slug_tag == $set_slug_tag) {
                    $similar_tags[$set_slug_tag] = $set_slug_tag . '-sets';
                }
            }
        }
       
        if (isset($tags_slug[$slug_tag])) {
            
            $tags_slug[$slug_tag]++;

            $slug_tag .= "-$tags_slug[$slug_tag]";
        } else {
            $tags_slug[$slug_tag] = 1;
        }

        $terms_sql[] = "($tag_id, '" . addslashes($product_tag->title) . "', '" . $slug_tag . "', 0)";

        $tag_products_count = 0;
        // relate products and tags with term_relation table
        if ($product_tag->products && !empty($tag_products = explode(",", $product_tag->products))) {
            foreach ($tag_products as $tag_product_id) {
                if (isset($products_data[$tag_product_id])) {
                    foreach ($products_data[$tag_product_id]['ids'] as $product_id) {
                        $term_relation_sql[] = "($product_id, $tag_id, 0)";
                        $tag_products_count++;
                    }
                }
            }
        }
        $termmeta_sql[] = "($tag_id, 'product_count_product_tag', $tag_products_count)";
        $term_taxonomy_sql[] = "($tag_id, $tag_id, 'product_tag', '', 0, $tag_products_count)";
        $tag_relations_sql[] = "($tag_id, $product_tag->id)";

    }


    $set_tags_slug = [];
    // Sets Tags
    foreach ($sets_tags as $set_tag) {
        $tag_id = $cat_id + $set_tag->id;

        $set_slug_tag = sanitize_title($set_tag->title);
        if (isset($similar_tags[$set_slug_tag])) {
            $set_slug_tag = $similar_tags[$set_slug_tag];
        }
      
        if (isset($set_tags_slug[$set_slug_tag])) {
            
            $set_tags_slug[$set_slug_tag]++;

            $set_slug_tag .= "-$set_tags_slug[$set_slug_tag]";
        } else {
            $set_tags_slug[$set_slug_tag] = 1;
        }

        $terms_sql[] = "($tag_id, '" . addslashes($set_tag->title) . "', '" . $set_slug_tag . "', 0)";

        $tag_sets_count = 0;
        // relate sets and tags with term_relation table
        if ($set_tag->sets && !empty($tag_sets = explode(",", $set_tag->sets))) {
            foreach ($tag_sets as $tag_set_id) {
                if (isset($set_ids[$tag_set_id])) {
                    $term_relation_sql[] = "($set_ids[$tag_set_id], $tag_id, 0)";
                    $tag_sets_count++;
                }
            }
        }
        $termmeta_sql[] = "($tag_id, 'product_count_product_tag', $tag_sets_count)";
        $term_taxonomy_sql[] = "($tag_id, $tag_id, 'product_tag', '', 0, $tag_sets_count)";

        $sets_tag_relations_sql[] = "($tag_id, $set_tag->id)";
    }

    // add the attributes data to the variables to insert to the required tables(terms, termmeta, term_taxonomy)
    $rental_img_attribute_value_rel = [];
    foreach ($attr_val as $val) {
        $term_taxonomy_id = $val["term_taxonomy_id"];
        $attribute = $val["attribute_slug"];
        $terms_sql[] = "($term_taxonomy_id, '" . addslashes($val["title"]) . "', '" . $val["slug"] . "', 0)";
        $termmeta = "($term_taxonomy_id, 'order_pa_$attribute', 0)";
        if (defined('ZOO_CW_VERSION')) {
            if ($val["color"]) {
                $termmeta .= ", ($term_taxonomy_id, 'slctd_clr', '" . $val["color"] . "')";
            } elseif ($val["img_id"]) {
                if (isset($rental_img_attribute_value_rel[$val["img_id"]])) {
                    $rental_img_attribute_value_rel[$val["img_id"]][] = $term_taxonomy_id;
                } else {
                    $rental_img_attribute_value_rel[$val["img_id"]] = [$term_taxonomy_id];
                }
            }
        }

        if (defined('RENTPRO_SWATCHES_PATH')) {
            if ($val["color"]) {
                $termmeta .= ", ($term_taxonomy_id, 'sw_color', '" . $val["color"] . "')";
                $termmeta .= ", ($term_taxonomy_id, 'sw_tooltip', '" . $val["title"] . "')";
            } else if ($val["img_id"]) {
                if (isset($rental_img_attribute_value_rel[$val["img_id"]])) {
                    $rental_img_attribute_value_rel[$val["img_id"]][] = $term_taxonomy_id;
                } else {
                    $rental_img_attribute_value_rel[$val["img_id"]] = [$term_taxonomy_id];
                }
                $termmeta .= ", ($term_taxonomy_id, 'sw_tooltip', '" . $val["title"] . "')";
            }
        }
        
        if (defined('WOOF_PATH')) {
            require_once("includes/models/RTImage.php");
            $attribute_name = "pa_$attribute";
            $woof_settings = get_option('woof_settings');

            if (!empty($woof_settings) && isset($woof_settings["tax_type"]) && isset($woof_settings["tax_type"][$attribute_name])) {
                $attribute_type = $woof_settings["tax_type"][$attribute_name];
                if ($attribute_type == "color") {
                    if ( !isset($woof_settings["color"])) {
                        $woof_settings["color"] = [$attribute_name => []];
                    } elseif ( !isset($woof_settings["color"][$attribute_name])) {
                        $woof_settings["color"][$attribute_name] = [];
                    }
                    $woof_settings["color"][$attribute_name][$val["slug"]] = $val["color"]?: "#000000";
                    update_option("woof_settings", $woof_settings);

                } elseif ($attribute_type == "image") {
                    $_image = "";
                    if ($val["img_id"]) {
                        $images = (new RTImage())->getImages([$val["img_id"]]);
                        if (isset($images[$val["img_id"]])) {
                            $_image = wp_get_attachment_image_url($images[$val["img_id"]]);
                        }
                    }

                    $_term_id = $wpdb->get_var("SELECT `term_id` FROM $wpdb->terms WHERE `name` = '$attribute_name' AND `slug` = '".$val["slug"]."'");
                    if ( !isset($woof_settings["images_term_$_term_id"])) {
                        $woof_settings["images_term_$_term_id"] = [];
                    }
                    $woof_settings["images_term_$_term_id"]["image_url"] = $_image;
                    update_option("woof_settings", $woof_settings);
                }
                
            }
        }

        $termmeta_sql[] = $termmeta;
        $term_taxonomy_sql[] = "($term_taxonomy_id, $term_taxonomy_id, 'pa_$attribute', '', 0, " . count($val["object_id"]) . ")";
        // relate products and attributes with term_relation table
        foreach ($val["object_id"] as $object_id) {
            $term_relation_sql[] = "($object_id, $term_taxonomy_id, 0)";
        }
    }

    // save image attribute value relation in session
    update_option('rental_img_attribute_value_rel', $rental_img_attribute_value_rel);

    if (!get_option('rental_do_not_use_rentopian_shipping')) {
        
        /**
         * Shipping settings
         */
        // if ($shipping_settings->shipping_by === 'mile' || $shipping_settings->shipping_by === 'kilometre') {

        //     $shipping_title = $shipping_settings->shipping_by === 'mile' ? 'Miles' : 'Kilometre';
        //     $shipping_label = $shipping_title . ' Based Shipping';
        //     if ($rental_miles_shipping_label_text = get_option('rental_miles_shipping_label_text', '')) {
        //         $shipping_label = $rental_miles_shipping_label_text;
        //     }

        //     update_option('woocommerce_miles_based_settings', array(
        //         'enabled'           =>  'yes',
        //         'title'             =>  $shipping_label,
        //         'first_miles'       =>  $shipping_settings->min_miles,
        //         'first_miles_rate'  =>  $shipping_settings->min_miles_cost,
        //         'per_mile_rate'     =>  $shipping_settings->per_mile_cost,
        //     ));
        //     update_option('woocommerce_enable_shipping_calc', 'no');
        //     if (isset($shipping_settings->google_map_key) && $shipping_settings->google_map_key) {
        //         update_option('rental_google_distance_key', $shipping_settings->google_map_key);
        //     }

        // } else {

            // update_option('woocommerce_miles_based_settings', array(
            //     'enabled'           =>  'no',
            // ));
            // $shipping_zones = rental_curl('shipping/zones', $api_key);

            // woocommerce shipping zone related tables
            // $woocommerce_shipping_zones = $wpdb->prefix . 'woocommerce_shipping_zones';
            // $woocommerce_shipping_zone_locations = $wpdb->prefix . 'woocommerce_shipping_zone_locations';
            // $woocommerce_shipping_zone_methods = $wpdb->prefix . 'woocommerce_shipping_zone_methods';

            // if ( !empty($shipping_zones)) {

                /** Arrays to hold shipping zone related sqls */
                // $shipping_zone_sql = [];
                // $shipping_zone_locations_sql = [];
                // $shipping_zone_methods_sql = [];
                // $shipping_zone_options_sql = [];
                // $shipping_zone_relations_sql = [];

                /**
                 * Shipping zone entry in database
                 */
                // foreach ($shipping_zones as $zone) {
                //     $shipping_zone_sql[] = "($zone->id, '" . $zone->country . "', 0)";

                //     if ($zone->state) {
                //         $shipping_zone_locations_sql[] = "($zone->id, '{$zone->country}:{$zone->state}', 'state')";
                //     } else {
                //         $shipping_zone_locations_sql[] = "($zone->id, '$zone->country', 'country')";
                //     }
                //     if ( !empty($zone->zip)) {
                //         if (is_array($zone->zip)) {
                //             foreach ($zone->zip as $postcode) {
                //                 $shipping_zone_locations_sql[] = "($zone->id, '$postcode', 'postcode')";
                //             }
                //         } else {
                //             $shipping_zone_locations_sql[] = "($zone->id, '$zone->zip', 'postcode')";
                //         }
                //     }

                //     $shipping_zone_methods_sql[] = "($zone->id, $zone->id, 'reduced_rate', 1, 1)";

                //     $shipping_zone_options_sql[] = "('woocommerce_reduced_rate_" . $zone->id . "_settings', '" . addslashes(serialize([
                //             'min_order_price' => $zone->min_order_price,
                //             'shipping_rate' => $zone->shipping_rate,
                //             'regular_shipping_rate' => $zone->regular_shipping_rate
                //         ])) . "')";

                //     $shipping_zone_relations_sql[] = "($zone->id, $zone->id, $zone->division_id)";
                // }

                /**
                 * shipping zone relations insert queries
                 */
                // query to insert shipping zone
                // $wpdb->query("INSERT INTO `$woocommerce_shipping_zones` (`zone_id`, `zone_name`, `zone_order`) VALUES " . implode(", ", $shipping_zone_sql));
                // // query to insert shipping zone locations
                // $wpdb->query("INSERT INTO `$woocommerce_shipping_zone_locations` (`zone_id`, `location_code`, `location_type`) VALUES " . implode(", ", $shipping_zone_locations_sql));
                // // query to insert shipping zone methods
                // $wpdb->query("INSERT INTO `$woocommerce_shipping_zone_methods` (`zone_id`, `instance_id`, `method_id`, `method_order`, `is_enabled`) VALUES " . implode(", ", $shipping_zone_methods_sql));
                // // query to insert shipping zone options
                // $wpdb->query("INSERT INTO `$wpdb->options` (`option_name`, `option_value`) VALUES " . implode(", ", $shipping_zone_options_sql));
                // // query to insert shipping zone relations
                // $wpdb->query("INSERT INTO `$rental_shipping_zone_relations` (`id`, `rental_id`, `rental_division_id`) VALUES " . implode(", ", $shipping_zone_relations_sql));

                // if ($wpdb->last_error !== '') {
                //     throw new RentalException("SQL_ERROR: $wpdb->last_error (SQL: $wpdb->last_query)", RentalException::TYPE_SYNC_GLOBAL);
                // }


                
            // } else {
                // local pickup address (not based on zone nor mile)
        
                // TODO : check to see if there is a condition to create local_pickup when synchronizing
                // or it must be done (better way) when the shipping settings are saved in rentopian-sync plugin settings

                
                // insert Local Pickup shipping zone
                // $wpdb->insert($woocommerce_shipping_zones, [
                //     "zone_name" => 'Local Pickup',
                //     "zone_order" => 9999
                // ]);
                // $last_zone_id = $wpdb->insert_id;
                
                // foreach($divisions_synced as $division) {
                //     if ($division->main_division == 1) {
                //         $address = $division->address;

                //         // handle country/state
                //         $country = empty($address->country) ? 'US' : $address->country;
                //         $state = empty($address->state) ? '' : $address->state;
                //         if (empty($state)) {
                //             // insert only country
                //             $wpdb->insert($woocommerce_shipping_zone_locations, [
                //                 "zone_id" => $last_zone_id,
                //                 "location_code" => $country,
                //                 "location_type" => 'country'
                //             ]);
                //         } else {
                //             // insert country-state
                //             $country_state = $country.':'.$state;
                //             $wpdb->insert($woocommerce_shipping_zone_locations, [
                //                 "zone_id" => $last_zone_id,
                //                 "location_code" => $country_state,
                //                 "location_type" => 'state'
                //             ]);
                //         }

                //         // insert zip code
                //         // if (!empty($address->zip)) {
                //         //     $wpdb->insert($woocommerce_shipping_zone_locations, [
                //         //         "zone_id" => $last_zone_id,
                //         //         "location_code" => $address->zip,
                //         //         "location_type" => 'postcode'
                //         //     ]);
                //         // }


                //         // insert methods
                //         $wpdb->insert($woocommerce_shipping_zone_methods, [
                //             "zone_id" => $last_zone_id,
                //             "method_id" => 'local_pickup',
                //             "method_order" => 1,
                //             "is_enabled" => 1
                //         ]);
                        
                //     }
                // }
                
            // }
        // }

        // to bypass shipping rate cache
        // update_option('woocommerce_shipping_debug_mode', 'yes');
    }

    rental_insert("INSERT INTO `$wpdb->terms` (`term_id`, `name`, `slug`, `term_group`) VALUES", $terms_sql);

    rental_insert("INSERT INTO `$wpdb->termmeta` (`term_id`, `meta_key`, `meta_value`) VALUES", $termmeta_sql);

    rental_insert("INSERT INTO `$wpdb->term_taxonomy` (`term_taxonomy_id`, `term_id`, `taxonomy`, `description`, `parent`, `count`) VALUES", $term_taxonomy_sql);

    rental_insert("INSERT INTO `$wpdb->term_relationships` (`object_id`, `term_taxonomy_id`, `term_order`) VALUES", $term_relation_sql, 800);

    rental_insert("INSERT INTO `$wpdb->posts` (`id`, `post_author`, `post_date`,
                `post_date_gmt`, `post_title`, `post_content`, `post_excerpt`, `post_status`,
                `comment_status`, `ping_status`, `post_name`, `to_ping`, `pinged`, `post_modified`,
                `post_modified_gmt`, `post_content_filtered`, `post_parent`, `guid`,`post_type`) VALUES", $product_sql, 500);
    rental_insert("INSERT INTO `$wpdb->posts` (`id`, `post_author`, `post_date`,
                `post_date_gmt`, `post_title`, `post_content`, `post_excerpt`, `post_status`,
                `comment_status`, `ping_status`, `post_name`, `to_ping`, `pinged`, `post_modified`,
                `post_modified_gmt`, `post_content_filtered`, `post_parent`, `guid`,`post_type`) VALUES", $variant_sql, 500);

    rental_insert("INSERT INTO `$wpdb->postmeta` (`post_id`, `meta_key`, `meta_value`) VALUES", $productmeta_sql, 300);
    rental_insert("INSERT INTO `$wpdb->postmeta` (`post_id`, `meta_key`, `meta_value`) VALUES", $variantmeta_sql, 300);

    rental_insert("INSERT INTO `$rental_product_relations` (`id`, `rental_id`, `rental_division_id`) VALUES", $product_relations_sql, 800);

    rental_insert("INSERT INTO `$rental_variant_relations` (`id`, `rental_id`, `rental_division_id`) VALUES", $variant_relations_sql, 800);

    rental_insert("INSERT INTO `$rental_set_relations` (`id`, `rental_id`, `rental_division_id`) VALUES", $set_relations_sql, 800);

    if (isset($product_meta_lookup_sql)) {
        rental_insert("INSERT INTO `$wpdb->wc_product_meta_lookup` (`product_id`, `sku`, `virtual`, `downloadable`, " .
            "`min_price`, `max_price`, `onsale`, `stock_quantity`, `stock_status`, `tax_status`) VALUES", $product_meta_lookup_sql, 500);
    }

    // passing excluded product ids into coupon add/sync function
    $exclude_product_ids = "";
    if (!empty($coupons_excluded_product_ids)) {
        $exclude_product_ids = implode(",", array_unique($coupons_excluded_product_ids) );
    }

    // inserting WP coupons/rental_coupon_relations
    $last_insert_id = rental_add_coupons($set_id, $exclude_product_ids);

    // inserting rental_price_multipliers
    rental_add_price_multipliers();

    
    // sync product up sells and cross sells
    rental_set_product_up_sells_cross_sells($product_up_sells, $product_cross_sells, $product_ids_for_up_cross_sells);
    
    // sync sets up sells and cross sells
    rental_set_sets_up_sells_cross_sells($set_up_sells_from_sets, $set_up_sells_from_products,
    $set_cross_sells_from_sets, $set_cross_sells_from_products, 
    $set_ids , $product_ids_for_up_cross_sells);


    // inserting rental inventory blocks
    rental_add_inventory_blocks();

    $sql= "";
    if ( !empty($category_relations_sql)) {
        $category_relations_sql = implode(", ", $category_relations_sql);
        $sql .= "INSERT INTO `$rental_category_relations` (`id`, `rental_id`) VALUES $category_relations_sql;";
    }
    if ( !empty($tag_relations_sql)) {
        $tag_relations_sql = implode(", ", $tag_relations_sql);
        $sql .= "INSERT INTO `$rental_tag_relations` (`id`, `rental_id`) VALUES $tag_relations_sql;";
    }

    if ( !empty($sets_tag_relations_sql)) {
        $sets_tag_relations_sql = implode(", ", $sets_tag_relations_sql);
        $sql .= "INSERT INTO `$rental_sets_tag_relations` (`id`, `rental_id`) VALUES $sets_tag_relations_sql;";
    }

    if ( !empty($brand_relations_sql)) {
        $brand_relations_sql = implode(", ", $brand_relations_sql);
        $sql .= "INSERT INTO `$rental_brand_relations` (`id`, `rental_id`) VALUES $brand_relations_sql;";
    }
    dbDelta($sql);

    // inserting rental product options
    rental_add_product_options();
    // inserting rental inventory sets options
    rental_add_set_options();

    rental_set_no_customer_pickup_items($shipping_settings);

    $delivery_time_selections = isset($shipping_settings->delivery_time_selections) && $shipping_settings->delivery_time_selections ? $shipping_settings->delivery_time_selections : [];
    update_option('delivery_time_selections', $delivery_time_selections);

    $no_index_items = [];
    if ($products_to_hide) {

        $no_index_items = $products_to_hide;

        foreach($products_to_hide as $product_id) {
            rental_set_product_catalog_visibility($product_id, 'hidden');
        }
    }

    if ( class_exists( 'WooCommerce_Single_Variations' ) && defined('WC_SINGLE_VAR_VERSION')) {
        $admin_wcs_variation = new WooCommerce_Single_Variations_Admin('plugin', WC_SINGLE_VAR_VERSION);
        $admin_wcs_variation->init();
        $admin_wcs_variation->update_variations(false, true);
        $admin_wcs_variation->reset_transients(false);
    }

    if ($do_not_index_hidden_duplicate_products_for_seo && get_option('rental_location_based_duplicate_filter', 0)) {

        if ($no_index_items) {
            $no_index_items = array_merge($no_index_items, $duplicate_product_ids);
        } else {
            $no_index_items = $duplicate_product_ids;
        }
    } 

    if (get_option('rental_no_index_items', [])) {
        update_option('rental_no_index_items', []);
    }

    if (get_option('rental_not_private_items', [])) {
        update_option('rental_not_private_items', []);
    }


    if ($no_index_items) {
        update_option('rental_no_index_items', $no_index_items);
    }

    if ($set_items_collection) {
        update_option('rental_not_private_items', $set_items_collection);
    }


    variants_stock_to_be_updated($variants_to_update_qty);

    // unlock tables
    $sql = "UNLOCK TABLES;";
    dbDelta($sql);

    // sorting the categories after inserting them relations
    sort_categories(json_decode(stripslashes(json_encode($categories))), false);

    if ($wpdb->last_error !== '') {
        throw new RentalException("SQL_ERROR: $wpdb->last_error (SQL: $wpdb->last_query)", RentalException::TYPE_SYNC_GLOBAL);
    }

    return true;
}

function variants_stock_to_be_updated($variants_to_update_qty) {
    if ($variants_to_update_qty && get_option('rental_location_based_duplicate_filter', 0)) {
        global $wpdb, $rental_tables;
        $rental_product_relations = $wpdb->prefix . $rental_tables["product_relations"];

        foreach($variants_to_update_qty as $variant_data) {

            if (isset($variant_data['variant_id']) && $variant_data['variant_id'] 
                && isset($variant_data['qty']) && $variant_data['qty']
            ) {

                update_post_meta($variant_data['variant_id'], '_stock', $variant_data['qty']);

                $wpdb->update( $wpdb->wc_product_meta_lookup, [ 
                    'stock_quantity' => $variant_data['qty']
                ], ['product_id' => $variant_data['variant_id']] );
            }
           
            
            if (
                isset($variant_data['rental_product_id']) && $variant_data['rental_product_id'] 
                && isset($variant_data['division_id']) && $variant_data['division_id']
                && isset($variant_data['qty']) && $variant_data['qty']
            ) {

                $rental_product_id = $variant_data['rental_product_id'];
                $division_id = $variant_data['division_id'];

                $pid = $wpdb->get_var("SELECT `id` FROM $rental_product_relations WHERE `rental_id` = $rental_product_id AND `rental_division_id` = $division_id");

                if ($pid) {
                    update_post_meta($pid, '_stock', $variant_data['qty']);
    
                    $wpdb->update( $wpdb->wc_product_meta_lookup, [ 
                        'stock_quantity' => $variant_data['qty']
                    ], ['product_id' => $pid] );
                }
            }
           
        }
    }
}

function toggle_index_yoast_seo($product_id, $do_not_index = 1) {
    
    if (defined('WPSEO_VERSION')) {
        global $wpdb;
        $yoast_indexable = $wpdb->prefix . 'yoast_indexable';

        $meta_key_index = '_yoast_wpseo_meta-robots-noindex';
        $meta_key_follow = '_yoast_wpseo_meta-robots-nofollow';

        if ($wpdb->get_var( "SHOW TABLES LIKE '{$yoast_indexable}'" ) == $yoast_indexable) {

            if ($do_not_index) {

                $updatable_data = [
                    'is_robots_noindex' => 1,
                    'is_robots_nofollow' => 1,
                    'is_robots_noarchive' => 1,
                    'is_robots_noimageindex' => 1,
                    'is_robots_nosnippet' => 1,
                ];
                $wpdb->update($yoast_indexable, $updatable_data, ['object_id' => $product_id]);

                // Set noindex (1 = noindex, 0 = index)
                update_post_meta($product_id, $meta_key_index, '1');
                
                // Set nofollow (1 = nofollow, 0 = follow)
                update_post_meta($product_id, $meta_key_follow, '1');
        
            } else {
        
                $updatable_data = [
                    'is_robots_noindex' => null,
                    'is_robots_nofollow' => null,
                    'is_robots_noarchive' => null,
                    'is_robots_noimageindex' => null,
                    'is_robots_nosnippet' => null,
                ];
                $wpdb->update($yoast_indexable, $updatable_data, ['object_id' => $product_id]);

                // Set noindex (1 = noindex, 0 = index)
                update_post_meta($product_id, $meta_key_index, '0');
                
                // Set nofollow (1 = nofollow, 0 = follow)
                update_post_meta($product_id, $meta_key_follow, '0');
            }

        }
    }
}

function sort_categories($categories, $from_api = true) {

    if ($categories) {

        global $wpdb, $rental_tables;
        $rental_category_relations = $wpdb->prefix . $rental_tables["category_relations"];

        if ($from_api) {

            foreach($categories as $category_id => $category) {
                $cat_id = $wpdb->get_var($wpdb->prepare( "SELECT `id` FROM $rental_category_relations WHERE `rental_id` = %d", $category_id ));
                resort_categories($cat_id, $category, $wpdb, $rental_category_relations);
            }

        } else {

            foreach($categories as $category) {
                $cat_id = $wpdb->get_var($wpdb->prepare( "SELECT `id` FROM $rental_category_relations WHERE `rental_id` = %d", $category->id ));
                resort_categories($cat_id, $category, $wpdb, $rental_category_relations);
            }

        }
        
    }

}

function resort_categories($cat_id, $category, $wpdb, $rental_category_relations) {
    if ($cat_id) {
        // check if the category has a parent
        $parent = 0;
        if (isset($category->parent_id)) {
            $parent_id = $wpdb->get_var($wpdb->prepare("SELECT `id` FROM $rental_category_relations WHERE `rental_id` = %d", $category->parent_id));
            if ($parent_id) {
                $parent = $parent_id;
            }
        }

        // update category's order and parent
        wp_update_term($cat_id, 'product_cat', ['parent' => $parent]);
        update_term_meta($cat_id, "order", $category->order);
    }
}

// set product upsell / crosssell ids
function rental_set_product_up_sells_cross_sells($product_up_sells, $product_cross_sells, $product_ids_for_up_cross_sells) {

    // upsells
    foreach($product_up_sells as $wp_product_id=>$rental_up_sell_pack) {

        if ($rental_up_sell_pack) {
            // collect wp upsell product ids
            $wp_up_sell_pack = [];
            foreach($rental_up_sell_pack as $rental_product_id) {
                if (isset($product_ids_for_up_cross_sells[$rental_product_id]) ) {

                    if (count($product_ids_for_up_cross_sells[$rental_product_id]) > 1) {
                        // multiple division

                        foreach($product_ids_for_up_cross_sells[$rental_product_id] as $wp_product_id_with_up_sells) {

                            if (!in_array($wp_product_id_with_up_sells, $wp_up_sell_pack)) {
                                $wp_up_sell_pack[] = $wp_product_id_with_up_sells;
                            }
                        }

                    } else {
                        // single division

                        $wp_product_id_with_up_sells = isset($product_ids_for_up_cross_sells[$rental_product_id][0]) ? $product_ids_for_up_cross_sells[$rental_product_id][0] : 0;
                        
                        if ($wp_product_id_with_up_sells && !in_array($wp_product_id_with_up_sells, $wp_up_sell_pack)) {
                            $wp_up_sell_pack[] = $wp_product_id_with_up_sells;
                        }
                    }
                }
            }

            wp_set_object_terms($wp_product_id, $wp_up_sell_pack, '_upsell_ids');
            update_post_meta($wp_product_id, '_upsell_ids', $wp_up_sell_pack);
        } else {

            // remove all
            wp_set_object_terms($wp_product_id, [], '_upsell_ids');
            update_post_meta($wp_product_id, '_upsell_ids', []);
        }
    }

    // crosssells
    foreach($product_cross_sells as $wp_product_id=>$rental_cross_sell_pack) {

        if ($rental_cross_sell_pack) {
            // collect wp upsell product ids
            $wp_cross_sell_pack = [];
            foreach($rental_cross_sell_pack as $rental_product_id) {
                if (isset($product_ids_for_up_cross_sells[$rental_product_id]) ) {

                    if (count($product_ids_for_up_cross_sells[$rental_product_id]) > 1) {
                        // multiple division

                        foreach($product_ids_for_up_cross_sells[$rental_product_id] as $wp_product_id_with_cross_sells) {

                            if (!in_array($wp_product_id_with_cross_sells, $wp_cross_sell_pack)) {
                                $wp_cross_sell_pack[] = $wp_product_id_with_cross_sells;
                            }
                        }

                    } else {
                        // single division

                        $wp_product_id_with_cross_sells = isset($product_ids_for_up_cross_sells[$rental_product_id][0]) ? $product_ids_for_up_cross_sells[$rental_product_id][0] : 0;
                        
                        if ($wp_product_id_with_cross_sells && !in_array($wp_product_id_with_cross_sells, $wp_cross_sell_pack)) {
                            $wp_cross_sell_pack[] = $wp_product_id_with_cross_sells;
                        }
                    }
                }
            }

            wp_set_object_terms($wp_product_id, $wp_cross_sell_pack, '_crosssell_ids');
            update_post_meta($wp_product_id, '_crosssell_ids', $wp_cross_sell_pack);
        } else {

            // remove all
            wp_set_object_terms($wp_product_id, [], '_crosssell_ids');
            update_post_meta($wp_product_id, '_crosssell_ids', []);
        }
    }
}


// set product upsell / crosssell ids
function rental_set_product_up_sells_cross_sells_for_api($product_up_sells, $product_cross_sells) {

    // collecting & creating product ids lookup table
    if (!empty($product_up_sells) || !empty($product_cross_sells)) {
        global $wpdb, $rental_tables;
        $rental_product_relations = $wpdb->prefix . $rental_tables["product_relations"];

        $product_ids = $wpdb->get_results("SELECT `id`, `rental_id` FROM $rental_product_relations");
        $product_ids_look_up_table = [];
        foreach($product_ids as $product_row) {
            $product_ids_look_up_table[$product_row->rental_id] = $product_row->id;
        }
    }

    // upsells
    foreach($product_up_sells as $wp_product_id=>$rental_up_sell_pack) {

        if (!empty($rental_up_sell_pack)) {
            // collect wp upsell product ids
            $wp_up_sell_pack = [];
            foreach($rental_up_sell_pack as $rental_product_id) {
                if (isset($product_ids_look_up_table[$rental_product_id]) ) {
                    $wp_upsell_product_id = $product_ids_look_up_table[$rental_product_id];
                    if (!in_array($wp_upsell_product_id, $wp_up_sell_pack)) {
                        $wp_up_sell_pack[] = $wp_upsell_product_id;
                    }
                }
            }

            wp_set_object_terms($wp_product_id, $wp_up_sell_pack, '_upsell_ids');
            update_post_meta($wp_product_id, '_upsell_ids', $wp_up_sell_pack);
        } else {
            // remove all
            wp_set_object_terms($wp_product_id, [], '_upsell_ids');
            update_post_meta($wp_product_id, '_upsell_ids', []);
        }

    }

    // crosssells
    foreach($product_cross_sells as $wp_product_id=>$rental_cross_sell_pack) {

        if (!empty($rental_cross_sell_pack)) {
            // collect wp upsell product ids
            $wp_cross_sell_pack = [];
            foreach($rental_cross_sell_pack as $rental_product_id) {
                if (isset($product_ids_look_up_table[$rental_product_id]) ) {
                    $wp_cross_sell_product_id = $product_ids_look_up_table[$rental_product_id];
                    if (!in_array($wp_cross_sell_product_id, $wp_cross_sell_pack)) {
                        $wp_cross_sell_pack[] = $wp_cross_sell_product_id;
                    }
                }
            }

            wp_set_object_terms($wp_product_id, $wp_cross_sell_pack, '_crosssell_ids');
            update_post_meta($wp_product_id, '_crosssell_ids', $wp_cross_sell_pack);
        } else {
            // remove all
            wp_set_object_terms($wp_product_id, [], '_crosssell_ids');
            update_post_meta($wp_product_id, '_crosssell_ids', []);
        }

    }

}


function rental_set_sets_up_sells_cross_sells($set_up_sells_from_sets, $set_up_sells_from_products,
    $set_cross_sells_from_sets, $set_cross_sells_from_products, 
    $set_ids , $product_ids_for_up_cross_sells) {

    // upsells
    $wp_up_sells_pack = [];
    foreach($set_up_sells_from_sets as $wp_set_id => $rental_up_sell_pack) {

        // remove all
        wp_set_object_terms($wp_set_id, [], '_upsell_ids');
        update_post_meta($wp_set_id, '_upsell_ids', []);

        if ($rental_up_sell_pack) {
            // collect wp upsell set ids
            $wp_set_up_sell_pack = [];
            foreach($rental_up_sell_pack as $rental_set_id) {
                if (isset($set_ids[$rental_set_id]) ) {

                    $wp_set_id_with_up_sells = $set_ids[$rental_set_id];
                    
                    if (!in_array($wp_set_id_with_up_sells, $wp_set_up_sell_pack)) {
                        $wp_set_up_sell_pack[] = $wp_set_id_with_up_sells;
                    }
                }
            }

            $wp_up_sells_pack[$wp_set_id] = $wp_set_up_sell_pack;
        }
    }

    foreach($set_up_sells_from_products as $wp_set_id => $rental_up_sell_pack) {

        // remove all
        wp_set_object_terms($wp_set_id, [], '_upsell_ids');
        update_post_meta($wp_set_id, '_upsell_ids', []);

        $wp_product_up_sell_pack = [];
        if ($rental_up_sell_pack) {
            // collect wp upsell product ids
            foreach($rental_up_sell_pack as $rental_product_id) {
                if (isset($product_ids_for_up_cross_sells[$rental_product_id]) ) {

                    if (count($product_ids_for_up_cross_sells[$rental_product_id]) > 1) {
                        // multiple division

                        foreach($product_ids_for_up_cross_sells[$rental_product_id] as $wp_product_id_with_up_sells) {

                            if (!in_array($wp_product_id_with_up_sells, $wp_product_up_sell_pack)) {
                                $wp_product_up_sell_pack[] = $wp_product_id_with_up_sells;
                            }
                        }

                    } else {
                        // single division

                        $wp_product_id_with_up_sells = isset($product_ids_for_up_cross_sells[$rental_product_id][0]) ? $product_ids_for_up_cross_sells[$rental_product_id][0] : 0;

                        if ($wp_product_id_with_up_sells && !in_array($wp_product_id_with_up_sells, $wp_product_up_sell_pack)) {
                            $wp_product_up_sell_pack[] = $wp_product_id_with_up_sells;
                        }
                    }
                }
            }
        }


        if ($wp_product_up_sell_pack) {
            if (isset($wp_up_sells_pack[$wp_set_id]) && $wp_up_sells_pack[$wp_set_id]) {
                $wp_up_sells_pack[$wp_set_id] = array_merge($wp_up_sells_pack[$wp_set_id], $wp_product_up_sell_pack);
            } else {
                $wp_up_sells_pack[$wp_set_id] = $wp_product_up_sell_pack;
            }
        }
            
        if (isset($wp_up_sells_pack[$wp_set_id]) && $wp_up_sells_pack[$wp_set_id]) {
            wp_set_object_terms($wp_set_id, $wp_up_sells_pack[$wp_set_id], '_upsell_ids');
            update_post_meta($wp_set_id, '_upsell_ids', $wp_up_sells_pack[$wp_set_id]);
        }
    }

    
    // cross sells
    $wp_cross_sells_pack = [];
    foreach($set_cross_sells_from_sets as $wp_set_id => $rental_cross_sell_pack) {

        // remove all
        wp_set_object_terms($wp_set_id, [], '_crosssell_ids');
        update_post_meta($wp_set_id, '_crosssell_ids', []);

        if ($rental_cross_sell_pack) {
            // collect wp upsell set ids
            $wp_cross_sells_pack = [];
            foreach($rental_cross_sell_pack as $rental_set_id) {
                if (isset($set_ids[$rental_set_id]) ) {

                    $wp_set_id_with_cross_sells = $set_ids[$rental_set_id];
                    
                    if (!in_array($wp_set_id_with_cross_sells, $wp_cross_sells_pack)) {
                        $wp_cross_sells_pack[] = $wp_set_id_with_cross_sells;
                    }
                }
            }

            $wp_cross_sells_pack[$wp_set_id] = $wp_cross_sells_pack;

        }
    }


    foreach($set_cross_sells_from_products as $wp_set_id => $rental_cross_sell_pack) {

        // remove all
        wp_set_object_terms($wp_set_id, [], '_crosssell_ids');
        update_post_meta($wp_set_id, '_crosssell_ids', []);

        $wp_product_cross_sell_pack = [];
        if ($rental_cross_sell_pack) {
            // collect wp upsell product ids
            foreach($rental_cross_sell_pack as $rental_product_id) {
                if (isset($product_ids_for_up_cross_sells[$rental_product_id]) ) {

                    if (count($product_ids_for_up_cross_sells[$rental_product_id]) > 1) {
                        // multiple division

                        foreach($product_ids_for_up_cross_sells[$rental_product_id] as $wp_product_id_with_cross_sells) {

                            if (!in_array($wp_product_id_with_cross_sells, $wp_product_cross_sell_pack)) {
                                $wp_product_cross_sell_pack[] = $wp_product_id_with_cross_sells;
                            }
                        }

                    } else {
                        // single division

                        $wp_product_id_with_cross_sells = isset($product_ids_for_up_cross_sells[$rental_product_id][0]) ? $product_ids_for_up_cross_sells[$rental_product_id][0] : 0;

                        if ($wp_product_id_with_cross_sells && !in_array($wp_product_id_with_cross_sells, $wp_product_cross_sell_pack)) {
                            $wp_product_cross_sell_pack[] = $wp_product_id_with_cross_sells;
                        }
                    }
                }
            }
        }

        if ($wp_product_cross_sell_pack) {
            if (isset($wp_cross_sells_pack[$wp_set_id]) && $wp_cross_sells_pack[$wp_set_id]) {
                $wp_cross_sells_pack[$wp_set_id] = array_merge($wp_cross_sells_pack[$wp_set_id], $wp_product_cross_sell_pack);
            } else {
                $wp_cross_sells_pack[$wp_set_id] = $wp_product_cross_sell_pack;
            }
        }
            
        if (isset($wp_cross_sells_pack[$wp_set_id]) && $wp_cross_sells_pack[$wp_set_id]) {
            wp_set_object_terms($wp_set_id, $wp_cross_sells_pack[$wp_set_id], '_crosssell_ids');
            update_post_meta($wp_set_id, '_crosssell_ids', $wp_cross_sells_pack[$wp_set_id]);
        }
    }

}

function getDayNumberByDayName($day_name, $rentopian_system = true) {
    
    if ($rentopian_system) {

        $days = [
            'Monday' => 1,
            'Tuesday' => 2,
            'Wednesday' => 3,
            'Thursday' => 4,
            'Friday' => 5,
            'Saturday' => 6,
            'Sunday' => 7,
        ];
    } else {

        // Plugin system
        $days = [
            'Monday' => 1,
            'Tuesday' => 2,
            'Wednesday' => 3,
            'Thursday' => 4,
            'Friday' => 5,
            'Saturday' => 6,
            'Sunday' => 0,
        ];
    }
   
    return $days[$day_name] ?? -1;
}

function getDayNameByNumber($day_num, $rentopian_system = true) {

    if ($rentopian_system) {

        $days = [
            // '0' => 'Everyday',
            '1' => 'Monday',
            '2' => 'Tuesday',
            '3' => 'Wednesday',
            '4' => 'Thursday',
            '5' => 'Friday',
            '6' => 'Saturday',
            '7' => 'Sunday'
        ];

    } else {

        // Plugin system
        $days = [
            '0' => 'Sunday',
            '1' => 'Monday',
            '2' => 'Tuesday',
            '3' => 'Wednesday',
            '4' => 'Thursday',
            '5' => 'Friday',
            '6' => 'Saturday',
        ];
    }
   
    return $days[$day_num] ?? '';
}

function rental_validate_dates($opt_hide_time, $opt_hide_zip, $start_date, $end_date, $zip, $error = '') {
        
    $error = $error ? $error : null;

    $start_date_timstamp = strtotime($start_date);

    $zip = $opt_hide_zip? null: $zip;
    
    $start_time = get_option('rental_default_start_time', '9:00 AM');
    $end_time = get_option('rental_default_end_time', '05:00 PM');
    
    $exploded_start_date = explode(" ", $start_date);
    if ($opt_hide_time && !isset($exploded_start_date[1])) {
        $start_date .= " $start_time";
    } else {
        $start_time = date('g:i A', $start_date_timstamp);
    }
    
    $exploded_end_date = explode(" ", $end_date);
    if (isset($end_date)) {
        if ($opt_hide_time && !isset($exploded_end_date[1])) {
            $end_date .= " $end_time";
        }
    } else {
        $end_date = date('Y/m/d', $start_date_timstamp) . " $end_time";
    }
    if (get_option('rental_hide_end_date')) {
        $end_date = date('Y/m/d', $start_date_timstamp) . " $end_time";
    }

    $end_date_timstamp = strtotime($end_date);

    $start_date_obj = new DateTime($start_date);
    $end_date_obj = new DateTime($end_date);
    $interval = $start_date_obj->diff($end_date_obj);
    $opt_min_date_range = (int) get_option('rental_min_dates_range', 0);
    $opt_max_date_range = (int) get_option('rental_max_dates_range', 0);

    $opt_disabled_week_days = get_option('rental_disabled_week_days', '');

    if ($end_date_timstamp <= $start_date_timstamp) {
        $error.= __('Return date must be later than start date! ', 'rentopian-sync');
        
    } 
    if ( !empty($opt_min_date_range) && $opt_min_date_range > $interval->days) {
        $error.= __("The minimum interval between start and end dates is {$opt_min_date_range} day(s)! ", 'rentopian-sync');

    }
    if ( !empty($opt_max_date_range) && $opt_max_date_range < $interval->days) {
        $error.= __("The maximum interval between start and end dates is {$opt_max_date_range} day(s)! ", 'rentopian-sync');

    } 
    if ($opt_disabled_week_days) {

        $start_date_day = date("l", $start_date_timstamp);
        $start_date_day_num = getDayNumberByDayName($start_date_day, false);
        $end_date_day = date("l", $end_date_timstamp);
        $end_date_day_num = getDayNumberByDayName($end_date_day, false);

        // start date restriction check
        if (isset($opt_disabled_week_days[$start_date_day_num])) {
            $error.= __("{$start_date_day}(".date('M j', $start_date_timstamp).") is a restricted day! ", 'rentopian-sync');
        }
        // end date restriction check
        if (isset($opt_disabled_week_days[$end_date_day_num])) {
            $error.= __("{$end_date_day}(".date('M j', $end_date_timstamp).") is a restricted day! ", 'rentopian-sync');
        }

    } 

    return $error;
}
// selecting start/end date, zip code and address + filtering available products automated
function rental_validate_dates_form_and_get_products_data_init($opt_hide_time, $opt_hide_zip, $opt_show_location, $start_date, $end_date, $address, $zip) {
    $error = null;

    $rental_unavailable_items_opt = get_option('rental_unavailable_items');
    if ($rental_unavailable_items_opt && is_array($rental_unavailable_items_opt)) {
        update_option('rental_unavailable_items', '');
    }

    if ( !$start_date) {
        $error = __('Start date is required!', 'rentopian-sync');
    }
    if ($opt_show_location) {
        if (!isset($address) || !$address) {
            $error = __('Address is required!', 'rentopian-sync');
        }
    }
    if ( !$opt_hide_zip && ( !isset($zip) || !$zip)) {
        $error = __('ZIP code is required!', 'rentopian-sync');
    }
    if (isset($zip) && !$zip) {
        $error = __('ZIP code is invalid!', 'rentopian-sync');
    }

    $validateZipCodeDivisionsAndProductSettings = rental_request_product_settings($zip);

    try {
        
        $error = rental_validate_dates($opt_hide_time, $opt_hide_zip, $start_date, $end_date, $zip, $error);

        $address = $opt_show_location ? trim($address) : '';

        if (empty($error)) {
            // set data in cookies as well, to be able to work with WP Rocket
            
            $start_end_date_expire_time = time() + RENTOPIAN_DATE_EXPIRE_TIME;  

            $encrypted_rental_start_date = encrypt_data($start_date, get_option('rental_encryption_key'));
            $_COOKIE['rental_start_date'] = $encrypted_rental_start_date;
            setcookie('rental_start_date', $encrypted_rental_start_date, $start_end_date_expire_time, "/", "", false, true);

            $encrypted_rental_end_date = encrypt_data($end_date, get_option('rental_encryption_key'));
            $_COOKIE['rental_end_date'] = $encrypted_rental_end_date;
            setcookie('rental_end_date', $encrypted_rental_end_date, $start_end_date_expire_time, "/", "", false, true);

            $encrypted_rental_zip = $zip ? encrypt_data($zip, get_option('rental_encryption_key')) : true;
            $_COOKIE['rental_zip'] = $encrypted_rental_zip;
            setcookie('rental_zip', $encrypted_rental_zip, $start_end_date_expire_time, "/", "", false, false);

            $encrypted_rental_address = encrypt_data($address, get_option('rental_encryption_key'));
            $_COOKIE['rental_address'] = $encrypted_rental_address;
            setcookie('rental_address', $encrypted_rental_address, $start_end_date_expire_time, "/", "", false, true);

            
            update_option('rental_product_settings', $validateZipCodeDivisionsAndProductSettings);

            update_option('rental_unavailable_items', get_option('rental_filter_unavailable_products', 1) ? get_unavailable_products($start_date, $end_date, $zip ? $zip : 1) : []);
        }
           
    } catch (RentalException $e) {

        ErrorHandler::registerErrorInLog($e->getMessage(), $e->getFile(), $e->getLine(), $e->getType(), null, $e->getStatusCode());
        // $error = $e->getMessage();

        update_option('rental_product_settings', '');
    }

    if (!is_null($error)) {

        update_option('rental_product_settings', '');

        if (isset($_COOKIE['rental_zip'])) {
            unset($_COOKIE['rental_zip']);
            setcookie('rental_zip', '', time() - (31556952), "/", "", false, false);
        }
    }

    return $error;
}

function rental_validate_dates_form_and_get_products_data_with_cookie($opt_hide_time, $opt_hide_zip) {
    
    if ( !isset($_COOKIE['rental_start_date']) || !$_COOKIE['rental_start_date']) {

        return false;
    } elseif ( !$opt_hide_zip && ( !isset($_COOKIE['rental_zip']) || !$_COOKIE['rental_zip'])) {

        return false;
    } elseif (isset($_COOKIE['rental_zip']) && !$_COOKIE['rental_zip']) {

        return false;
    } else {

        $validateZipCodeDivisionsAndProductSettings = rental_request_product_settings($zip);

        try {

            $decrypted_rental_zip = decrypt_data($_COOKIE['rental_zip'], get_option('rental_encryption_key'));
            $zip = $opt_hide_zip? null: $decrypted_rental_zip;

            $start_time = get_option('rental_default_start_time', '9:00 AM');
            $end_time = get_option('rental_default_end_time', '05:00 PM');

            $decrypted_rental_start_date = decrypt_data($_COOKIE['rental_start_date'], get_option('rental_encryption_key'));
            $start_date = $decrypted_rental_start_date;

            if ($opt_hide_time) {
                $start_date .= " $start_time";
            } else {
                $start_time = date('g:i A', strtotime($start_date));
            }

            if (isset($_COOKIE['rental_end_date'])) {

                $decrypted_rental_end_date = decrypt_data($_COOKIE['rental_end_date'], get_option('rental_encryption_key'));
                $end_date = $decrypted_rental_end_date;

                if ($opt_hide_time) {
                    $end_date .= " $end_time";
                }
            } else {

                $end_date = date('Y/m/d', strtotime($decrypted_rental_start_date)) . " $end_time";
            }

            if (get_option('rental_hide_end_date')) {
                $end_date = date('Y/m/d', strtotime($decrypted_rental_start_date)) . " $end_time";
            }

            $start_date_ts = strtotime($start_date);
            $end_date_ts = strtotime($end_date);

            if ($end_date_ts <= $start_date_ts) {

                return false;
            } else {

                $start_end_date_expire_time = time() + RENTOPIAN_DATE_EXPIRE_TIME;  

                $encrypted_rental_start_date = encrypt_data($start_date, get_option('rental_encryption_key'));
                $_COOKIE['rental_start_date'] = $encrypted_rental_start_date;
                setcookie('rental_start_date', $encrypted_rental_start_date, $start_end_date_expire_time, "/", "", false, true);

                $encrypted_rental_end_date = encrypt_data($end_date, get_option('rental_encryption_key'));
                $_COOKIE['rental_end_date'] = $encrypted_rental_end_date;
                setcookie('rental_end_date', $encrypted_rental_end_date, $start_end_date_expire_time, "/", "", false, true);

                $encrypted_rental_zip = $zip ? encrypt_data($zip, get_option('rental_encryption_key')) : true;
                $_COOKIE['rental_zip'] = $encrypted_rental_zip;
                setcookie('rental_zip', $encrypted_rental_zip?: true, $start_end_date_expire_time, "/", "", false, false);

                update_option('rental_product_settings', $validateZipCodeDivisionsAndProductSettings);
            }

        } catch (RentalException $e) {
            ErrorHandler::registerErrorInLog($e->getMessage(), $e->getFile(), $e->getLine(), $e->getType(), null, $e->getStatusCode());
            // $error = $e->getMessage();

            update_option('rental_product_settings', '');
        }
        rental_remove_unavailable_cart_items();
    }

}

// function for create date form
function rental_create_date_form() {
    global $product;
    global $wp;
    $product_id = 0;
    $url = add_query_arg( $wp->query_vars, home_url( $wp->request ) );
    if (isset($product) && !empty($product)) {
        if (!$product->has_child()) {
            $product_id = $product->get_id();
        }
    }
    $check_rental_select_a_day_by_default = get_option('rental_select_a_day_by_default', 0);
    $check_rental_start_date = isset($_COOKIE['rental_start_date']) && $_COOKIE['rental_start_date'] ? 1 : 0;
    $dates_on_checkout = get_option('rental_dates_on_checkout', 0) == 1 && get_option('rental_allow_overbook', 0) == 1 ? 1 : 0;
    $form_filled = (isset($_COOKIE['rental_form_filled']) && $_COOKIE['rental_form_filled'] !== '') ? 1 : 0;

    if ( (!isset($_COOKIE['rental_form_filled']) || empty($_COOKIE['rental_form_filled'])) && $dates_on_checkout === 1) {
        $zip_code_text = get_option('rental_hide_zip') ? '' : 'and your delivery zip code';
        $form_text_on_top = "<p class='rental-form-text-on-top'> Please enter your rental dates {$zip_code_text} to proceed </p>";
        $div_overlay = '<div class="rental-overlay"></div>';
        echo $form_text_on_top . $div_overlay;
    }
    $div = '<div data-form-filled="'.$form_filled.'" data-dates-on-checkout="'.$dates_on_checkout.'" data-has-start-date="'.$check_rental_start_date.'" data-has-default-date="'.$check_rental_select_a_day_by_default.'" data-url="'.$url.'" data-pid="'.$product_id.'" id="rntp-form-holder"></div>';
    echo $div;
}

// function rental_add_last_selected_product_to_cart() {
//     if (empty($_COOKIE['rental_last_selected_product'])) {
//         return;
//     }

//     $product = json_decode($_COOKIE['rental_last_selected_product'], true);
//     if (isset($product['time']) && ($product['time'] + 300) > time() && rental_validate_cart_item($product['product_id'], $product['variation_id'], $product['quantity'])) {
        
//         $cart = WC()->cart;
//         $cart->add_to_cart($product['product_id'], $product['quantity'], $product['variation_id']);
//         $_COOKIE['rental_product_added_to_cart_message'] = wc_add_to_cart_message([$product['product_id'] => $product['quantity']], true, true);
//         setcookie('rental_product_added_to_cart_message', wc_add_to_cart_message([$product['product_id'] => $product['quantity']], true, true) , time() + (10800), "/", "", false, true);
//         // reset cache of cart total
//         $cart->calculate_totals();
//     }

//     unset($_COOKIE['rental_last_selected_product']);
//     setcookie('rental_last_selected_product', '', time() - (31556952), "/", "", false, true);
// }

// function to remove unavailable cart items
function rental_remove_unavailable_cart_items() {
    global $woocommerce;

    $cart_contents = $woocommerce->cart->cart_contents;
    if (empty($cart_contents)) {
        return false;
    }

    $inventories = [];
    foreach ($cart_contents as $cart_item) {
        if (get_post_meta($cart_item['product_id'], '_rental_is_set', true)) {
            continue;
        }
        $inv_id = get_post_meta($cart_item['variation_id']?: $cart_item['product_id'], '_rental_inventory_id', true);
        if ( !$inv_id) {
            $removed_items[] = $cart_item['key'];
            unset($woocommerce->cart->cart_contents[$cart_item['key']]);
            continue;
        }
        if ( !in_array($inv_id, $inventories)) {
            $inventories[] = $inv_id;
        }
        $cart_contents[$cart_item["key"]]["rental_inventory_id"] = $inv_id;
    }

    if (empty($inventories) || is_null($availability = rental_check_availability($inventories)) || empty($availability["inventories"])) {
        $woocommerce->cart->empty_cart();
        return false;
    }

    $removed_items = [];
    foreach ($cart_contents as $cart_item) {
        if ( !isset($cart_item["rental_inventory_id"])) {
            continue;
        }
        $parent_item_key = null;
        if (isset($cart_item["rental_add_on_of"])){
            $parent_item_key = $cart_item["rental_add_on_of"];
            if(in_array($parent_item_key, $removed_items)) {
                continue;
            }
        }
        if ( !isset($availability["inventories"][$cart_item["rental_inventory_id"]])
            || ( !$availability["allow_overbook"] && $cart_item["quantity"] > $availability["inventories"][$cart_item["rental_inventory_id"]]['quantity'])) {
            $key = $parent_item_key && $cart_item["rental_add_on_required"]? $parent_item_key: $cart_item["key"];
            $removed_items[] = $key;
            unset($woocommerce->cart->cart_contents[$key]);
        } elseif( !$availability["allow_overbook"]) {
            $availability["inventories"][$cart_item["rental_inventory_id"]]['quantity'] -= $cart_item["quantity"];
        }
    }

    foreach ($removed_items as $item_key) {
        do_action('woocommerce_cart_item_removed', $item_key, $woocommerce->cart);
    }

    // reset cache of cart total
    $woocommerce->cart->calculate_totals();

    return true;
}

function get_unavailable_products($start_date, $end_date = null, $zip = null) {
    if ( !isset($zip) || !isset($start_date)) {
        return null;
    }
    if (!get_option('rental_hide_end_date') && !isset($end_date)) {
        return null;
    }
    if (strtotime($start_date) < strtotime("today")) {
        return 'not_valid';
    }

    if(get_option('rental_allow_overbook', 1) == 1){
        return [];
    }

    try {
        return json_decode(rental_curl('inventories/bulk-availability/check', get_option('rental_api_key'), false, [
            // 'calculate_available_quantity' => get_option('rental_overbook_text')? 1: 0,
            'gmt_offset' => get_option('timezone_string')?: get_option('gmt_offset'),
            'start_date' => $start_date,
            'end_date' => $end_date,
            'division_id' => get_option('rental_select_division') && isset($_COOKIE['rental_division_id'])? $_COOKIE['rental_division_id']: '',
            'zip' => get_option('rental_hide_zip')? '': $zip
        ]), true);
    } catch (Exception $e) {
        return $e;
    }
}

function rental_dates_on_checkout_page_option_effect() {

    // if we have allow overbook and rental dates on checkout page
    if (!isset($_COOKIE['rental_zip'])) {
        $zip = get_option('rental_hide_zip') ? TRUE : get_shop_address(get_option('rental_divisions'));

        $start_end_date_expire_time = time() + RENTOPIAN_DATE_EXPIRE_TIME;

        $encrypted_rental_zip = encrypt_data($zip, get_option('rental_encryption_key'));
        $_COOKIE['rental_zip'] = $encrypted_rental_zip;
        setcookie('rental_zip', $encrypted_rental_zip, $start_end_date_expire_time, "/", "", false, false);

        // $_COOKIE['rental_zip'] = $zip;
        // setcookie("rental_zip", $zip, time() + (10800), "/", "", false, true);
    }

    if (!isset($_COOKIE['rental_start_date']) || !isset($_COOKIE['rental_end_date'])) {

        $opt_default_start_time = get_option('rental_default_start_time', '09:00 AM');
        $opt_default_end_time = get_option('rental_default_end_time', '05:00 PM');
        $today = date('Y/m/d h:ia', strtotime("today"));
        $tomorrow = date('Y/m/d h:ia', strtotime("tomorrow"));

        // set the default date/time based on selecting a day by default option
        $opt_select_a_day_by_default = get_option('rental_select_a_day_by_default', 0);
        if (isset($opt_select_a_day_by_default) && $opt_select_a_day_by_default == 1) {
            $opt_selected_default_day = get_option('rental_selected_default_day', 1);
            if ($opt_selected_default_day > 1) {
                $days_added_number = $opt_selected_default_day - 1;
                $day_string = $days_added_number == 1 ? "day" : "days";
                
                $days_added_string = "+".$days_added_number." ".$day_string;
                $today = date('Y/m/d h:ia', strtotime($days_added_string));

                $days_added_string = "+".($days_added_number + 1)." ".$day_string;
                $tomorrow = date('Y/m/d h:ia', strtotime($days_added_string));
            }
        }

        
        if ( $opt_rental_min_start_date_days = get_option('rental_min_start_date', 0) ) {

            $day_string = $opt_rental_min_start_date_days == 1 ? "day" : "days";
            $days_added_string = "+".$opt_rental_min_start_date_days." ".$day_string;
            $today = date('Y/m/d h:ia', strtotime($days_added_string));

            $days_added_string = "+".($opt_rental_min_start_date_days + 1)." ".$day_string;
            $tomorrow = date('Y/m/d h:ia', strtotime($days_added_string));
        }

    }

    $today_start = $today_end = $tomorrow_end = 0;
    if (!isset($_COOKIE['rental_start_date'])) {
        $today_exploded = explode(' ', $today);
        $today_start = $today_exploded[0] .' '. $opt_default_start_time;
    }


    if (!isset($_COOKIE['rental_end_date'])) {
        $today_exploded = explode(' ', $today);
        $today_end = $today_exploded[0] .' '. $opt_default_end_time;

        $tomorrow_exploded = explode(' ', $tomorrow);
        $tomorrow_end = $tomorrow_exploded[0] .' '. $opt_default_end_time;
    }

    if (
        $today_start 
        && $tomorrow_end
        && $today_end
    ) {

        $start_date_obj = new DateTime($today_start);
        $end_date_obj = new DateTime($tomorrow_end);
        $interval = $start_date_obj->diff($end_date_obj);

        $opt_min_date_range = (int) get_option('rental_min_dates_range', 0);
        $opt_max_date_range = (int) get_option('rental_max_dates_range', 0);

        if ($opt_min_date_range && $opt_min_date_range > $interval->days) {
            
            $calcDays = $opt_min_date_range - $interval->days;
            $tomorrow_end = date('Y/m/d h:ia', strtotime("$today_end +$calcDays day"));
        }

        if ( $opt_max_date_range && $opt_max_date_range < $interval->days) {

            $calcDays = $opt_max_date_range - $interval->days;
            $tomorrow_end = date('Y/m/d h:ia', strtotime("$today_end +$calcDays day"));
        }


        $start_end_date_expire_time = time() + RENTOPIAN_DATE_EXPIRE_TIME;

        $encrypted_rental_start_date = encrypt_data($today_start, get_option('rental_encryption_key'));
        $_COOKIE['rental_start_date'] = $encrypted_rental_start_date;
        setcookie("rental_start_date", $encrypted_rental_start_date, $start_end_date_expire_time, "/", "", false, true);

        $encrypted_rental_end_date = encrypt_data($tomorrow_end, get_option('rental_encryption_key'));
        $_COOKIE['rental_end_date'] = $encrypted_rental_end_date;
        setcookie("rental_end_date", $encrypted_rental_end_date, $start_end_date_expire_time, "/", "", false, true);
    }
}

// function to check available products real time from the core system
function rental_check_availability($inventories) {

    if (get_option('rental_dates_on_checkout', 0) == 1 && get_option('rental_allow_overbook', 0) == 1) {

        // if we allow overbook and rental dates on checkout page
        rental_dates_on_checkout_page_option_effect();

    } else {
        // usual journey

        if ( !isset($_COOKIE['rental_zip']) || !isset($_COOKIE['rental_start_date'])) {
            return 'not_set';
        }
        if (!get_option('rental_hide_end_date') && !isset($_COOKIE['rental_end_date'])) {
            return 'not_set';
        }

        $decrypted_rental_start_date = decrypt_data($_COOKIE['rental_start_date'], get_option('rental_encryption_key'));
        if (strtotime($decrypted_rental_start_date) < strtotime("today")) {
            return 'not_valid';
        }
    }
   
    // $allow_overbook = get_option('rental_allow_overbook', 1);
    // if($allow_overbook == 1){
    //     return true;
    // }

    try {

        $decrypted_rental_start_date = '';
        if (isset($_COOKIE['rental_start_date'])) {
            $decrypted_rental_start_date = decrypt_data($_COOKIE['rental_start_date'], get_option('rental_encryption_key'));
        }

        $decrypted_rental_end_date = '';
        if (isset($_COOKIE['rental_end_date'])) {
            $decrypted_rental_end_date = decrypt_data($_COOKIE['rental_end_date'], get_option('rental_encryption_key'));
        }

        $decrypted_rental_zip = '';
        if (isset($_COOKIE['rental_zip'])) {
            $decrypted_rental_zip = decrypt_data($_COOKIE['rental_zip'], get_option('rental_encryption_key'));
        }
        
        return json_decode(rental_curl('inventories/availability/check', get_option('rental_api_key'), false, [
            'calculate_available_quantity' => !get_option('rental_allow_overbook', 1),
            'gmt_offset' => get_option('timezone_string')?: get_option('gmt_offset'),
            // 'start_date' => isset($_COOKIE['rental_start_date'])? $_COOKIE['rental_start_date']: '',
            'start_date' => $decrypted_rental_start_date,
            'end_date' => $decrypted_rental_end_date,
            'division_id' => get_option('rental_select_division') && isset($_COOKIE['rental_division_id'])? $_COOKIE['rental_division_id']: '',
            'zip' => get_option('rental_hide_zip')? '': $decrypted_rental_zip,
            'inventories' => json_encode($inventories)
        ]), true);

    } catch (Exception $e) {

    }

    return null;
}

// function for get available hourly products
function rental_check_availability_hourly($inventories, $rental_start_date) {

    if ( get_option('rental_synchronized_product_type') != "hourly") {
        return null;
    }

    try {
        $result = json_decode(rental_curl('inventories/availability/check', get_option('rental_api_key'), false, [
            'calculate_available_quantity' => !get_option('rental_allow_overbook', 1),
            'gmt_offset' => get_option('timezone_string')?: get_option('gmt_offset'),
            'start_date' => $rental_start_date,
            'end_date' => '',
            'division_id' => get_option('rental_select_division') && isset($_COOKIE['rental_division_id'])? $_COOKIE['rental_division_id']: '',
            'zip' => '',
            'inventories' => json_encode($inventories)
        ]), true);

        return $result;
    } catch (Exception $e) {

    }

    return null;
}

// return true if the $haystack ends with the $needle
function ends_with($haystack, $needle) {
    return substr($haystack, -strlen($needle)) === $needle;
}

function set_hourly_start_end_date() {
    $all_options = wp_load_alloptions();
    $dates_seconds = [];

    foreach ($all_options as $option_name => $option_value) {
        if (
            strpos($option_name, '_rental_by_interval') !== false ||
            strpos($option_name, '_rental_by_slot') !== false
        ) {
            $value = maybe_unserialize($option_value);
            if (is_array($value) && isset($value['active']) && $value['active'] == 1) {
                $dates_seconds[] = strtotime($value["start_date"]);
            }
        }
    }


    if ($dates_seconds) {
        $start_date = date("Y/m/d", min($dates_seconds));
        // $date_max_seconds = max($dates_seconds) + 86400;
        $date_max_seconds = max($dates_seconds);
        $end_date = date("Y/m/d", $date_max_seconds);

        $_COOKIE["rental_hourly_start_date"] = $start_date;
        $_COOKIE["rental_hourly_end_date"] = $end_date;
        setcookie("rental_hourly_start_date", $start_date, time() + (10800), "/", "", false, true);
        setcookie("rental_hourly_end_date", $end_date, time() + (10800), "/", "", false, true);
    }
}


function unset_temporary_data() {

    $_COOKIE["rental_order_submitted"] = 1;
    setcookie("rental_order_submitted", 1, time() + (10800), "/", "", false, true);

    // if (isset($_COOKIE['rental_start_date'])) {
    //     unset($_COOKIE['rental_start_date']);
    //     setcookie('rental_start_date', '', time() - (31556952), "/", "", false, false);
    // }

    if ($set_ids_with_optional_items = get_set_ids_with_optional_items()) {

        foreach($set_ids_with_optional_items as $set_with_optional_items_id => $selected_product_key_variant_or_product_value_array) {
                
            $rental_set_items_default = get_post_meta($set_with_optional_items_id, '_rental_set_items_default', true);
            update_post_meta($set_with_optional_items_id, '_rental_set_items', $rental_set_items_default);
        }

        delete_option('_rental_set_ids_with_optional_items');
    }

    if ($set_with_variant_addons_exists_in_process_data = get_option('_rental_sets_with_variant_addons_exist_in_process', [])) {

        foreach($set_with_variant_addons_exists_in_process_data as $set_with_variant_addons_id_data) {

            // $set_id = $set_with_variant_addons_id_data['set_id'];
            $set_id = $set_with_variant_addons_id_data;
            $rental_set_items_default = get_post_meta($set_id, '_rental_set_items_default', true);
            update_post_meta($set_id, '_rental_set_items', $rental_set_items_default);
        }


        update_option('_rental_sets_with_variant_addons_exist_in_process', []);
    }

    // if (isset($_COOKIE['rental_end_date'])) {
    //     unset($_COOKIE['rental_end_date']);
    //     setcookie('rental_end_date', '', time() - (31556952), "/", "", false, false);
    // }

    // if (isset($_COOKIE['rental_zip'])) {
    //     unset($_COOKIE['rental_zip']);
    //     setcookie('rental_zip', '', time() - (31556952), "/", "", false, false);
    // }

    /*
    Notice : commenting out unused code
    TODO : rewrite later with WC()->session for hourly products

    $all_options = wp_load_alloptions();

    foreach ($all_options as $option_name => $option_value) {
        if (
            strpos($option_name, '_rental_by_interval') !== false ||
            strpos($option_name, '_rental_by_slot') !== false ||
            strpos($option_name, '_rental_by_interval_removed') !== false ||
            strpos($option_name, '_rental_by_slot_removed') !== false ||
            strpos($option_name, '_rental_by_interval_updated') !== false ||
            strpos($option_name, '_rental_by_slot_updated') !== false
        ) {
            delete_option($option_name);
        }
    }
    */


    if (get_rental_session_data('rental_product_options_valuables')) {
        delete_rental_session_data('rental_product_options_valuables');
    }

    
    $tracked_keys = WC()->session->get('tracked_rental_keys', []);

    if ( !empty($tracked_keys) ) {
        $selected_options = [];
        $selected_options_of_set = [];

        // Loop through each tracked key.
        foreach ( $tracked_keys as $session_key ) {
            // Check if the key is one of the selected options.
            if ( strpos( $session_key, '_selected_options' ) !== false ) {
                $selected_options[] = $session_key;
            }

            // Check if the key is one of the selected options of set.
            if ( strpos( $session_key, '_selected_options_of_set' ) !== false ) {
                $selected_options_of_set[] = $session_key;
            }
        }

        // Delete session data for each selected option.
        if ( !empty($selected_options) ) {
            foreach ( $selected_options as $key ) {
                delete_rental_session_data($key);
            }
        }

        // Delete session data for each selected option of set.
        if ( !empty($selected_options_of_set) ) {
            foreach ( $selected_options_of_set as $key ) {
                delete_rental_session_data($key);
            }
        }
    }
    

    
    // product order options
    if (get_rental_session_data('rental_order_selected_options', [])) {
        delete_rental_session_data('rental_order_selected_options');
    }

    // set order options
    if (get_rental_session_data('rental_order_selected_options_of_sets', [])) {
        delete_rental_session_data('rental_order_selected_options_of_sets');
    }

    // product uncertain addons data on a cart process
    // if(get_rental_session_data('rental_uncertain_add_ons', [])) {
    //     delete_rental_session_data('rental_uncertain_add_ons');
    // }

    if(isset($_COOKIE['rental_rentpro_coupon_code'])) {
        unset($_COOKIE['rental_rentpro_coupon_code']);
        setcookie('rental_rentpro_coupon_code', false, time() - (31556952), "/", "", false, false);
    }


    if (get_rental_session_data('wc_shipping_method', 0)) {
        delete_rental_session_data('wc_shipping_method');
    }

    if (isset($_COOKIE['rental_client_address_lat'])) {
        unset($_COOKIE['rental_client_address_lat']);
        setcookie('rental_client_address_lat', false, time() - (31556952), "/", "", false, false);
    }
    
    if (isset($_COOKIE['rental_client_address_lng'])) {
        unset($_COOKIE['rental_client_address_lng']);
        setcookie('rental_client_address_lng', false, time() - (31556952), "/", "", false, false);
    }


    if (get_rental_session_data('rental_delivery_venue_address_id', 0)) {
        delete_rental_session_data('rental_delivery_venue_address_id');
    }

    if (get_rental_session_data('charge_only_delivery_for_website', 0)) {
        delete_rental_session_data('charge_only_delivery_for_website');
    }
    
    if (get_rental_session_data('rental_pickup_venue_address_id', 0)) {
        delete_rental_session_data('rental_pickup_venue_address_id');
    }
    
    if (get_rental_session_data('rental_pickup_address_type', 0)) {
        delete_rental_session_data('rental_pickup_address_type');
    }
    
    if (get_rental_session_data('rental_delivery_cost', 0)) {
        delete_rental_session_data('rental_delivery_cost');
    }

    if (get_rental_session_data('rental_delivery_original_cost', 0)) {
        delete_rental_session_data('rental_delivery_original_cost');
    }

    if (get_rental_session_data('rental_pickup_original_cost', 0)) {
        delete_rental_session_data('rental_pickup_original_cost');
    }

    if (get_rental_session_data('rental_coupon_discount', 0)) {
        delete_rental_session_data('rental_coupon_discount');
    }

    if (get_rental_session_data('rental_pickup_cost', 0)) {
        delete_rental_session_data('rental_pickup_cost');
    }

    if (isset($_COOKIE['rental_different_pick_up_address'])) {
        unset($_COOKIE['rental_different_pick_up_address']);
        setcookie('rental_different_pick_up_address', false, time() - (31556952), "/", "", false, false);
    }

    if (isset($_COOKIE['rental_client_pickup_address_lat'])) {
        unset($_COOKIE['rental_client_pickup_address_lat']);
        setcookie('rental_client_pickup_address_lat', false, time() - (31556952), "/", "", false, false);
    }

    if (isset($_COOKIE['rental_client_pickup_address_lng'])) {
        unset($_COOKIE['rental_client_pickup_address_lng']);
        setcookie('rental_client_pickup_address_lng', false, time() - (31556952), "/", "", false, false);
    }

    if (isset($_COOKIE['rental_pick_up_city'])) {
        unset($_COOKIE['rental_pick_up_city']);
        setcookie('rental_pick_up_city', false, time() - (31556952), "/", "", false, false);
    }
    
    if (isset($_COOKIE['rental_pick_up_state'])) {
        unset($_COOKIE['rental_pick_up_state']);
        setcookie('rental_pick_up_state', false, time() - (31556952), "/", "", false, false);
    }

    if (isset($_COOKIE['rental_pick_up_address_1'])) {
        unset($_COOKIE['rental_pick_up_address_1']);
        setcookie('rental_pick_up_address_1', false, time() - (31556952), "/", "", false, false);
    }

    if (isset($_COOKIE['rental_pick_up_address_2'])) {
        unset($_COOKIE['rental_pick_up_address_2']);
        setcookie('rental_pick_up_address_2', false, time() - (31556952), "/", "", false, false);
    }

    if (isset($_COOKIE['rental_pick_up_country'])) {
        unset($_COOKIE['rental_pick_up_country']);
        setcookie('rental_pick_up_country', false, time() - (31556952), "/", "", false, false);
    }

    if (isset($_COOKIE['rental_pick_up_postcode'])) {
        unset($_COOKIE['rental_pick_up_postcode']);
        setcookie('rental_pick_up_postcode', false, time() - (31556952), "/", "", false, false);
    }

    unset_delivery_times_data();

    if (isset($_COOKIE['delivery_time_selections_id'])) {
        unset($_COOKIE['delivery_time_selections_id']);
        setcookie('delivery_time_selections_id', false, time() - (31556952), "/", "", false, false);
    }

    if (isset($_COOKIE['pickup_time_selections_id'])) {
        unset($_COOKIE['pickup_time_selections_id']);
        setcookie('pickup_time_selections_id', false, time() - (31556952), "/", "", false, false);
    }

}


function rental_request_product_settings($zip = null) {
	$data = [];
    if (get_option('rental_select_division')) {
        if ( !isset($_COOKIE['rental_division_id'])) {
            throw new RentalException(__('Please select location!', 'rentopian-sync'));
        }
        $data['division_id'] = $_COOKIE['rental_division_id'];
    }
	if ($zip && !get_option('rental_hide_zip')) {
		$data['zip'] = $zip;
	}
	$settings_data = json_decode(rental_curl('inventories', get_option('rental_api_key'), false, $data), true);
	$expiration_date = time() + 150;
	if ( !isset($settings_data['expiration_date']) || $settings_data['expiration_date'] > $expiration_date) {
		$settings_data['expiration_date'] = $expiration_date;
	}

	return $settings_data;
}

/*
 * get product settings from rentopian
 * 
*/
function rental_get_product_settings() {
    if (get_option('rental_synchronized_product_type') != "hourly") {

        if (get_option('rental_dates_on_checkout', 0) == 1 && get_option('rental_allow_overbook', 0) == 1) {
            // if we have allow overbook and rental dates on checkout page
            
            rental_dates_on_checkout_page_option_effect();
            
        } else {
            // usual journey

            if ( !isset($_COOKIE['rental_zip']) || !isset($_COOKIE['rental_start_date'])) {
                return null;
            }
        }
    }

    $rental_product_settings = get_option('rental_product_settings');

    // if ($rental_product_settings && isset($rental_product_settings['expiration_date']) && $rental_product_settings['expiration_date'] > time()) {
    //     return $rental_product_settings;
    // }

    try {

        $decrypted_rental_zip = '';
        if (isset($_COOKIE['rental_zip'])) {
            $decrypted_rental_zip = decrypt_data($_COOKIE['rental_zip'], get_option('rental_encryption_key'));
        }

        $rental_product_settings = rental_request_product_settings($decrypted_rental_zip);
        // Store product settings data in options
        update_option('rental_product_settings', $rental_product_settings);
        return $rental_product_settings;
        
    } catch (Exception $e) {
        // Handle exception
    }

    return null;
}


// get price multipliers by variant or set id
function get_price_multiplier_items_by_post_id($post_id) {
    global $wpdb, $rental_tables;
    $rental_price_multipliers = $wpdb->prefix . $rental_tables["price_multipliers"];

    $sql = "
        SELECT 
            p.id
            , price_multipliers.title price_multiplier_title
            , price_multipliers.items price_multiplier_items
            , price_multipliers.is_monthly
            , price_multipliers.is_repeat
        FROM 
            {$wpdb->posts} p
        LEFT JOIN {$wpdb->postmeta} pm_price_multiplier ON pm_price_multiplier.post_id = p.id AND pm_price_multiplier.meta_key = '_price_multiplier_id'
        LEFT JOIN {$rental_price_multipliers} price_multipliers ON price_multipliers.id = pm_price_multiplier.meta_value
        WHERE
            p.id = %d
    ";

    $result = $wpdb->get_row( $wpdb->prepare($sql, [$post_id]), ARRAY_A );
    if ($result) {
        $result['price_multiplier_items'] = isset($result['price_multiplier_items']) && $result['price_multiplier_items'] ? unserialize($result['price_multiplier_items']) : '';
        return $result;
    } else {
        return '';
    }
}

// get rental supported divisions
function rental_get_supported_divisions() {
    $settings = rental_get_product_settings();
    return isset($settings['divisions']) ? $settings['divisions'] : [];
}


function rental_get_products_variants_divisions() {

    if ($data = get_rental_cache('rental_products_variants_divisions', 'rental_products_variants_divisions_expiration_date')) {
        return $data;
    }

    global $wpdb, $rental_tables;
    $rental_variant_relations = $wpdb->prefix . $rental_tables["variant_relations"];
    $rental_product_relations = $wpdb->prefix . $rental_tables["product_relations"];

    $result_final = [];
    $sql = "
        SELECT 
            id,
            rental_division_id
        FROM 
            {$rental_variant_relations}
    ";
    $result = $wpdb->get_results($sql, ARRAY_A);

    if ($result) {
        $result_final = array_merge($result_final, $result);
    }

    $sql_prods = "
        SELECT 
            id,
            rental_division_id
        FROM 
            {$rental_product_relations}
    ";
    $result_prods = $wpdb->get_results($sql_prods, ARRAY_A);
   
    if ($result_prods) {
        $result_final = array_merge($result_final, $result_prods);
    }

    set_rental_cache($result_final, 'rental_products_variants_divisions', 'rental_products_variants_divisions_expiration_date');
    
    return $result_final;
}

function rental_get_sets_divisions() {

    if ($data = get_rental_cache('rental_sets_divisions', 'rental_sets_divisions_expiration_date')) {
        return $data;
    }


    global $wpdb, $rental_tables;
    $rental_set_relations = $wpdb->prefix . $rental_tables["set_relations"];

    $result_final = [];

    $sql_set = "
        SELECT 
            id,
            rental_division_id
        FROM 
            {$rental_set_relations}
    ";
    $result_set = $wpdb->get_results($sql_set, ARRAY_A);

    if ($result_set) {
        $result_final = array_merge($result_final, $result_set);
    }

    set_rental_cache($result_final, 'rental_sets_divisions', 'rental_sets_divisions_expiration_date');

    return $result_final;
}

// function to calculate multiplier for 7 days
function rental_get_daily_prices($price_multiplier) {
    $days = [];
    if ($price_multiplier) {
        for ($i = 1; $i <= 7; $i++) {
            $days[$i] = rental_calculate_price_multiplier($price_multiplier, $i);
        }
    }
    return $days;
}

// function for calculate price multiplier
function rental_calculate_price_multiplier($items, $days, $options = []) {
    // Remove any service item up front
    $items = array_filter($items, function($i) {
        return !isset($i['we_rate']);
    });

    // Re-index so $items[0] is always the first remaining element
    $items = array_values($items);

    // If we have no items left, or days is too small for the first bracket, just return days
    if (empty($items) || !isset($items[0]['min']) || $days <= ($items[0]['min'] / 24)) {
        return $days;
    }

    // Apply any monthly/repeat adjustments
    if (!empty($options)) {
        if (!empty($options['is_monthly'])) {
            $items = get_monthly_price_multiplier_days($items, $days);
        } elseif (!empty($options['is_repeat'])) {
            $items = get_repeat_price_multiplier_days($items, $days);
        }
    }

    $coefficient = (($items[0]['min'] ?? 0) / 24);
    $currentDay  = (($items[0]['max'] ?? 0) / 24);

    foreach ($items as $item) {
        // if there’s a gap between brackets for monthly/repeat, add it in
        if (!empty($options['is_monthly']) || !empty($options['is_repeat'])) {
            if (!empty($item['max']) && $currentDay < $item['min'] / 24) {
                $coefficient += ($item['min'] / 24 - $currentDay);
            }
        }
        $currentDay = $item['max'] / 24;

        // if $days falls inside this bracket, add the partial segment and return
        if (empty($item['max']) || $days <= ($item['max'] / 24)) {
            $coefficient += ($days - ($item['min'] / 24)) * $item['multiplier'];
            return $coefficient;
        }

        // otherwise add the full segment for this bracket
        $coefficient += (($item['max'] - $item['min']) / 24) * $item['multiplier'];
    }

    // if we’ve fallen out of the loop, days exceeded all defined brackets
    // add the remainder at a 1× multiplier
    $lastMax = end($items)['max'] / 24;
    $coefficient += ($days - $lastMax);
    return $coefficient;
}

// function rental_calculate_price_multiplier($items, $days, $options = []) {
//     if (empty($items) || $days <= ($items[0]['min'] / 24)) {
//         return $days;
//     }
//     // we need to delete service item to avoid problems
//     foreach($items as $k=>$i) {
//         if(isset($i['we_rate'])) {unset($items[$k]); break;}
//     }    

//     if ($options) {
//         if ($options['is_monthly'] == 1) {
//             $items = get_monthly_price_multiplier_days($items, $days);
//         } else if ($options['is_repeat'] == 1) {
//             $items = get_repeat_price_multiplier_days($items, $days);
//         }
//     }

//     $coefficient = $items[0]['min'] / 24;
//     $currentDay = $items[0]['max'] / 24;
//     foreach($items as $item) {
//         if ($options) {
//             if(($options['is_monthly'] == 1 || $options['is_repeat'] == 1) && $item['max'] && $currentDay < $item['min'] / 24) {
//                 $coefficient += $item['min'] / 24 - $currentDay;
//             }
//         }
//         $currentDay = $item['max'] / 24;

//         if ( !$item['max'] || $days <= ($item['max'] / 24)) {
//             $coefficient += ($days - ($item['min'] / 24)) * $item['multiplier'];
//             return $coefficient;
//         } else {
//             $coefficient += (($item['max'] - $item['min']) / 24) * $item['multiplier'];
//         }
//     }
//     $coefficient += ($days - ($item['max'] / 24));
//     return $coefficient;
// }

function get_monthly_price_multiplier_days($originalItems, $days) {
    $items = [];
    $lastMonth = 0;
    $multipliersLength = count($originalItems);
    $daysLeft = $days;

    $tz = rental_get_timezone();
    // $date_obj = (new DateTime($_COOKIE['rental_start_date'], $tz));
    
    $decrypted_rental_start_date = '';
    if (isset($_COOKIE['rental_start_date'])) {
        $decrypted_rental_start_date = decrypt_data($_COOKIE['rental_start_date'], get_option('rental_encryption_key'));
    }

    if ($decrypted_rental_start_date) {

        $date_obj = (new DateTime($decrypted_rental_start_date, $tz));

        $month = $date_obj->getTimestamp();
        
        $monthDays = date('t', $month);
        if ($monthDays > $daysLeft) {
            $monthDays = $daysLeft;
        }
        for ($d = 0; $d < $days; $d += $lastMonth) {
            for ($multiplier = 0; $multiplier < $multipliersLength; $multiplier++) {
                $max = $originalItems[$multiplier]['max'];
                $min = $originalItems[$multiplier]['min'];
                $offset = ($days - $daysLeft) * 24;
                if($min / 24 < $monthDays) {
                    $maxMax = $offset + $monthDays * 24;
                    $item = unserialize(serialize($originalItems[$multiplier]));
                    $item['max'] = $max && ($max + $offset < $maxMax) ? $max + $offset : $maxMax;
                    $item['min'] = $min + $offset;
                    $items[] = $item;
                }
            }

            $lastMonth = $monthDays;
            $daysLeft -= $lastMonth;
            $date_obj->modify('+1 month'); 
            $month = $date_obj->getTimestamp();
            $monthDays = date('t', $month);
            if ($monthDays > $daysLeft) {
                $monthDays = $daysLeft;
            }
        }
    }
    
    return $items;
}

function get_repeat_price_multiplier_days($originalItems, $days) {
    $items = [];
    $multipliersLength = count($originalItems);
    $daysLeft = $days;
    $multiDays = 0;

    for($d = 0; $d < $days; $d += $multiDays) {
        $multiDays = $originalItems[0]['min'] / 24;
        for ($multiplier = 0; $multiplier < $multipliersLength; $multiplier++) {
            $max = $originalItems[$multiplier]['max'];
            $min = $originalItems[$multiplier]['min'];
            $multiDays += ($max - $min) / 24;
            $offset = ($days - $daysLeft) * 24;
            if ($min / 24 < $daysLeft) {
                $maxMax = $days * 24;
                $item = unserialize(serialize($originalItems[$multiplier]));
                $item['max'] = $max && ($max + $offset < $maxMax) ? $max + $offset : $maxMax;
                $item['min'] = $min + $offset;
                $items[] = $item;
            }
        }

        $daysLeft -= $multiDays;
        if ($daysLeft < 0) {
            $multiDays = $daysLeft + $multiDays;
            $daysLeft = 0;
        }
    }
    return $items;
}

// function for get tax
function rental_get_tax() {
    global $woocommerce;

    if (get_option('rental_synchronized_product_type') == "hourly") {
        if ( !isset($_COOKIE["rental_hourly_start_date"])) {
            return null;
        }
    } else {
        if (get_option('rental_dates_on_checkout', 0) == 1 && get_option('rental_allow_overbook', 0) == 1) {
            // if we have allow overbook and rental dates on checkout page
            rental_dates_on_checkout_page_option_effect();
            
        } else {
            // usual journey
            if ( !isset($_COOKIE['rental_zip']) || !isset($_COOKIE['rental_start_date'])) {
                return null;
            }

        }
    }

    try {

        $zip = strip_zip_code_extensions($woocommerce->customer->get_shipping_postcode());
        $zip_key = 'rental_taxes_' . md5( (string) $zip );
        $expire_time = 600; // 10 minutes
        $rental_tax_type = get_option('rental_tax_type', 1);
        
        $cached = get_transient($zip_key);
        if ( $cached && isset($rental_tax_type) && $rental_tax_type == 2 ) {
            return $cached;
        }

        $shipping_city = $woocommerce->customer->get_shipping_city();
        $shipping_address = $woocommerce->customer->get_shipping_address_1();
        if ($shipping_address && $woocommerce->customer->get_shipping_address_2()) {
            $shipping_address .= ' ' . $woocommerce->customer->get_shipping_address_2();
        }

        $taxes = json_decode(rental_curl('taxes', get_option('rental_api_key'), false, [
            'zip' => $zip, 
            'address' => $shipping_address, 
            'city' => $shipping_city
        ]), true);

        if ($taxes) {
            
            if ( isset($taxes['auto_tax']) && $taxes['auto_tax'] == 1 && !empty($taxes['auto_tax_rates']) ) {
                
                // auto tax
                if (isset($rental_tax_type) && $rental_tax_type != 2) {
                    update_option('rental_tax_type', 2);
                }
                
                set_transient($zip_key, $taxes, $expire_time);

            } else {

                // manual tax
                if (isset($rental_tax_type) && $rental_tax_type != 1) {
                    update_option('rental_tax_type', 1);
                }

                update_option('rental_auto_tax', 0);
            }

            return $taxes;
        }
        
    } catch (Exception $e) {

    }

    return null;
}

function get_shop_address($rental_divisions) {
    //check if rental division is only one then just send its address
    if( count($rental_divisions) < 2 ){
        $shipping_rental_divison = $rental_divisions[0];
    }
    //else find selected division or use main division
    else{
        // if rental select division option is enabled and divion set in session
        if(get_option('rental_select_division') && (isset($_COOKIE['rental_division_id']) && !empty($_COOKIE['rental_division_id'])) ){
            $selected_division = $_COOKIE['rental_division_id'];

            $shipping_rental_divison = '';
            foreach( $rental_divisions as $division ){
                if($division->id == $selected_division){
                    $shipping_rental_divison = $division;
                    break;
                }
            }
        }
        //retrieve main division form options
        else{
            $shipping_rental_divison = '';
            foreach( $rental_divisions as $division ){
                if($division->main_division == 1){
                    $shipping_rental_divison = $division;
                    break;
                }
            }
        }

    }
    // get divions address object
    // $store_divison = $shipping_rental_divison->address;
    return $shipping_rental_divison->address->zip;
}

// Get the damage waiver information
function rental_get_damage_waiver() {
    $product_settings = rental_get_product_settings();

    return (isset($product_settings['damage_waiver']))? $product_settings['damage_waiver']: null;
}

// Get the date time zone information
function rental_get_timezone() {
    $product_settings = rental_get_product_settings();

    return isset($product_settings['timezone']) && $product_settings['timezone']? new DateTimeZone($product_settings['timezone']): null;
}

// Get the rush fee information
function rental_get_rush_fee() {
    $product_settings = rental_get_product_settings();

    return (isset($product_settings['rush_fee']))? $product_settings['rush_fee']: null;
}

// Get the rush fee information
function rental_get_delivery_tax_setting() {
    $product_settings = rental_get_product_settings();

    $settings = [
        'delivery_tax' => isset($product_settings['delivery_tax']) ? $product_settings['delivery_tax'] : NULL ,
        'exclude_delivery_cost_from_taxable' => isset($product_settings['exclude_delivery_cost_from_taxable']) ? $product_settings['exclude_delivery_cost_from_taxable'] : NULL,
    ];

    return $settings;
}

// Get suitable rush fee
function rental_get_suitable_rush_fee() {

    $start_date = "";
    if (get_option('rental_synchronized_product_type') == "hourly") {
        
        $start_date = (isset($_COOKIE["rental_hourly_start_date"]) && $_COOKIE["rental_hourly_start_date"]) ? $_COOKIE["rental_hourly_start_date"] : "";
    } else {

        $decrypted_rental_start_date = "";
        if ( (isset($_COOKIE['rental_start_date']) && $_COOKIE['rental_start_date']) ) {

            $decrypted_rental_start_date = decrypt_data($_COOKIE['rental_start_date'], get_option('rental_encryption_key'));
        }

        $start_date = $decrypted_rental_start_date;
    }

    if ($start_date && isset($_COOKIE['rental_zip']) && $_COOKIE['rental_zip']) {

        if ($rush_fee = rental_get_rush_fee()) {

            $tz = rental_get_timezone();
            $start = (new DateTime($start_date, $tz))->getTimestamp();
            $diff = $start - time();
            foreach ($rush_fee as $fee) {
                if ($diff <= $fee['by_hours'] * 3600) { // 1 hour = 3600 seconds
                    return $fee;
                }
            }
        }

    }

    return [
        'days' => 0,
        'hours' => 0,
        'type' => 0,
        'amount' => 0,
    ];
}

// Calculate rush fee
function rental_calculate_rush_fee($subtotal) {

    $rush_fee = rental_get_suitable_rush_fee();

    if ($rush_fee['type'] == 2) {
        return ($subtotal * $rush_fee['amount'] / 100);
    }

    return $rush_fee['amount'];
}

// Get the deposit information
function rental_get_deposit() {
    $product_settings = rental_get_product_settings();
    return (isset($product_settings['deposit']))? $product_settings['deposit']: null;
}

// Get the security deposit information
function rental_get_security_deposit() {
    $product_settings = rental_get_product_settings();
    return (isset($product_settings['security_deposit']))? $product_settings['security_deposit']: null;
}

// Get auto applied order fees
function rental_get_auto_applied_fees() {
    $product_settings = rental_get_product_settings();

    return (isset($product_settings['auto_applied_fees']))? $product_settings['auto_applied_fees']: null;
}

function rental_get_coupon_settings() {
    $product_settings = rental_get_product_settings();

    return (isset($product_settings['coupon_settings']))? $product_settings['coupon_settings']: null;
}

// Get applied coupons
function get_applied_coupons() {
    $coupons = [];
    $cart = WC()->cart;
    $coupons_applied = !empty($cart->applied_coupons) ? $cart->applied_coupons : [];
    if (!empty($coupons_applied)) {
        foreach($coupons_applied as $app_coupon) {
            $coupon = new WC_Coupon($app_coupon);
            $coupons[] = [
                'code' => $coupon->get_code(),
                'amount' => $coupon->get_amount(),
                'discount_type' => $coupon->get_discount_type(),
            ];
        }
    }

    return $coupons;
}

function get_coupon_id_by_title($coupon_title) {
    $coupons = get_posts([
        'post_type' => 'shop_coupon',
        'post_status' => 'publish',
        'posts_per_page' => 1, // We only need one result
        'fields' => 'ids', // We only need the post IDs
        'title' => $coupon_title // Filter by coupon title
    ]);

    if ($coupons) {
        return $coupons[0]; 
    } else {
        return false; 
    }
}

// Calculate cart fees
function rental_calculate_order_total() {
    if( !rental_get_product_settings()) {
        return null;
    }

    $data = [
        'labor_cost' => 0,
        'shipping' => 0,
        'shipping_tax_id' => 0,
        'shipping_tax_rate' => 0,
        'shipping_tax' => 0,
        'rush_fee' => 0,
        'rental_tax' => 0,
        'rental_tax_id' => 0,
        'rental_tax_rate' => 0,
        'sale_tax' => 0,
        'sale_tax_id' => 0,
        'sale_tax_rate' => 0,
        'service_tax' => 0,
        'service_tax_id' => 0,
        'service_tax_rate' => 0,
        'damage_waiver' => 0,
        'damage_waiver_tax_id' => 0,
        'damage_waiver_tax_rate' => 0,
        'damage_waiver_tax' => 0,
        'discount_before_tax' => 0,
        'coupon_discount' => 0,
        'coupons' => [],
        'order_fees' => [],
        'security_deposit_fee' => 0,
        'tip' => 0,
    ];

    
    $rental_product_subtotal = get_rental_session_data('rental_product_subtotal', 0);
    // $rental_product_subtotal = get_option('rental_product_subtotal' . get_new_unique_id(), 0);

    $cart = WC()->cart;
    $subtotal = !empty($rental_product_subtotal) ? $rental_product_subtotal : $cart->get_subtotal();

    $total = $subtotal;
    $tax = rental_get_tax();
    $rental_taxable = 0;
    $sale_taxable = 0;
    $service_taxable = 0;
    $damage_waiver = rental_get_damage_waiver();
    if ($damage_waiver && !get_option('rental_hide_and_buy_damage_waiver_by_default')) {
        if (isset($_COOKIE['rental_exempt_waiver']) && !get_option('rental_hide_damage_waiver')) {
            if ($_COOKIE['rental_exempt_waiver']) {
                $damage_waiver = null;
            }
        } elseif ( !get_option('rental_buy_damage_waiver_by_default')) {
            $damage_waiver = null;
        }

        if (get_option('rental_hide_damage_waiver')) {
            $damage_waiver = null;
        }
    }


    $damage_waiver_subtotal = 0;
    foreach ($cart->get_cart() as $item) {
        
        $id = $item['variation_id']?: $item['product_id'];

        $price = 0;
        if ( !(isset($item['set_id']) && $item['set_id'])) {
            $price = $item['data']->get_price() * $item['quantity'];
        }

         // calculating set items with optional items price as taxable
         if ( isset($item['set_id']) && $item['set_id'] ) {
	
            if ($item['rental_add_on_price']) {
                // set item's addon price (taxable value)
                $price = $item['rental_add_on_price'] * $item['quantity'];
            }
        }
       
        $price_for_damage_waiver = $item['data']->get_price() * $item['quantity'];
        
        // calculate job cost of the product/variant/set item
        if ( $job_cost = get_post_meta($id, '_job_cost', true)) {
            $data['labor_cost'] += ($job_cost * $item['quantity']);
        }

        if ($tax && get_post_meta($id, '_tax_status', true) == 'taxable') {

            if ( !is_null($tax['sale_tax_rate']) && get_post_meta($item['product_id'], '_rental_is_sale', true)) {

                $sale_taxable += $price;
            } else {

                $rental_taxable += $price;
            }
        }

        if ($damage_waiver && !get_post_meta($item['product_id'], '_rental_exempt_waiver', true) && !get_post_meta($item['product_id'], '_rental_is_sale', true)) {
            $damage_waiver_subtotal += $price_for_damage_waiver;
        }
    }


    // Add labor cost to total
    $total += $data['labor_cost'];
    $labor_cost_taxable = 0;
    if(isset($tax['job_cost_taxable']) && $tax['job_cost_taxable']){
        $labor_cost_taxable = $data['labor_cost'];
    }
  

    // Add rush fee to total
    $data['rush_fee'] = rental_calculate_rush_fee($subtotal);

    $total += $data['rush_fee'];

    $rush_fee_taxable = 0;
    if(isset($tax['rush_fee_taxable']) && $tax['rush_fee_taxable']){
        $rush_fee_taxable = $data['rush_fee']; 
    }

    $rush_fee_calculated = 0;

    $shipping_fee = (float) $cart->get_shipping_total();
    $data['shipping'] = $shipping_fee;

    $total += $shipping_fee;
    if ($shipping_fee > 0 && $tax && !empty($tax['shipping_tax_id']) ) {
        $data['shipping_tax_id'] = $tax['shipping_tax_id'];
        $data['shipping_tax_rate'] = $tax['shipping_tax_rate'];
    }
    
    // Add damage waiver fee to total
    if ($damage_waiver_subtotal && !empty($damage_waiver['damage_waiver'])) {
        $damage_waiver_fee = $damage_waiver_subtotal * $damage_waiver['damage_waiver'] / 100;
        $data['damage_waiver'] = $damage_waiver_fee;

        $total += $damage_waiver_fee;
        if ( !empty($damage_waiver['tax_id'])) {
            $data['damage_waiver_tax_id'] = $damage_waiver['tax_id'];
            $data['damage_waiver_tax_rate'] = $damage_waiver['tax_rate'];
        }
    }

    // Get applied woocommerce coupons from cart
    $coupons = get_applied_coupons();

    // Add coupon discount fee to total before taxes
    $discount_before_tax = !empty(rental_get_coupon_settings()) ? rental_get_coupon_settings()["discount_before_tax"] : NULL;
    $exclude_delivery_from_coupon = !empty(rental_get_coupon_settings()) ? rental_get_coupon_settings()["exclude_delivery_from_coupon"] : NULL;
    

    $discountable_total = $total;
    $ratio = 0;
    if (!empty($coupons) && !empty($discount_before_tax) && $discount_before_tax == 1) {
        $coupon_discount = 0;
        foreach($coupons as $key=>$coupon) {
            if ($coupon['discount_type'] == 'percent') {

                if ($exclude_delivery_from_coupon == 1) {
                    $discountable_total -= $shipping_fee;

                    if ($data['shipping_tax']) {
                        $discountable_total -= $data['shipping_tax'];
                    }
                }

                $coupon_discount = $discountable_total * $coupon['amount'] / 100;

                // $coupon_discount = $total * $coupon['amount'] / 100;

            } else if ($coupon['discount_type'] == 'fixed_cart') {
                $coupon_discount = $coupon['amount'];
            }
            if ($coupon_discount > $discountable_total) {
                $coupon_discount = $discountable_total;
            }
            $data['discount_before_tax'] = 1;


            $ratio = ($discountable_total > 0) ? 1 - ($coupon_discount / $discountable_total) : 0;

            // effecting the discount on the products that were calculated before this line
            $rental_taxable = $rental_taxable * $ratio;

            $sale_taxable = $sale_taxable * $ratio;
            $service_taxable = $service_taxable * $ratio;

            if ($exclude_delivery_from_coupon != 1) {
                $shipping_fee *= $ratio;
            }

            if ($damage_waiver && $data['damage_waiver_tax_rate']) {
                $damage_waiver_fee *= $ratio;
            }

            if (isset($tax['rush_fee_taxable']) && $tax['rush_fee_taxable']){
                $rush_fee_taxable *= $ratio;
            }

            if(isset($tax['job_cost_taxable']) && $tax['job_cost_taxable']){
                $labor_cost_taxable *= $ratio;
            }

            $data['coupons'][$key] = [
                'discount_type' => $coupon['discount_type'],
                'coupon_discount' => $coupon_discount,
                'amount' => $coupon['amount'],
                'code' => $coupon['code'],
            ];

            $data['coupon_discount'] = $coupon_discount;

            set_rental_session_data('rental_coupon_discount', $coupon_discount);

            break;
        }

        $total -= $coupon_discount;
    }


    $delivery_tax_settings = rental_get_delivery_tax_setting();

    $delivery_taxable = 0;
    // Add tax fees to total
    if ($tax) {

        // add shipping fee to subtotal items price and then calculate Tax
        if ($shipping_fee && !$delivery_tax_settings['delivery_tax'] && !$delivery_tax_settings['exclude_delivery_cost_from_taxable']) {
            
            $delivery_taxable = $shipping_fee;
        }
        
        if (isset($tax['auto_tax']) && $tax['auto_tax'] == 1) {
            // auto tax
            $data['is_auto_tax'] = 1;
            if($tax['auto_tax_rates']) {
                if (!empty($tax['auto_tax_rates']['totalRate'])) {
                    $data['auto_tax_rate'] = $tax['auto_tax_rates']['totalRate'] * 100;

                    $data['auto_tax'] = 0;
                    if (!empty($tax['sale_tax_rate'])) {

                        if(isset($tax['rush_fee_taxable']) && $tax['rush_fee_taxable']){
                            $sale_taxable += $rush_fee_taxable;
                            $rush_fee_calculated = 1;
                        }

                        // apply auto tax to damage waiver
                        if ($damage_waiver && isset($tax['auto_tax']) && $tax['auto_tax'] == 1 && isset($tax['apply_auto_tax_to_dw']) && $tax['apply_auto_tax_to_dw'] == 1) {
                            
                            $sale_taxable += $damage_waiver_fee;
                            
                            $data['damage_waiver_tax_rate'] = $data['auto_tax_rate'];
                            $data['damage_waiver_tax_id'] = 0;
                            $data['damage_waiver_tax'] = 0;

                        } 

                        $data['auto_tax'] = format_value_to_fixed_precision($sale_taxable * $tax['auto_tax_rates']['totalRate'], 2);

                    } 
                    
                    // if ($rental_taxable) {
                    
                        // rental taxable
                        if($rush_fee_calculated == 0 && isset($tax['rush_fee_taxable']) && $tax['rush_fee_taxable']){
                            $rental_taxable += $rush_fee_taxable;
                            $rush_fee_calculated = 1;
                        }

                        // apply auto tax to damage waiver
                        if ($damage_waiver && isset($tax['auto_tax']) && $tax['auto_tax'] == 1 && isset($tax['apply_auto_tax_to_dw']) && $tax['apply_auto_tax_to_dw'] == 1) {
                                          
                            $rental_taxable += $damage_waiver_fee;
                            
                            $data['damage_waiver_tax_rate'] = $data['auto_tax_rate'];
                            $data['damage_waiver_tax_id'] = 0;
                            $data['damage_waiver_tax'] = 0;

                        } 

                        if ($delivery_taxable) {
                            $rental_taxable += $delivery_taxable;
                        }

                        if(isset($tax['job_cost_taxable']) && $tax['job_cost_taxable']){
                            $rental_taxable += $labor_cost_taxable;
                        }

                        $data['auto_tax'] = format_value_to_fixed_precision($rental_taxable * $tax['auto_tax_rates']['totalRate'], 2);

                    // }

                    if (!empty($tax['auto_tax_rates']['rates'])) {
                        $data['rental_auto_tax_rates'] = [];
                        foreach($tax['auto_tax_rates']['rates'] as $rate) {
                            $rate_data = $rate['name'];
                            $rate_data .= ' - ' . $rate['type'];
                            $rate_data .= '(' . format_value_to_fixed_precision(($rate['rate'] * 100), 3) . '%)';
                            $data['rental_auto_tax_rates'][] = [
                                "name" => $rate_data,
                                "value" => $rental_taxable * $rate['rate'],
                            ];
                        }
                    }

                    $total += $data['auto_tax'];
                }

            }

        } else {
            // manual tax

            // service tax
            if (isset($tax['service_tax_rate']) && $tax['service_tax_rate']) {
                $data['service_tax_id'] = $tax['service_tax_id'];

                if (isset($tax['rush_fee_taxable']) && $tax['rush_fee_taxable']){
                    $service_taxable += $rush_fee_taxable;
                    $rush_fee_calculated = 1;
                }

                $data['service_tax_rate'] = $tax['service_tax_rate'];
                $data['service_tax'] = format_value_to_fixed_precision($service_taxable * $tax['service_tax_rate'] / 100, 2);

                $total += $data['service_tax'];
            }

            // sale tax
            if (!empty($tax['sale_tax_rate'])) {
                $data['sale_tax_id'] = $tax['sale_tax_id'];

                if ($rush_fee_calculated == 0 && isset($tax['rush_fee_taxable']) && $tax['rush_fee_taxable']){
                    $sale_taxable += $rush_fee_taxable;

                    $rush_fee_calculated = 1;
                }

                $data['sale_tax_rate'] = $tax['sale_tax_rate'];
                $data['sale_tax'] = format_value_to_fixed_precision($sale_taxable * $tax['sale_tax_rate'] / 100, 2);

                $total += $data['sale_tax'];
            }

            
            // rental tax
            $data['rental_tax_id'] = $tax['rental_tax_id'];
            if ($tax['rental_tax_rate']) {

                if ($rush_fee_calculated == 0 && isset($tax['rush_fee_taxable']) && $tax['rush_fee_taxable']){
                    $rental_taxable += $rush_fee_taxable;

                    $rush_fee_calculated = 1;
                }

                $data['rental_tax_rate'] = $tax['rental_tax_rate'];

                if ($delivery_taxable) {
                    $rental_taxable += $delivery_taxable;
                }

                if(isset($tax['job_cost_taxable']) && $tax['job_cost_taxable']){
                    $rental_taxable += $labor_cost_taxable;
                }

                $data['rental_tax'] = format_value_to_fixed_precision($rental_taxable * $tax['rental_tax_rate'] / 100, 2);
               
                $total += $data['rental_tax'];
            }

        }
    }

    if ($shipping_fee && $delivery_tax_settings['delivery_tax']) {
        if ($data['shipping_tax_rate']) {

            $data['shipping_tax'] = $shipping_fee * $data['shipping_tax_rate'] / 100;

            $total += $data['shipping_tax'];
        }
    }
    
    if ($damage_waiver && $data['damage_waiver_tax_rate']) {
        if ( !(isset($tax['auto_tax']) && $tax['auto_tax'] == 1 && isset($tax['apply_auto_tax_to_dw']) && $tax['apply_auto_tax_to_dw'] == 1)) {
            $data['damage_waiver_tax'] = format_value_to_fixed_precision($damage_waiver_fee * $data['damage_waiver_tax_rate'] / 100, 2);
            
            $total += $data['damage_waiver_tax'];
        }
    }
    

    $coupon_after_tax_is_caculated = false;
    $discountable_total = $total;
    $coupon_discount = 0;

    $auto_applied_fees = rental_get_auto_applied_fees();
    if ( $auto_applied_fees && !get_option('rental_exclude_order_fees', 0)) {

        $condition = RELATION_LOGISTICS_COMPANY_PICK_UP_COMPANY_RETURN;
        if (!get_option('rental_do_not_use_rentopian_shipping')) {

            if (get_option('rental_pickup_delivery') == 'company_delivery_return') {
                $condition = RELATION_LOGISTICS_COMPANY_PICK_UP_COMPANY_RETURN;
            } else if (get_option('rental_pickup_delivery') == 'client_pickup_return') {
                $condition = RELATION_LOGISTICS_CLIENT_PICK_UP_CLIENT_RETURN;
            } else if (get_option('rental_pickup_delivery') == 'company_client_delivery_return') {
                
                if (isset($_COOKIE['rental_shipping_method'])) {
                    if ($_COOKIE['rental_shipping_method'] == 1) {
                        $condition = RELATION_LOGISTICS_COMPANY_PICK_UP_COMPANY_RETURN;
                    } else {
                        $condition = RELATION_LOGISTICS_CLIENT_PICK_UP_CLIENT_RETURN;
                    }
                }
            }
        }


        // Temp calculating for coupon only (to have $coupon_discount)
        foreach ($auto_applied_fees as $key => $fee) {
            if ( !empty($fee['conditions']) && !in_array($condition, $fee['conditions'])) {
                continue;
            }

            if ($fee['is_percent']) {
                continue;
            }

            $fee['auto_fee_id'] = $fee['id'];
            $fee['percent'] = 0;

            // only used in fixed auto applied fee amounts
            $fee_amount_taxable = !$fee['is_percent'] ? $fee['amount'] : 0;

            if (!$fee['is_percent']) {
                
                if ($fee['taxable']) {
                    
                    if (isset($tax['auto_tax']) && $tax['auto_tax'] == 1 && isset($data['auto_tax'])) {

                        $temp_auto_tax = $data['auto_tax'];

                        $fee_amount_taxable = $fee['amount'];
                        if (!empty($coupons) && !empty($discount_before_tax) && $discount_before_tax == 1 && !empty($ratio)) {
                            $fee_amount_taxable *= $ratio;
                        }

                        $rental_taxable += $fee_amount_taxable;

                        $discountable_total -= $temp_auto_tax;
                        $temp_auto_tax = format_value_to_fixed_precision($rental_taxable * $tax['auto_tax_rates']['totalRate'], 2);
                        $discountable_total += $temp_auto_tax;

                        $rental_taxable -= $fee_amount_taxable;
                    
                    } else {
                        // manual tax
                        // must prioritize the service and then sale and then rental tax in tax calculations

                        $fee_tax_calculated = false;
                        if (!empty($tax['service_tax_rate'])) {
                            $fee_tax_calculated = true;

                            $temp_service_tax = $data['service_tax'];

                            $fee_amount_taxable = $fee['amount'];
                            if (!empty($coupons) && !empty($discount_before_tax) && $discount_before_tax == 1 && !empty($ratio)) {
                                $fee_amount_taxable *= $ratio;
                            }

                            $service_taxable += $fee_amount_taxable;

                            $discountable_total -= $temp_service_tax;
                            $temp_service_tax = format_value_to_fixed_precision($service_taxable * $tax['service_tax_rate'] / 100, 2);
                            $discountable_total += $temp_service_tax;

                            $service_taxable -= $fee_amount_taxable;
                        }

                        if (!empty($tax['sale_tax_rate']) && !$fee_tax_calculated) {
                            $fee_tax_calculated = true;

                            $temp_sale_tax = $data['sale_tax'];

                            $fee_amount_taxable = $fee['amount'];
                            if (!empty($coupons) && !empty($discount_before_tax) && $discount_before_tax == 1 && !empty($ratio)) {
                                $fee_amount_taxable *= $ratio;
                            }

                            $sale_taxable += $fee_amount_taxable;

                            $discountable_total -= $temp_sale_tax;
                            $temp_sale_tax = format_value_to_fixed_precision($sale_taxable * $tax['sale_tax_rate'] / 100, 2);
                            $discountable_total += $temp_sale_tax;

                            $sale_taxable -= $fee_amount_taxable;
                        }

                        if (!empty($tax['rental_tax_rate']) && !$fee_tax_calculated) {

                            $temp_rental_tax = $data['rental_tax'];

                            $fee_amount_taxable = $fee['amount'];
                            if (!empty($coupons) && !empty($discount_before_tax) && $discount_before_tax == 1 && !empty($ratio)) {
                                $fee_amount_taxable *= $ratio;
                            }

                            $rental_taxable += $fee_amount_taxable;

                            $discountable_total -= $temp_rental_tax;
                            $temp_rental_tax = format_value_to_fixed_precision($rental_taxable * $tax['rental_tax_rate'] / 100, 2);
                            $discountable_total += $temp_rental_tax;


                            $rental_taxable -= $fee_amount_taxable;
                        }

                    }

                }


                if (!$coupon_after_tax_is_caculated) {
                    if (!empty($coupons) && $discount_before_tax != 1) {
                      
                        foreach($coupons as $key=>$coupon) {
                            if ($coupon['discount_type'] == 'percent') {
            
                                if ($exclude_delivery_from_coupon == 1) {
                                    $discountable_total -= $shipping_fee;
            
                                    if ($data['shipping_tax']) {
                                        $discountable_total -= $data['shipping_tax'];
                                    }
                                }
            
                                $coupon_discount = $discountable_total * $coupon['amount'] / 100;
            
                            } else if ($coupon['discount_type'] == 'fixed_cart') {
                                $coupon_discount = $coupon['amount'];
                            }
                            if ($coupon_discount > $total) {
                                $coupon_discount = $total;
                            }
            
                            set_rental_session_data('rental_coupon_discount', $coupon_discount);
            
                            $data['coupon_discount'] = $coupon_discount;
                            break;
                        }
                    }
                }
                 

            }
        }


        $total_fees = 0;
        foreach ($auto_applied_fees as $key => $fee) {
            if ( !empty($fee['conditions']) && !in_array($condition, $fee['conditions'])) {
                continue;
            }


            $fee['auto_fee_id'] = $fee['id'];
            $fee['percent'] = 0;

            // only used in fixed auto applied fee amounts
            $fee_amount_taxable = !$fee['is_percent'] ? $fee['amount'] : 0;

            if ($fee['is_percent']) {

                $included_total = 0;
                if ($fee['include_products']) {
                    $included_total += $subtotal;
                }
                if ($fee['include_job_cost']) {
                    $included_total += $data['labor_cost'];
                }

                if (isset($tax['auto_tax']) && $tax['auto_tax'] == 1 && isset($data['auto_tax'])) {

                    if ($fee['include_rental_tax'] || $fee['include_sale_tax'] || $fee['taxable']) {
                        $included_total += $data['auto_tax'];
                    }

                } else {
                    
                    if ($fee['include_rental_tax']) {
                        $included_total += $data['rental_tax'];
                    }
                    if ($fee['include_sale_tax']) {
                        $included_total += $data['sale_tax'];
                    }
                    if ($fee['include_service_tax'] && isset($data['service_tax'])) {
                        $included_total += $data['service_tax'];
                    }
                }
               
                if ($fee['include_delivery']) {
                    $included_total += $data['shipping'];
                }
                if ($fee['include_delivery_tax']) {
                    $included_total += $data['shipping_tax'];
                }
               

                if (isset($fee['include_arrival_cost']) && !empty($fee['include_arrival_cost'])) {
                    // TODO : after exact arrival cost integrated
                    // $included_total += $data['shipping_tax'];
                }

                if (isset($fee['include_pickup_cost']) && !empty($fee['include_pickup_cost'])) {
                    // TODO : after exact pickup cost integrated
                    // $included_total += $data['shipping_tax'];
                }

                if ($fee['include_damage_waiver']) {
                    $included_total += $data['damage_waiver'];
                }
                if ($fee['include_damage_waiver_tax']) {
                    $included_total += $data['damage_waiver_tax'];
                }
                if ($fee['include_rush_fee']) {
                    $included_total += $data['rush_fee'];
                }
                if ($fee['include_coupon']) {
                    $included_total -= $data['coupon_discount'];
                }
                if ($fee['include_fees']) {
                    $included_total += $total_fees;
                }

                $fee['percent'] = $fee['amount'];

                $fee['amount'] = format_value_to_fixed_precision($included_total * $fee['percent'] / 100, 2);

            } else {
                
                if ($fee['taxable']) {
                    
                    if (isset($tax['auto_tax']) && $tax['auto_tax'] == 1 && isset($data['auto_tax'])) {

                        $fee_amount_taxable = $fee['amount'];
                        if (!empty($coupons) && !empty($discount_before_tax) && $discount_before_tax == 1 && !empty($ratio)) {
                            $fee_amount_taxable *= $ratio;
                        }

                        $rental_taxable += $fee_amount_taxable;

                        $total -= $data['auto_tax'];
                        $data['auto_tax'] = format_value_to_fixed_precision($rental_taxable * $tax['auto_tax_rates']['totalRate'], 2);
                        $total += $data['auto_tax'];
                    
                    } else {
                        // manual tax
                        // must prioritize the service and then sale and then rental tax in tax calculations

                        $fee_tax_calculated = false;
                        if (!empty($tax['service_tax_rate'])) {
                            $fee_tax_calculated = true;

                            $fee_amount_taxable = $fee['amount'];
                            if (!empty($coupons) && !empty($discount_before_tax) && $discount_before_tax == 1 && !empty($ratio)) {
                                $fee_amount_taxable *= $ratio;
                            }

                            $service_taxable += $fee_amount_taxable;
    
                            $total -= $data['service_tax'];
                            $data['service_tax'] = format_value_to_fixed_precision($service_taxable * $tax['service_tax_rate'] / 100, 2);
                            $total += $data['service_tax'];

                            // when total is update, discountable total must be updated
                            $discountable_total = $total;

                        }

                        if (!empty($tax['sale_tax_rate']) && !$fee_tax_calculated) {
                            $fee_tax_calculated = true;

                            $fee_amount_taxable = $fee['amount'];
                            if (!empty($coupons) && !empty($discount_before_tax) && $discount_before_tax == 1 && !empty($ratio)) {
                                $fee_amount_taxable *= $ratio;
                            }

                            $sale_taxable += $fee_amount_taxable;

                            $total -= $data['sale_tax'];
                            $data['sale_tax'] = format_value_to_fixed_precision($sale_taxable * $tax['sale_tax_rate'] / 100, 2);
                            $total += $data['sale_tax'];

                            // when total is update, discountable total must be updated
                            $discountable_total = $total;

                        }

                        if (!empty($tax['rental_tax_rate']) && !$fee_tax_calculated) {

                            $fee_amount_taxable = $fee['amount'];
                            if (!empty($coupons) && !empty($discount_before_tax) && $discount_before_tax == 1 && !empty($ratio)) {
                                $fee_amount_taxable *= $ratio;
                            }

                            $rental_taxable += $fee_amount_taxable;

                            $total -= $data['rental_tax'];
                            $data['rental_tax'] = format_value_to_fixed_precision($rental_taxable * $tax['rental_tax_rate'] / 100, 2);
                            $total += $data['rental_tax'];

                            // when total is update, discountable total must be updated
                            $discountable_total = $total;
                        }

                    }

                }


                
                if (!$coupon_after_tax_is_caculated) {

                    if (!empty($coupons) && $discount_before_tax != 1) {

                        $coupon_discount = 0;
                        foreach($coupons as $key=>$coupon) {
                            if ($coupon['discount_type'] == 'percent') {

                                if (!$coupon_discount) {
                                    if ($exclude_delivery_from_coupon == 1) {
                                        $discountable_total -= $shipping_fee;
                
                                        if ($data['shipping_tax']) {
                                            $discountable_total -= $data['shipping_tax'];
                                        }
                                    }
                
                                    $coupon_discount = $discountable_total * $coupon['amount'] / 100;
                                }
            
                            } else if ($coupon['discount_type'] == 'fixed_cart') {
                                
                                if (!$coupon_discount) {
                                    $coupon_discount = $coupon['amount'];
                                }
                            }

                            if ($coupon_discount > $total) {
                                $coupon_discount = $total;
                            }
            
                            $total -= $coupon_discount;
            
                            $data['coupons'][$key] = [
                                'discount_type' => $coupon['discount_type'],
                                'coupon_discount' => $coupon_discount,
                                'amount' => $coupon['amount'],
                                'code' => $coupon['code'],
                            ];
            
                            set_rental_session_data('rental_coupon_discount', $coupon_discount);
            
                            $coupon_after_tax_is_caculated = true;

                            $data['coupon_discount'] = $coupon_discount;
                            break;
                        }
                    }
                }
                 

            }

            $total_fees += $fee['amount'];
            $data['order_fees'][] = $fee;
        }

        $total += $total_fees;
    } 


    if (!$coupon_after_tax_is_caculated) {
        // Add coupon discount fee to total after taxes
        if (!empty($coupons) && $discount_before_tax != 1) {
            $coupon_discount = 0;
            foreach($coupons as $key=>$coupon) {

                if ($coupon['discount_type'] == 'percent') {

                    if ($exclude_delivery_from_coupon == 1) {
                        $discountable_total -= $shipping_fee;

                        if ($data['shipping_tax']) {
                            $discountable_total -= $data['shipping_tax'];
                        }
                    }

                    $coupon_discount = $discountable_total * $coupon['amount'] / 100;

                } else if ($coupon['discount_type'] == 'fixed_cart') {
                    $coupon_discount = $coupon['amount'];
                }

                if ($coupon_discount > $total) {
                    $coupon_discount = $total;
                }

                $total -= $coupon_discount;

                $data['coupons'][$key] = [
                    'discount_type' => $coupon['discount_type'],
                    'coupon_discount' => $coupon_discount,
                    'amount' => $coupon['amount'],
                    'code' => $coupon['code'],
                ];

                $data['coupon_discount'] = $coupon_discount;

                set_rental_session_data('rental_coupon_discount', $coupon_discount);

                break;
            }
        }
    }
      
    

    // rental taxable amount of an order
    if ($rental_taxable) {
        set_rental_session_data('rental_taxable_amount', $rental_taxable);
    }
    
    // the total amount without security_deposit_fee and payment_tip_amount
    set_rental_session_data('total_excluded_extra_fees', $total);

    // if security deposit is enabled
    if (get_option('rental_allow_to_pay_security_deposit') && !empty($security_deposit = rental_get_security_deposit())) {
        $data['security_deposit_fee'] = rental_get_security_deposit_cart_calculations($cart, $total, $security_deposit);
        // Add security deposit fee to total
        $total += $data['security_deposit_fee'];
    }

    if (
        get_option("rental_direct_only_bookings", 0)
        && get_option("rental_payment_tips_enabled", 0)
    ) {

        $tip_amount = 0;
        if (!isset($_COOKIE['TIP_ID_SELECTED_BY_CUSTOMER' . get_new_unique_id()])) {
            // use default tip amount when no tip selected
            
            $tip_amount = calculate_tip_amount(0, true);

        } else {

            $tip_amount = calculate_tip_amount($_COOKIE['TIP_ID_SELECTED_BY_CUSTOMER' . get_new_unique_id()]);
        }
        
        $data['tip'] = $tip_amount;

        // Add tip amount to total
        $total += $data['tip'];
    }

    $data['total'] = $total;
    return $data;
}

// get calculated security deposit fee based on each cart item
function rental_get_security_deposit_cart_calculations($cart, $total, $security_deposit) {
    $data_security_deposit_fee = 0;
    
    // calculate based on each item's replacement price and quantity
    if ($security_deposit['on_replacement'] && $security_deposit['is_percent']) {
        foreach ($cart->get_cart() as $item) {
            $id = $item['variation_id']?: $item['product_id'];

            if (!get_post_meta($item['product_id'], '_rental_is_set', true)) {
                // replacement price is always calculated with percent rate
                $replacement_price = empty(get_post_meta($id, '_rental_replacement_price', true )) ? 0 : get_post_meta($id, '_rental_replacement_price', true );
                $replacement_price_amount = ($security_deposit['rate'] * $replacement_price)/100;
                $data_security_deposit_fee += ($replacement_price_amount * $item['quantity']);
            }
        }
    } 
    // calculate based on total and security deposit rate
    else {
        
        // calculate with percent rate
        if ($security_deposit['is_percent']) {
            $data_security_deposit_fee = ($security_deposit['rate'] * $total)/100;
        }
        // calculate with fixed amount
        else {
            $data_security_deposit_fee = $security_deposit['rate'];
        }
                    
    }

    return $data_security_deposit_fee;
}

function get_days_from_rental_dates($rental_start_date, $rental_end_date) {
        
    $start_date = $rental_start_date ? new DateTime($rental_start_date) : "";
    $end_date = $rental_end_date ? new DateTime($rental_end_date) : "";
    
    $days = 1;
    if ($start_date && $end_date) {
        $end_date->setTime(0, 0);
        $start_date->setTime(0, 0);
        $days = $end_date->diff($start_date);
        $days = $days->days + 1;
    }

    return $days;
}

// Calculate days
function rental_get_days() {
    global $wpdb, $rental_tables;
    $rental_day_tiers = $wpdb->prefix . $rental_tables["day_tiers"];

    if (get_option('rental_synchronized_product_type') == "hourly") {

        $end_date = new DateTime($_COOKIE["rental_hourly_end_date"]);
        $start_date = new DateTime($_COOKIE["rental_hourly_start_date"]);

    } else {

        if (get_option('rental_hide_end_date') || !isset($_COOKIE['rental_end_date']) || !$_COOKIE['rental_end_date']) {
            $min_range = (int) get_option('rental_min_dates_range');
            return $min_range > 1? $min_range: 1;
        }

        $decrypted_rental_start_date = "";
        if ( isset($_COOKIE['rental_start_date']) ) {
            $decrypted_rental_start_date = decrypt_data($_COOKIE['rental_start_date'], get_option('rental_encryption_key'));
        }

        $decrypted_rental_end_date = "";
        if ( isset($_COOKIE['rental_end_date']) ) {
            $decrypted_rental_end_date = decrypt_data($_COOKIE['rental_end_date'], get_option('rental_encryption_key'));
        }
        
        $end_date = $decrypted_rental_end_date ? new DateTime($decrypted_rental_end_date) : "";
        $start_date = $decrypted_rental_start_date ? new DateTime($decrypted_rental_start_date) : "";
    }

    $days = 1;
    if ($start_date && $end_date) {
        $days = $end_date->diff($start_date);
        $hours = $days->h + (24 * $days->days);
        $days = $wpdb->get_var("SELECT `day` FROM $rental_day_tiers WHERE `min` < $hours AND `max` >= $hours");
        if ( !$days) {
            $end_date->setTime(0, 0);
            $start_date->setTime(0, 0);
            $days = $end_date->diff($start_date);
            $days = $days->days + 1;
            // if ($days == 0) {
            //     $days = 1;
            // }
        }
    }

    return $days;
}

// Get order custom fields
function rental_get_custom_fields() {
    $api_key = get_option('rental_api_key');

    $rental_custom_fields = json_decode(rental_curl('custom-fields', $api_key, false), 1);
    update_option('rental_custom_fields', $rental_custom_fields);

    return $rental_custom_fields;
}

// stripping zip code(post code) extensions if exists 
function strip_zip_code_extensions($zip) {
    if ( $dash_position = strpos($zip, '-') ){
        $zip = trim(substr_replace($zip, "", $dash_position));
    }
    return $zip;
}

// override/format the value to a fixed [$decimal_number] precision
function format_value_to_fixed_precision($value, $decimal_number) {
    return number_format((float) $value, $decimal_number, '.', '');
}

function rental_sanitize($data) {
    if ($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
    }
    return $data;
}
function rental_validate($data, $type = "", $check_empty = true) {
    if ($check_empty) {
        if (empty($data)) {
            return "empty_err";
        }
    }

    if ($type && $data) {
        switch($type) {
            case "numeric":
                if (!is_numeric($data)) {
                    return "numeric_err";
                }
                return true;
            case "not_numeric":
                if (is_numeric($data)) {
                    return "not_numeric_err";
                }
                return true;
            case "email":
                if (!filter_var($data, FILTER_VALIDATE_EMAIL)) {
                    return "email_err";
                }
                return true;
        }
    }
    return true;
}

function wp_ajax_rental_send_wishlist_form() {
    if (
        isset($_POST["name"])
        && isset($_POST["email"])
        && isset($_POST["date"])
        && isset($_POST["location"])
        && isset($_POST["phone"])
        && isset($_POST["guest_count"])
        && isset($_POST["note"])
    ) {

        $name = rental_sanitize($_POST["name"]);
        $email = rental_sanitize($_POST["email"]);
        $date = rental_sanitize($_POST["date"]);

        $location = rental_sanitize($_POST["location"]);
        $address_2 = rental_sanitize($_POST["address_2"]);
        $state = rental_sanitize($_POST["state"]);
        $city = rental_sanitize($_POST["city"]);
        $zip = rental_sanitize($_POST["zip"]);
        $country = rental_sanitize($_POST["country"]);
        
        $phone = rental_sanitize($_POST["phone"]);
        $guest_count = rental_sanitize($_POST["guest_count"]);
        $note = rental_sanitize($_POST["note"]);
        $err = rental_validate($name, "not_numeric");
        if (!$err) {
            wp_send_json(["err" => $err, "field" => "Name"], 401);
            wp_die();
        }
        $err = rental_validate($email, "email");
        if (!$err) {
            wp_send_json(["err" => $err, "field" => "Email"], 401);
            wp_die();
        }
        $err = rental_validate($date);
        if (!$err) {
            wp_send_json(["err" => $err, "field" => "Date"], 401);
            wp_die();
        }
        $err = rental_validate($location);
        if (!$err) {
            wp_send_json(["err" => $err, "field" => "Location"], 401);
            wp_die();
        }
        if ($guest_count) {
            $err = rental_validate($guest_count, "numeric");
            if (!$err) {
                wp_send_json(["err" => $err, "field" => "Guest Count"], 401);
                wp_die();
            }
        }

        $err = rental_validate($state, "not_numeric");
        if (!$err) {
            wp_send_json(["err" => $err, "field" => "State"], 401);
            wp_die();
        }

        $err = rental_validate($city, "not_numeric");
        if (!$err) {
            wp_send_json(["err" => $err, "field" => "City"], 401);
            wp_die();
        }

        $err = rental_validate($country, "not_numeric");
        if (!$err) {
            wp_send_json(["err" => $err, "field" => "Country"], 401);
            wp_die();
        }
        
        
        $data = [
            "name" => $name,
            "email" => $email,
            "date" => $date,
            "location" => $location,
            "address_2" => $address_2,
            "state" => $state,
            "city" => $city,
            "zip" => $zip,
            "country" => $country,
            "lat" => isset($_COOKIE['rental_client_wish_address_lat']) && $_COOKIE['rental_client_wish_address_lat'] ? $_COOKIE['rental_client_wish_address_lat'] : '',
            "lng" => isset($_COOKIE['rental_client_wish_address_lng']) && $_COOKIE['rental_client_wish_address_lng'] ? $_COOKIE['rental_client_wish_address_lng'] : '',
            "phone" => $phone,
            "guest_count" => $guest_count,
            "notes" => $note,
        ];

        
        global $wpdb, $rental_tables;
        $rental_lead_relations = $wpdb->prefix . $rental_tables["lead_relations"];

        $log = [
            "http_code" => 200,
            "message" => "",
            "rental_id" => 0,
            "register_time" => time(),
        ];

        $response = [];
        $http_code = 200;
        try {

            $rental_lead = rental_curl("leads/add", get_option("rental_api_key"), true, $data);
            
            if (isset($rental_lead->id)) {
                $response = ["data" => $rental_lead->id];
                $log["rental_id"] = $rental_lead->id;
                $log["data"] = serialize($rental_lead);
                
            }

        } catch (RentalException $e) {

            $http_code = $e->getStatusCode();
            $response = [["err" => "serverside", "field" => "serverside"]];
            $log["http_code"] = $http_code;
            $log["message"] = $e->getMessage();
        }

        $log["version"] = RENTOPIAN_SYNC_VERSION;
        $log["data"] = serialize($data);
        $wpdb->insert($rental_lead_relations, $log);
        if ($wpdb->last_error !== "") {
            throw new RentalException("SQL_ERROR: $wpdb->last_error (SQL: $wpdb->last_query)");
        }

        if ($http_code != 200) {
            $error_msg = json_decode($e->getMessage(), true);
            wp_send_json(["err" => false, "field" => " ", "msg" => $error_msg], 401);
            wp_die();
        }
        wp_send_json($response, $http_code);
        wp_die();
    }
}

function rental_create_order($order_id) {
    global $wpdb, $rental_tables;
    $rental_product_relations = $wpdb->prefix . $rental_tables["product_relations"];
    $rental_order_relations = $wpdb->prefix . $rental_tables["order_relations"];

    if ( get_option('rental_synchronized_product_type') == "hourly") {
        // It's on hourly mode, continue!
    } else {
        if ( !isset($_COOKIE['rental_zip']) || !isset($_COOKIE['rental_start_date'])) {
            return;
        }
    }

    if ($wpdb->get_var("SELECT `rental_id` FROM $rental_order_relations WHERE `id` = $order_id")) {
        return;
    }

    // get order by id
    $wc_order = new WC_Order($order_id);

    // get selected products and their quantity
    $cart = WC()->cart;
    $cart_contents = $cart->cart_contents;
    $inventories = [];
    $time_date_compare_start = [];
    $time_date_compare_end = [];
    foreach ($cart_contents as $cart_item) {

        $quantity = $cart_item["quantity"];
        $product_variant_id = $cart_item['variation_id'] ? $cart_item['variation_id'] : $cart_item['product_id'];

        if (get_post_meta($cart_item["product_id"], "_rental_is_set", true)
            || !($product_id = $wpdb->get_var("SELECT `rental_id` FROM ". $rental_product_relations ." WHERE `id` = " . $cart_item["product_id"]))
            || !($inventory_id = get_post_meta($product_variant_id, "_rental_inventory_id", true))) {
            continue;
        }

        
        $rental_set_id = $set_quantity = $parent_id = $parent_inventory_id = $wp_set_id = 0;
        $sel_variant_id = $set_subtotal = 0; // used for sets having items with optional items and sets with items having addons
        $item_has_price_multiplier = $set_has_price_multiplier = 0;
        $item_subtotal = $cart_item["line_subtotal"]; // subtotal

        $item_has_price_multiplier = get_post_meta($product_variant_id, '_price_multiplier_id', true);

        if (isset($cart_item["rental_add_on_of"])) {

            if ( !isset($cart_contents[$cart_item["rental_add_on_of"]])) {
                continue;
            }

            if (isset($cart_item["rental_set_id"]) && $cart_item["rental_set_id"]) {

                $rental_set_id = $cart_item["rental_set_id"];
                $wp_set_id = $cart_item["set_id"];
                $set_quantity = $cart_contents[$cart_item["rental_add_on_of"]]["quantity"];
                
                $set_has_price_multiplier = get_post_meta($product_variant_id, '_price_multiplier_id', true);

                // sel_variant_id parameter is only for sets items having optional items
                if ($set_ids_with_optional_items = get_set_ids_with_optional_items()) {

                    foreach($set_ids_with_optional_items as $set_with_optional_items_id => $selected_product_key_variant_or_product_value_array) {
                        
                        if ($wp_set_id == $set_with_optional_items_id) {
                            $sel_variant_id = isset($cart_item["rental_variant_id"]) && $cart_item["rental_variant_id"] ? $cart_item["rental_variant_id"] : (isset($cart_item["rental_product_id"]) && $cart_item["rental_product_id"] ? $cart_item["rental_product_id"] : 0);
                            
                            break;
                        }
                    }
                }

                $set_subtotal = $cart_contents[$cart_item["rental_add_on_of"]]["line_subtotal"]; // set subtotal

                if ((isset($cart_item["parent_set_item_product_id"]) 
                    && $cart_item["parent_set_item_product_id"])
                    || (isset($cart_item["parent_set_item_variant_id"]) 
                    && $cart_item["parent_set_item_variant_id"])
                ) {

                    $parent_id = $wpdb->get_var("SELECT `rental_id` FROM $rental_product_relations WHERE `id` = " . $cart_item["parent_set_item_product_id"]);
                    $parent_inventory_id = get_post_meta($cart_item["parent_set_item_variant_id"] ? $cart_item["parent_set_item_variant_id"] : $cart_item["parent_set_item_product_id"], "_rental_inventory_id", true);
                }
             

            } else {

                $parent_id = $wpdb->get_var("SELECT `rental_id` FROM $rental_product_relations WHERE `id` = " . $cart_contents[$cart_item["rental_add_on_of"]]["product_id"]);
                $parent_inventory_id = get_post_meta($cart_contents[$cart_item["rental_add_on_of"]]["variation_id"]?: $cart_contents[$cart_item["rental_add_on_of"]]["product_id"], "_rental_inventory_id", true);
            }
        }

        // override cart's line subtotal if it exceeds precision 2
        $item_subtotal = format_value_to_fixed_precision($item_subtotal, 2);
        $item_price = 0;
        
        $rental_product_options_valuables = get_rental_session_data('rental_product_options_valuables', []);

        $product_options = [];
        if ($wp_set_id) {
            $product_options = isset($rental_product_options_valuables[$wp_set_id]) && $rental_product_options_valuables[$wp_set_id] ? $rental_product_options_valuables[$wp_set_id] : []; 
        }

        if ( get_option('rental_synchronized_product_type') == "hourly" ) {

            $item_price = (float)$item_subtotal/$quantity;

            $product_id = $cart_item['variation_id'] ? $cart_item['variation_id'] : $cart_item['product_id'];
            $session_name_interval = $product_id."_rental_by_interval";
            $session_name_slot = $product_id."_rental_by_slot";

            $rental_by_interval_opt = get_option($session_name_interval);
            $rental_by_slot_opt = get_option($session_name_slot);

            if ($rental_by_interval_opt !== false && $rental_by_interval_opt) {
                // rental_by_interval

                // start date time
                $start_time = $rental_by_interval_opt["selected_times_prices"][0]["time"];
                
                $start_time_stripped_AM = explode("AM", $start_time);
                $start_time_stripped_PM = explode("PM", $start_time);
                if (count($start_time_stripped_AM) == 2) {
                    $start_time_stripped[0] = $start_time_stripped_AM[0]; // value
                    $start_time_stripped[1] = "AM";
                } else if (count($start_time_stripped_PM) == 2) {
                    $start_time_stripped[0] = $start_time_stripped_PM[0]; // value
                    $start_time_stripped[1] = "PM";
                }

                $start_time_type = $start_time_stripped[1]; // AM/PM
                $start_time_stripped2 = explode( ":" ,$start_time_stripped[0]);
                if ($start_time_type == "PM") {
                    $hour_minute_to_seconds = (( ($start_time_stripped2[0] != 12) ? $start_time_stripped2[0] + 12 : $start_time_stripped2[0]) * 60 * 60) + ($start_time_stripped2[1] * 60);
                } else {
                    $hour_minute_to_seconds = (($start_time_stripped2[0]) * 60 * 60) + ($start_time_stripped2[1] * 60);
                }
                $start_time_seconds = $hour_minute_to_seconds;

                // end date time
                $end_time = $rental_by_interval_opt["selected_times_prices"][count($rental_by_interval_opt["selected_times_prices"]) - 1]["time"];
                
                $end_time_stripped_AM = explode("AM", $end_time);
                $end_time_stripped_PM = explode("PM", $end_time);
                if (count($end_time_stripped_AM) == 2) {
                    $end_time_stripped[0] = $end_time_stripped_AM[0]; // value
                    $end_time_stripped[1] = "AM";
                } else if (count($end_time_stripped_PM) == 2) {
                    $end_time_stripped[0] = $end_time_stripped_PM[0]; // value
                    $end_time_stripped[1] = "PM";
                }


                $end_time_type = $end_time_stripped[1]; // AM/PM
                $end_time_stripped2 = explode( ":" ,$end_time_stripped[0]);
                if ($end_time_type == "PM") {
                    $hour_minute_to_seconds = (( ($end_time_stripped2[0] != 12) ? $end_time_stripped2[0] + 12 : $end_time_stripped2[0] ) * 60 * 60) + ($end_time_stripped2[1] * 60);
                } else {
                    $hour_minute_to_seconds = (($end_time_stripped2[0]) * 60 * 60) + ($end_time_stripped2[1] * 60);
                }
                $end_time_seconds = $hour_minute_to_seconds;

                $date = $rental_by_interval_opt["start_date"];

                $start_date_time_seconds = strtotime($date) + $start_time_seconds;
                $end_date_time_seconds = strtotime($date) + $end_time_seconds;
                $start_date_time = date('Y/m/d h:ia', $start_date_time_seconds);
                $end_date_time = date('Y/m/d h:ia', $end_date_time_seconds);

                $time_date_compare_start[] = $start_date_time_seconds;
                $time_date_compare_end[] = $end_date_time_seconds;

                $inventories[] = [
                    "product_id" => $product_id,
                    "inventory_id" => $inventory_id,
                    "quantity" => $cart_item["quantity"],
                    "hourly_price" => $item_price,
                    "subtotal" => $item_subtotal,
                    "set_id" => $rental_set_id,
                    "set_quantity" => $set_quantity,
                    "parent_id" => $parent_id,
                    "parent_inventory_id" => $parent_inventory_id,
                    "rental_by_day" => 0,
                    "rental_by_interval" => 1,
                    "rental_by_slot" => 0,
                    "interval_steps" => $rental_by_interval_opt["interval_steps"],
                    "rental_interval" => $rental_by_interval_opt["rental_interval"],
                    "time_slot_id" => 0,
                    "start_date" => $start_date_time,
                    "end_date" => $end_date_time,
                    "product_options" => $rental_product_options_valuables ? $rental_product_options_valuables[$product_variant_id] : []
                ];

            } else if ($rental_by_slot_opt !== false && $rental_by_slot_opt) {
                // rental_by_slot

                $item_price = (float)$item_subtotal/$quantity;

                // start date time
                $start_time = $rental_by_slot_opt["selected_times_prices"][0]["start_time"];
                $start_time_stripped = explode(" ", $start_time);
                $start_time_type = $start_time_stripped[1]; // AM/PM
                $start_time_stripped2 = explode( ":" ,$start_time_stripped[0]);
                if ($start_time_type == "PM") {
                    $hour_minute_to_seconds = (( ($start_time_stripped2[0] != 12) ? $start_time_stripped2[0] + 12 : $start_time_stripped2[0]) * 60 * 60) + ($start_time_stripped2[1] * 60);
                } else {
                    $hour_minute_to_seconds = (($start_time_stripped2[0]) * 60 * 60) + ($start_time_stripped2[1] * 60);
                }
                $start_time_seconds = $hour_minute_to_seconds;

                // end date time
                $end_time = $rental_by_slot_opt["selected_times_prices"][0]["end_time"];
                $end_time_stripped = explode(" ", $end_time);
                $end_time_type = $end_time_stripped[1]; // AM/PM
                $end_time_stripped2 = explode( ":" ,$end_time_stripped[0]);
                if ($end_time_type == "PM") {
                    $hour_minute_to_seconds = (( ($end_time_stripped2[0] != 12) ? $end_time_stripped2[0] + 12 : $end_time_stripped2[0]) * 60 * 60) + ($end_time_stripped2[1] * 60);
                } else {
                    $hour_minute_to_seconds = (($end_time_stripped2[0]) * 60 * 60) + ($end_time_stripped2[1] * 60);
                }
                $end_time_seconds = $hour_minute_to_seconds;

                $date = $rental_by_slot_opt["start_date"];
                $start_date_time_seconds = strtotime($date) + $start_time_seconds;
                $end_date_time_seconds = strtotime($date) + $end_time_seconds;
                $start_date_time = date('Y/m/d h:ia', $start_date_time_seconds);
                $end_date_time = date('Y/m/d h:ia', $end_date_time_seconds);

                $time_date_compare_start[] = $start_date_time_seconds;
                $time_date_compare_end[] = $end_date_time_seconds;

                $inventories[] = [
                    "product_id" => $product_id,
                    "inventory_id" => $inventory_id,
                    "quantity" => $cart_item["quantity"],
                    "hourly_price" => $item_price,
                    "subtotal" => $item_subtotal,
                    "set_id" => $rental_set_id,
                    "set_quantity" => $set_quantity,
                    "parent_id" => $parent_id,
                    "parent_inventory_id" => $parent_inventory_id,
                    "rental_by_day" => 0,
                    "rental_by_interval" => 0,
                    "rental_by_slot" => 1,
                    "interval_steps" => 0,
                    "rental_interval" => 0,
                    "time_slot_id" => $rental_by_slot_opt["time_slot_id"],
                    "start_date" => $start_date_time,
                    "end_date" => $end_date_time,
                    "product_options" => $rental_product_options_valuables ? $rental_product_options_valuables[$product_variant_id] : []
                ];

            }

        } else {
            // rental_by_day

            // $rental_product_options_valuables = get_rental_session_data('rental_product_options_valuables', []);

            $inventories[] = [
                "product_id" => $product_id,
                "inventory_id" => $inventory_id,
                "quantity" => $cart_item["quantity"],
                "hourly_price" => $item_price,
                "subtotal" => $item_subtotal,
                "set_id" => $rental_set_id,
                "set_quantity" => $set_quantity,
                "set_subtotal" => $set_subtotal,
                "sel_variant_id" => $sel_variant_id,
                "parent_id" => $parent_id,
                "parent_inventory_id" => $parent_inventory_id,
                "rental_by_day" => 1,
                "rental_by_interval" => 0,
                "rental_by_slot" => 0,
                "interval_steps" => 0,
                "rental_interval" => 0,
                "time_slot_id" => 0,
                "multiplier_applied" => $item_has_price_multiplier ? 1 : 0,
                "set_multiplier_applied" => $set_has_price_multiplier ? 1 : 0,
                "product_options" => isset($rental_product_options_valuables[$product_variant_id]) ? $rental_product_options_valuables[$product_variant_id] : $product_options
            ];

        }

    }

    // send the necessary data for quotes
    if ($inventories) {

        $opt_hide_time_pickers = get_option('rental_hide_time_pickers');
        $opt_default_end_time = get_option('rental_default_end_time', '05:00 PM');
        $opt_default_start_time = get_option('rental_default_start_time', '09:00 AM');
        $opt_hide_end_date = get_option('rental_hide_end_date');

        $start_date = isset($_COOKIE['rental_start_date']) && $_COOKIE['rental_start_date'] ? decrypt_data($_COOKIE['rental_start_date'], get_option('rental_encryption_key')) : '';
        $end_date = isset($_COOKIE['rental_end_date']) && $_COOKIE['rental_end_date'] ? decrypt_data($_COOKIE['rental_end_date'], get_option('rental_encryption_key')) : '';

        // Set default start time if time picker is hidden on calendar
        // if ($start_date && $opt_hide_time_pickers) {
        //     $start_date_exploded = explode(" ", $start_date);

        //     if (isset($start_date_exploded[1]) && isset($start_date_exploded[0])) {
        //         $start_date = $start_date_exploded[0] . ' ' . $opt_default_start_time;
        //     }
        // }

        if ( get_option('rental_synchronized_product_type') == "hourly" ) {
            $start_date = date("Y/m/d h:ia", min($time_date_compare_start));
        }

        $finilizedStartEndDate = RTDelivery::extractFinalRentalStartEndDate($start_date, $end_date, $opt_hide_time_pickers, $opt_default_start_time, $opt_default_end_time, $opt_hide_end_date);

        $start_date = $finilizedStartEndDate['rental_start_date'];
        $end_date = $finilizedStartEndDate['rental_end_date'];

        // Set default end time if time picker or end date is hidden on calendar
        // if (
        //     !$end_date &&
        //     ($opt_hide_time_pickers 
        //     || get_option('rental_hide_end_date'))
        // ) {
        //     $start_date_exploded = explode(" ", $start_date);

        //     if (isset($start_date_exploded[1]) && isset($start_date_exploded[0])) {
        //         $end_date = $start_date_exploded[0] . ' ' . $opt_default_end_time;
        //     }
        // }
        
        // if (
        //     $end_date &&
        //     ($opt_hide_time_pickers 
        //     || get_option('rental_hide_end_date'))
        // ) {
        //     $end_date_exploded = explode(" ", $end_date);

        //     if (isset($end_date_exploded[1]) && isset($end_date_exploded[0])) {
        //         $end_date = $end_date_exploded[0] . ' ' . $opt_default_end_time;
        //     }
        // }
      
        
        if ( get_option('rental_synchronized_product_type') == "hourly" ) {
            $end_date = date("Y/m/d h:ia", max($time_date_compare_end));
        }

        $days = rental_get_days();
        update_post_meta($order_id, "_rental_start_date", $start_date);
        update_post_meta($order_id, "_rental_end_date", $end_date);
        update_post_meta($order_id, "_rental_days", $days);

        $event_time = "";
        if (get_option("rental_event_start_time") && isset($_COOKIE["rental_event_time"]) && $_COOKIE["rental_event_time"]) {
            $event_time = date("Y/m/d", strtotime($start_date)) ." ". $_COOKIE["rental_event_time"];
            unset($_COOKIE["rental_event_time"]);
            setcookie('rental_event_time', '', time() - (31556952), "/", "", false, true);
        }
        update_post_meta($order_id, "_rental_event_time", $event_time);

        $shipping_selected = get_option('rental_pickup_delivery') === 'company_delivery_return';
        $fees = rental_calculate_order_total();

        $delivery_tax_settings = rental_get_delivery_tax_setting();

        $default_shipping = $delivery_cost = $delivery_tax_rate = $delivery_tax_value = $delivery_tax_id = $delivery_status = 0;
        if (!empty($fees['shipping'])) {
            $delivery_status = 1;
            // $delivery_cost = $fees['shipping']; // total delivery + pickup cost

            if ($delivery_tax_settings['delivery_tax']) {
                $delivery_tax_id = $fees['shipping_tax_id'];
                // $delivery_tax_rate = $fees['shipping_tax_rate'];
                $delivery_tax_value = $fees['shipping_tax'];
            }
        } 


        if (get_option("rental_do_not_use_rentopian_shipping")) {
            $default_shipping = 1;
            if ( !$delivery_status && !empty(wc_get_chosen_shipping_method_ids())) {
                $delivery_status = 1;
            }
        }

        $opt_pickup_delivery = get_option('rental_pickup_delivery', 'company_delivery_return');
        if ($opt_pickup_delivery == 'company_delivery_return') {
            $delivery_status = 1;
        } else if ($opt_pickup_delivery == 'client_pickup_return') {
            $delivery_status = 2;
        } else if ($opt_pickup_delivery == 'company_client_delivery_return') {

            if (isset($_COOKIE['rental_shipping_method'])) {
                $delivery_status = $_COOKIE['rental_shipping_method'];
                setcookie('rental_shipping_method', 1, time() - 3600, "/", "", false, true); // 1 hour expiration
                unset($_COOKIE['rental_shipping_method']);
            }
        }

        // $division_zip = get_option("rental_hide_zip")? '': $_COOKIE['rental_zip'];
        $decrypted_rental_zip = '';
        if (isset($_COOKIE['rental_zip'])) {
            $decrypted_rental_zip = decrypt_data($_COOKIE['rental_zip'], get_option('rental_encryption_key'));
        }
        $division_zip = get_option("rental_hide_zip") ? '' : $decrypted_rental_zip;

        $billing_address_2 = $wc_order->get_billing_address_2() ? $wc_order->get_billing_address_2() : '';
        $billing_address = $wc_order->get_billing_address_1() ? trim($wc_order->get_billing_address_1()) : '';
        
        $shipping_address = $wc_order->get_shipping_address_1() ? trim($wc_order->get_shipping_address_1()) : '';
        $shipping_address_2 = $wc_order->get_shipping_address_2() ? trim($wc_order->get_shipping_address_2()) : '';

        $rush_fee = rental_get_suitable_rush_fee();
        $rush_fee["total"] = !empty($fees['rush_fee']) ? $fees['rush_fee'] : 0;

        $coupon_code = '';
        $coupons = get_applied_coupons();
        if (!empty($coupons)) {
            // if (count($coupons) > 1) {
            //     $coupon_codes_array = []; 
            //     foreach($coupons as $coupon) {
            //         $coupon_codes_array[] = $coupon->get_code();
            //     }
            //     $coupon_code = implode(',', $coupon_codes_array);
            // } else {
                // $coupon_code = $coupons[0]['code'];
            // }

            $coupon_code = $coupons[0]['code'];

            $couponDiscount = get_rental_session_data('rental_coupon_discount', 0);
            // update coupon in db
            update_post_meta($order_id, "_cart_discount", !empty($couponDiscount) ? $couponDiscount : $fees['coupon_discount']);
        }
        

        $deposit_id = $deposit_amount_raw = $deposit_is_percent = $deposit_amount = 0;
        if ($deposit = rental_get_deposit()) {
            $deposit_id = isset($deposit['id']) && $deposit['id'] ? $deposit['id'] : 0;
            $deposit_amount_raw = isset($deposit['amount']) && $deposit['amount'] ? $deposit['amount'] : 0;
            $deposit_is_percent = isset($deposit['is_percent']) && $deposit['is_percent'] ? $deposit['is_percent'] : 0;

            if ( $total_excluded_extra_fees = get_rental_session_data('total_excluded_extra_fees', 0) ) {
                $deposit_amount = $deposit_is_percent == 1 ? format_value_to_fixed_precision($total_excluded_extra_fees * ($deposit_amount_raw / 100), 2) : $deposit_amount_raw;
            }
        }

        if (isset(WC()->cart->rental_deposit['deposit_enabled']) && WC()->cart->rental_deposit['deposit_enabled']) {
            $deposit_id = WC()->cart->rental_deposit['deposit_id'];
            $deposit_amount = WC()->cart->rental_deposit['deposit_amount'];
        }

        $custom_fields = isset($_POST["rental_custom_fields"])? json_encode($_POST["rental_custom_fields"]): "";
        $security_deposit_settings = rental_get_security_deposit();


        $rental_order_selected_options_opt = get_rental_session_data('rental_order_selected_options', []);
        $rental_order_selected_options_of_sets = get_rental_session_data("rental_order_selected_options_of_sets", []);

        // tracking wc shipping method only if rentopian shipping is disabled
        if (
            $wc_shipping_method = get_rental_session_data('wc_shipping_method', 0)
            && get_option('rental_do_not_use_rentopian_shipping')
            && get_option('rental_track_wc_shipping')
        ) {
            $delivery_status = $wc_shipping_method;
        }


        $charge_only_delivery_for_website = get_rental_session_data('charge_only_delivery_for_website', 0);
        $delivery_cost_with_additionals = get_rental_session_data('rental_delivery_cost', 0);
        $pickup_cost_with_additionals = !$charge_only_delivery_for_website ? get_rental_session_data('rental_pickup_cost', 0) : 0;
        
        $timezone = rental_get_timezone();
        $exact_time = $startDateTime = $endDateTime = '';
        if (
            isset($_COOKIE['rental_selected_delivery_selection_time'])
            && $_COOKIE['rental_selected_delivery_selection_time']
        ) {

            $deliveryTimesData = RTDelivery::extractDeliveryStartEndTime($start_date, $timezone, $_COOKIE['rental_selected_delivery_selection_time']);

            $startDateTime = $deliveryTimesData['start_time'];
            $endDateTime = $deliveryTimesData['end_time'];
        }


        $pickup_exact_time = $pickupStartDateTime = $pickupEndDateTime = '';
        if (
            isset($_COOKIE['rental_selected_pickup_selection_time'])
            && $_COOKIE['rental_selected_pickup_selection_time']
        ) {

            $pickupTimesData = RTDelivery::extractPickupStartEndTime($end_date, $timezone, $_COOKIE['rental_selected_pickup_selection_time']);

            $pickupStartDateTime = $pickupTimesData['start_time'];
            $pickupEndDateTime = $pickupTimesData['end_time'];
        }

        // echo "<pre>"; print_r($inventories); echo "</pre>"; exit;

        $exclude_delivery_from_coupon = !empty(rental_get_coupon_settings()) ? rental_get_coupon_settings()["exclude_delivery_from_coupon"] : NULL;

        $data = [
            "wp_order_id" => $order_id,
            "inventories" => json_encode($inventories),
            "order_options" => isset($rental_order_selected_options_opt) && $rental_order_selected_options_opt  ? json_encode($rental_order_selected_options_opt) : "",
            "order_options_sets" => isset($rental_order_selected_options_of_sets) ? json_encode($rental_order_selected_options_of_sets) : "",
            "total" => (float) $wc_order->get_total(),
            "type" => get_option("rental_direct_only_bookings")? "order": "quote",
            "gmt_offset" => get_option("timezone_string")?: get_option("gmt_offset"),
            "start_date" => $start_date,
            "end_date" => $end_date,
            "days" => $days,
            "event_time" => $event_time,
            // "delivery_restriction_met" => 0,
            "new_delivery_system" => 1, // TODO : Must be removed after updating all the clients websites
            "delivery_cost" => $delivery_status == 1 ? $delivery_cost_with_additionals : 0,
            "total_delivery_cost" => $delivery_status == 1 ? $delivery_cost_with_additionals : 0,
            "pickup_cost" => $delivery_status == 1 ? $pickup_cost_with_additionals : 0,
            "total_pickup_cost" => $delivery_status == 1 ? $pickup_cost_with_additionals : 0,
            "delivery_tax" => $delivery_tax_value,
            "delivery_tax_id" => $delivery_tax_id,
            "delivery_status" =>  $delivery_status,
            "custom_delivery" => $default_shipping,
            "rental_tax_id" => !empty($fees['rental_tax_id']) ? $fees['rental_tax_id'] : 0,
            "rental_taxable_amount" => (float) get_rental_session_data('rental_taxable_amount'),
            "sale_tax_id" => !empty($fees['sale_tax_id']) ? $fees['sale_tax_id'] : 0,
            "service_tax_id" => !empty($fees['service_tax_id']) ? $fees['service_tax_id'] : 0,
            "exempt_waiver" => isset($fees['damage_waiver']) && $fees['damage_waiver'] ? 0: 1,
            "damage_waiver_tax_id" => !empty($fees['damage_waiver_tax_id']) ? $fees['damage_waiver_tax_id'] : 0,
            "rush_fee" => $rush_fee["total"],
            "rush_fee_amount" => $rush_fee["amount"],
            "rush_fee_type" => $rush_fee["type"],
            "coupon_code" => $coupon_code,
            "discount_before_tax" => !empty($fees['discount_before_tax']) ? $fees['discount_before_tax'] : 0,
            "order_fees" => empty($fees['order_fees'])? null: json_encode($fees['order_fees']),
            "deposit_id" => $deposit_id,
            "deposit_amount" => $deposit_amount,
            "firstname" => $wc_order->get_billing_first_name(),
            "lastname" => $wc_order->get_billing_last_name(),
            "company" => $wc_order->get_billing_company(),
            "email" => $wc_order->get_billing_email(),
            "phone" => $wc_order->get_billing_phone(),
            "address" => $billing_address,
            "address_2" => $billing_address_2,
            "city" => $wc_order->get_billing_city(),
            "state" => $wc_order->get_billing_state(),
            "country" => $wc_order->get_billing_country(),
            "zip" => $wc_order->get_billing_postcode()?: $division_zip,
            "division_zip" => $division_zip,
            "division_id" => get_option('rental_select_division') && isset($_COOKIE['rental_division_id'])? $_COOKIE['rental_division_id']: '',
            "shipping_address" => $delivery_status == 1 ? $shipping_address : '',
            "shipping_address_2" => $delivery_status == 1 ? $shipping_address_2 : '',
            "shipping_zip" => $wc_order->get_shipping_postcode()?: $division_zip,
            "shipping_city" => $wc_order->get_shipping_city(),
            "shipping_state" => $wc_order->get_shipping_state(),
            "shipping_country" => $wc_order->get_shipping_country(),
            "send_email" => get_option("rental_send_email")? 1: 0,
            "notes" => $wc_order->get_customer_note(),
            "custom_fields" => $custom_fields,
            "referral_source_id" => get_rental_session_data('rental_referral_source_id', 0),
            "event_type" => get_rental_session_data('rental_event_type_title', ''),
            "exclude_delivery_from_coupon" => $exclude_delivery_from_coupon
        ];

        // stripping zip (billing post code) and shipping zip (shipping post code) extensions if exists 
        $data['zip'] = strip_zip_code_extensions($data['zip']);
        $data['shipping_zip'] = strip_zip_code_extensions($data['shipping_zip']);

        if ($delivery_status == 1) {
            if ($delivery_venue_address_id = get_rental_session_data('rental_delivery_venue_address_id', 0)) {
                $data['venue_address_id'] = $delivery_venue_address_id;
            }

            if (!$charge_only_delivery_for_website) {
                $pickup_address_type = get_rental_session_data('rental_pickup_address_type', 1);
                if ($pickup_venue_address_id = get_rental_session_data('rental_pickup_venue_address_id', 0)) {
                    $data['pickup_address_id'] = $pickup_address_type == 2 ? $pickup_venue_address_id : 0;
                }
    
                $data['pickup_address_type'] = $pickup_address_type;
            }


            $data["delivery_date_time"] = json_encode([
                "type" => "window",
                "start_time" => $startDateTime ? $startDateTime : '',
                "end_time" => $endDateTime ? $endDateTime : '',
                // "exact_time" => 0,
            ]);

            $data["pickup_data_time"] = json_encode([
                "pickup_date_type" => "window",
                "pickup_start_date" => $pickupStartDateTime ? $pickupStartDateTime : '',
                "pickup_end_date" => $pickupEndDateTime ? $pickupEndDateTime : '',
                // "pickup_exact_date" => ""
            ]);

        }


        // adding security deposit calculations and settings to order
        if (!empty($fees['security_deposit_fee'])) {
            $data["security_deposit_id"] = !empty($security_deposit_settings) ? $security_deposit_settings['id'] : 0;
            $data["security_deposit_rate"] = !empty($security_deposit_settings) ? $security_deposit_settings['rate'] : 0;
            $data["security_deposit_amount"] = !empty($fees['security_deposit_fee']) ? $fees['security_deposit_fee'] : 0;
            $data["security_deposit_on_replacement"] = !empty($security_deposit_settings) ? $security_deposit_settings['on_replacement'] : 0;
        }

        if ($shipping_selected && isset($_POST['rental_different_pick_up_address'])) {

            $data['pick_up_address'] = $delivery_status == 1 ? $_POST['rental_pick_up_address_1'] : '';

            if (!empty($_POST['rental_pick_up_address_2'])) {
                $data['pick_up_address_2'] = $delivery_status == 1 ? $_POST['rental_pick_up_address_2'] : '';
            }
            $data['pick_up_zip'] = $_POST['rental_pick_up_postcode'];
            $data['pick_up_city'] = $_POST['rental_pick_up_city'];
            $data['pick_up_state'] = $_POST['rental_pick_up_state'];
            $data['pick_up_country'] = $_POST['rental_pick_up_country'];
        }

        // adding auto tax data to order
        if (isset($fees['is_auto_tax']) && $fees['is_auto_tax'] == 1 && isset($fees['auto_tax'])) {
            $data['is_auto_tax'] = $fees['is_auto_tax'];
            $data['auto_tax_rate'] = $fees['auto_tax_rate'];
            $data['auto_tax'] = $fees['auto_tax'];
        }

        rental_send_order($order_id, $data);
        unset_temporary_data();
    }
}

function rental_send_order($order_id, $data, $resend = false) {
    global $wpdb, $rental_tables;
    $rental_order_relations = $wpdb->prefix . $rental_tables["order_relations"];

    $log = [
        "rental_id" => 0,
        "http_code" => 200,
        "message" => "",
        "register_time" => time()
    ];

    try {
        $rental_order = rental_curl("orders/add", get_option("rental_api_key"), true, $data);
       
        if (isset($rental_order->id)) {
            $log["rental_id"] = $rental_order->id;
        }
    } catch (RentalException $e) {
        $log["http_code"] = $e->getStatusCode();
        $log["message"] = $e->getMessage();
    }

    if ($resend) {
        $wpdb->update($rental_order_relations, $log, ["id" => $order_id]);
    } else {
        $log["id"] = $order_id;
        $log["data"] = serialize($data);
        $log["version"] = RENTOPIAN_SYNC_VERSION;
        $wpdb->insert($rental_order_relations, $log);
    }

    if ($wpdb->last_error !== "") {
        throw new RentalException("SQL_ERROR: $wpdb->last_error (SQL: $wpdb->last_query)");
    }

    return $log;
}

// send the payment data
function rental_pay_order($order_id) {
    global $wpdb, $rental_tables;
    $rental_order_relations = $wpdb->prefix . $rental_tables["order_relations"];

    $rental_order_id = $wpdb->get_var("SELECT `rental_id` FROM $rental_order_relations WHERE `id` = $order_id");
    if ( !$rental_order_id) {
        return;
    }

    $wc_order = (new WC_Order($order_id));
    $payment_method = $wc_order->get_payment_method();
    $transaction_id = $wc_order->get_transaction_id();
    if ($payment_method == "cod" || $payment_method == "cheque" || !$transaction_id) {
        return;
    }

    // $amount = $wc_order->get_total();
    $amount = get_rental_session_data('total_excluded_extra_fees', 0);

    $data_to_send = [
        "wp_order_id" => $order_id,
        "order_id" => $rental_order_id,
        "transaction_id" => $transaction_id,
        "amount" => (float) $amount,
    ];

    $payment_tip_id = get_rental_session_data('rental_payment_tip_id', 0);
    // $payment_tip_id = get_option('rental_payment_tip_id' . get_new_unique_id(), 0);
    $payment_tip_amount = get_rental_session_data('rental_payment_tip_amount', 0);
    // $payment_tip_amount = get_option('rental_payment_tip_amount' . get_new_unique_id(), 0);

    if ($payment_tip_id && $payment_tip_amount) {
        $data_to_send = [
            "wp_order_id" => $order_id,
            "order_id" => $rental_order_id,
            "transaction_id" => $transaction_id,
            "amount" => (float) $amount,
            "tip_id" => $payment_tip_id,
            "tip_amount" => $payment_tip_amount,
        ];
    }
    
    $rental_payment = rental_curl("orders/pay", get_option("rental_api_key"), true, $data_to_send);
}

// send the payment data
function rental_delete_order($order_id) {
    global $wpdb, $rental_tables;
    $rental_order_relations = $wpdb->prefix . $rental_tables["order_relations"];

    $rental_order_id = $wpdb->get_var("SELECT `rental_id` FROM $rental_order_relations WHERE `id` = $order_id");
    if ( !$rental_order_id) {
        return;
    }

    $wc_order = (new WC_Order($order_id));
    $payment_method = $wc_order->get_payment_method();
    $transaction_id = $wc_order->get_transaction_id();
    if ($payment_method == "cod" || $payment_method == "cheque" || !$transaction_id) {
        $amount = 0;
    } else {
        $amount = $wc_order->get_total();
    }
    

    if (time() < $wc_order->get_date_created()->getTimestamp() + 5400) { // 5400 seconds is 90 minutes
        return;
    }

    rental_curl("orders/delete", get_option("rental_api_key"), true, [
        "wp_order_id" => $order_id,
        "order_id" => $rental_order_id,
        "amount" => $amount
    ]);
}

// Check if set, if its not set add an error.
function rental_checkout_process($order_id) {

    // $rental_shipping_has_error = get_rental_session_data('rental_shipping_has_error', 0);
    // if ($rental_shipping_has_error) {
    //     // wc_add_notice(__('Please contact us for a quote since you are outside of our delivery zone', 'rentopian-sync'), 'error');
    //     wc_add_notice(__('There is a temporary issue with delivery system. Please Contact us for a quote until the issue is solved.', 'rentopian-sync'), 'error');
    // }

    if (isset($_POST['rental_event_time']) && $_POST['rental_event_time']) {
        $_COOKIE["rental_event_time"] = $_POST['rental_event_time'];
        setcookie('rental_event_time', $_POST['rental_event_time'], time() + (10800), "/", "", false, true);
    }


    if (get_option('rental_synchronized_product_type') == "hourly") {

        if ( !isset($_COOKIE["rental_hourly_start_date"])) {
            wc_add_notice(__('Rental Start date is required.', 'rentopian-sync'), 'error');
        }

    } else {

        if (!isset($_COOKIE['rental_start_date']) || !$_COOKIE['rental_start_date']) {
            wc_add_notice(__('Rental Start date is required.', 'rentopian-sync'), 'error');
        }

        if (isset($_COOKIE['rental_start_date']) && $_COOKIE['rental_start_date']
            // && strtotime($_COOKIE['rental_start_date']) < strtotime("today")
        ) {

            $decrypted_rental_start_date = "";
            if (isset($_COOKIE['rental_start_date']) && $_COOKIE['rental_start_date']) {
                $decrypted_rental_start_date = decrypt_data($_COOKIE['rental_start_date'], get_option('rental_encryption_key'));
            }

            if (empty($decrypted_rental_start_date) || ($decrypted_rental_start_date && strtotime($decrypted_rental_start_date) < strtotime("today"))) {
                wc_add_notice(__('Please select a valid rental start date.', 'rentopian-sync'), 'error');
            }
            
        }

        if (!isset($_COOKIE['rental_zip'])) {
            wc_add_notice(__('ZIP Code (submitted via rental dates selection form) is required.', 'rentopian-sync'), 'error');
        }

    }
    
    // only when allow overbook is disabled validate inventories before checkout 
    if (get_option('rental_allow_overbook', 1) != 1) {
        $_cart = WC()->cart;
        $cart_contents = $_cart->cart_contents;
        $sum_quantity_in_cart = [];
        $inventories = [];
        foreach ($cart_contents as $cart_item_key => $cart_item) {
            global $wpdb, $rental_tables;
            $rental_set_relations = $wpdb->prefix . $rental_tables["set_relations"];
    
            $product_id = $cart_item['product_id'];
            $variation_id = $cart_item['variation_id'] ? $cart_item['variation_id'] : $cart_item['product_id'];
            // if (rental_check_product_availability($variation_id) == 0) {
            //     $_cart->remove_cart_item($cart_item_key);
            //     continue;
            // }
    
            $cart = [];
            if ($cart_item["key"] != $cart_item_key) {
                $unique_key = $cart_item["product_id"] . "_" . $cart_item["variation_id"];
                if (isset($cart[$unique_key])) {
                    $cart[$unique_key] += $cart_item["quantity"];
                } else {
                    $cart[$unique_key] = $cart_item["quantity"];
                }
            }
    
            $inv_id = 0;
            if (get_post_meta($product_id, '_rental_is_set', true)) {
                $set_id = $wpdb->get_var("SELECT `rental_id` FROM $rental_set_relations WHERE `id` = " . $product_id);
                $add_ons = get_post_meta($product_id, '_rental_set_items', true);
                foreach ($add_ons as $i => $add_on) {
                    if ($add_on['variant_id']) {
                        $add_on['inv_id'] = get_post_meta($add_on['variant_id'], '_rental_inventory_id', true);
                    } else {
                        $add_on['variant_id'] = 0;
                        $add_on['inv_id'] = get_post_meta($add_on['product_id'], '_rental_inventory_id', true);
                    }
                    $add_on['price'] = 0;
                    $add_on['required'] = true;
                    $add_on['set_id'] = $set_id;
                    $add_ons[$i] = $add_on;
                    $inventories[] = $add_on['inv_id'];
                }
            } else {
                $inventories[] = $inv_id = get_post_meta($variation_id?: $product_id, '_rental_inventory_id', true);
                $add_ons = get_post_meta($product_id, '_rental_add_ons', true);
                if ( !empty($add_ons)) {
                    foreach ($add_ons as $i => $add_on) {
                        $product = wc_get_product($add_on['product_id']);
                        if ($product->is_type('variable')) {
                            if ( !$add_on['variant_id']) {
                                $variants = $product->get_visible_children();
    
                                if ( !isset($variants[0])) {
                                    $error_msg = 'Sorry, this product is not available.';
                                    wc_add_notice(__($error_msg, 'rentopian-sync'), 'error');
                                    return;
                                }
                                if (isset($_POST['rental_add_on_variants']) && isset($_POST['rental_add_on_variants'][$add_on['product_id']]) &&
                                    in_array($_POST['rental_add_on_variants'][$add_on['product_id']], $variants)) {
                                    $add_on['variant_id'] = $_POST['rental_add_on_variants'][$add_on['product_id']];
                                } else {
                                    $add_on['variant_id'] = $variants[0];
                                }
                            }
                            $add_on['inv_id'] = get_post_meta($add_on['variant_id'], '_rental_inventory_id', true);
                        } else {
                            $add_on['inv_id'] = get_post_meta($add_on['product_id'], '_rental_inventory_id', true);
                        }
                        $add_on['set_id'] = 0;
                        $add_ons[$i] = $add_on;
                        $inventories[] = $add_on['inv_id'];
                    }
                }
            }
    
            $sum_quantity_in_cart[$inv_id] = $cart_item["quantity"];
            $item_cart_keys[$inv_id] = $cart_item_key;
            if (isset($cart[$product_id . "_" . $variation_id])) {
                $sum_quantity_in_cart[$inv_id] += $cart[$product_id . "_" . $variation_id];
            }
        }
    
        // only when allow overbook is disabled(on the fly) validate inventories before checkout 
        $availability = rental_check_availability($inventories);
        $validation_has_error = false;
        $validation_error_list = [];
        $return_to_shop_html_link = '<a target="_blank" href="' . esc_url( wc_get_page_permalink( 'shop' ) ) . '" class="wc-backward">' . __( 'return to shop', 'woocommerce' ) . '</a>';
        $custom_cart_label = get_option('rental_cart_button_text') ? lcfirst(get_option('rental_cart_button_text')) : 'cart';
        $custom_cart_label_html_link = "<a target='_blank' href='" . esc_url(wc_get_cart_url()) . "'>" .$custom_cart_label. "</a>"; 
        if (isset($availability['allow_overbook']) && !$availability['allow_overbook']) {
            
            if (empty($inventories) || empty($availability)) {
                wc_add_notice(__('Unfortunately, there was a change in product availability. Please, review your '.$custom_cart_label_html_link.' again.', 'rentopian-sync'), 'error');
                return;
            }
            if (isset($availability["inventories"])) {
                foreach($availability["inventories"] as $inventory) {
                    if(isset($inventory['id'])) {
                        $inv_id = $inventory['id'];
                        $available_quantity = $inventory["quantity"];
                        $name = isset($item_cart_keys[$inv_id]) && $item_cart_keys[$inv_id] && isset($cart_contents[$item_cart_keys[$inv_id]])? '"' . $cart_contents[$item_cart_keys[$inv_id]]['data']->get_name() . '" ': '';
                        if (empty($available_quantity)) {
                            $validation_has_error = true;
                            WC()->cart->remove_cart_item($item_cart_keys[$inv_id]);
                            $validation_error_list[] = __($name . ' : Removed from cart!', 'rentopian-sync');

                        } else if (isset($sum_quantity_in_cart[$inv_id]) && $sum_quantity_in_cart[$inv_id] > $available_quantity) {
                            $validation_has_error = true;
                            $validation_error_list[] = __($name . ' : Only', 'rentopian-sync') . " $available_quantity $name " . __('available. ', 'rentopian-sync');
                        }
                    }
                }
            }
        }

        if ($validation_has_error && $validation_error_list) {
            $err_wrapper = __('Unfortunately, there was a change in product(s) availability. Please, review your '.$custom_cart_label_html_link.' again or ' . $return_to_shop_html_link, 'rentopian-sync');
            $err_wrapper .= "<br/> <ul>";
            foreach($validation_error_list as $err_msg) {
                $err_wrapper .= "<li> - " . $err_msg . "</li>";
            }
            $err_wrapper .= "</ul>";

            wc_add_notice($err_wrapper, 'error');
            return;
        }
    }
   
    $check = rental_check_selected_options();
    if ($check["check"] === false) {
        wc_add_notice(__('Please review the <a href="'.$check["url"].'" > options</a> before checking out.', 'rentopian-sync'), 'error');
    }

    // $min_order_amount = get_option('rental_min_order_amount');
    $delivery_settings = rental_get_delivery_settings();
    $min_order_amount = $delivery_settings['restriction_fixed_min_for_website'];
    if (
        $min_order_amount 
        && WC()->cart->get_subtotal() < $min_order_amount
        // && (get_option('rental_pickup_delivery') === 'company_delivery_return' || !get_option('rental_min_order_pickup'))) {
        && (get_option('rental_pickup_delivery') === 'company_delivery_return' 
        || !$delivery_settings['restriction_fixed_min_allow_pickup_for_website'] )
    ) {
        
        // $message = get_option('rental_min_order_text');
        $message = $delivery_settings['restriction_fixed_min_message_for_website'];
        if ( !$message) {
            $message = 'You must have an order with a minimum of ' . wc_price($min_order_amount) . ' to place your order.';
        }
        wc_add_notice($message, 'error');
    }


    if (isset($_POST['rental_different_pick_up_address']) 
        && $delivery_settings['enable_different_pickup_delivery_address_for_website']
        // && get_option('rental_different_pick_up_addresses')
        && get_option('rental_pickup_delivery') === 'company_delivery_return'
    ) {
        if (empty($_POST['rental_pick_up_country'])) {
            wc_add_notice(__('Pick up country is required', 'rentopian-sync'), 'error');
        }
        if (empty($_POST['rental_pick_up_address_1'])) {
            wc_add_notice(__('Pick up street address is required', 'rentopian-sync'), 'error');
        }
        if (empty($_POST['rental_pick_up_city'])) {
            wc_add_notice(__('Pick up city is required', 'rentopian-sync'), 'error');
        }
        if (empty($_POST['rental_pick_up_state'])) {
            wc_add_notice(__('Pick up state is required', 'rentopian-sync'), 'error');
        }
        if (empty($_POST['rental_pick_up_postcode'])) {
            wc_add_notice(__('Pick up zip is required', 'rentopian-sync'), 'error');
        }
    }

    if (!get_option('rental_direct_only_bookings')) {
        add_filter('woocommerce_cart_needs_payment', 'return_false');
    }
    
    if (isset($_POST['payment_method'])) {
        if (!get_option('rental_direct_only_bookings')) {
            wc_add_notice(__('No need to make payment', 'rentopian-sync'), 'error');
        }
    }

    $email = isset($_POST['billing_email']) ? $_POST['billing_email'] : null;
    $phone = isset($_POST['billing_phone']) ? $_POST['billing_phone'] : null;
    $billing_first_name = isset($_POST['billing_first_name']) ? $_POST['billing_first_name'] : null;
    $billing_last_name = isset($_POST['billing_last_name']) ? $_POST['billing_last_name'] : null;
    
    $check_blocked_client = rental_check_blacklisted_client($email, $phone, $billing_first_name, $billing_last_name);
    if (is_array($check_blocked_client) && isset($check_blocked_client['message'])) {
        if ($check_blocked_client['message'] != 'no_match_found') {
            wc_add_notice(__($check_blocked_client['message'], 'rentopian-sync'), 'error');
        }
    }

    // check google map zip code against rental form zip code
    $billing_postcode = isset($_POST['billing_postcode']) ? $_POST['billing_postcode'] : null;
    $shipping_postcode = isset($_POST['shipping_postcode']) ? $_POST['shipping_postcode'] : null;
    $rental_pick_up_postcode = isset($_POST['rental_pick_up_postcode']) ? $_POST['rental_pick_up_postcode'] : null;
    $checkout_form_zip = $billing_postcode;
    if (is_null($billing_postcode)) {
        $checkout_form_zip = $shipping_postcode;
        if (is_null($shipping_postcode)) {
            $checkout_form_zip = $rental_pick_up_postcode;
        }
    }
    
    $decrypted_rental_zip = '';
    if (isset($_COOKIE['rental_zip'])) {
        $decrypted_rental_zip = decrypt_data($_COOKIE['rental_zip'], get_option('rental_encryption_key'));
    }

    $rental_zip = isset($_COOKIE['rental_zip']) && !get_option('rental_hide_zip') ? $decrypted_rental_zip : '';

    if (!empty($checkout_form_zip) && !empty($rental_zip) && ($checkout_form_zip != $rental_zip)) {
        wc_add_notice('The ZIP code provided in the rental form differs from the ZIP code of the specified address. Please either change the ZIP code on the rental form to match with the current address or change the current address to match the ZIP code provided in the rental form.', 'error');
    }

    if (isset($_POST['shipping_method']) && is_array($_POST['shipping_method'])) {
        
        $rental_shipping_method_value = str_contains($_POST['shipping_method'][0], 'local_pickup') ? 2 : 1;
        $_COOKIE['rental_shipping_method'] = $rental_shipping_method_value;
        setcookie('rental_shipping_method', $rental_shipping_method_value, time() + (3600), "/", "", false, true); // 1 hour expiration
    }

    if (isset($_POST['rental_referral_source_id']) && $_POST['rental_referral_source_id']) {
        set_rental_session_data('rental_referral_source_id', intval($_POST['rental_referral_source_id']));
    }

    if (isset($_POST['rental_event_types_id']) && $_POST['rental_event_types_id']) {
        $event_type_id = intval($_POST['rental_event_types_id']);
        $rental_event_types = get_option('rental_event_types', []);

        $rental_event_type_title = '';
        if ($rental_event_types) {
            foreach ($rental_event_types as $option) {
                if ($option->id == $event_type_id) {
                    $rental_event_type_title = $option->title;

                    break;
                }
            }
        }

        set_rental_session_data('rental_event_type_title', $rental_event_type_title);
    }

    if (
        isset($_POST['rental_payment_tip_id']) 
        && $_POST['rental_payment_tip_id']
        && get_option("rental_direct_only_bookings", 0)
        && get_option("rental_payment_tips_enabled", 0)
    ) {

        $tip_id = intval($_POST['rental_payment_tip_id']);
        calculate_tip_amount($tip_id);
    }

    $rental_custom_fields = get_option('rental_custom_fields');
    if ($rental_custom_fields !== false && $rental_custom_fields && isset($_POST['rental_custom_fields'])) {
        
        $groups = $rental_custom_fields;
        
        foreach ($groups as $group) {
            foreach ($group as $field) {
                $val = isset($_POST['rental_custom_fields'][$field['id']]) ? $_POST['rental_custom_fields'][$field['id']] : 0;

                if ($field['required'] == 1 && empty($val)) {
                    wc_add_notice(__($field['title'] . ' is required', 'rentopian-sync'), 'error');
                }
            }
        }
    }   


    if (get_option('rental_do_not_use_rentopian_shipping') && get_option('rental_track_wc_shipping')) {
        
        $wc_shipping_method = 1;
        if (str_contains($_POST['shipping_method'][0], 'local_pickup')) {
            $wc_shipping_method = 2;
        } else if (str_contains($_POST['shipping_method'][0], 'free_shipping') || str_contains($_POST['shipping_method'][0], 'flat_rate')) {
            $wc_shipping_method = 1;
        }
        
        set_rental_session_data('wc_shipping_method', $wc_shipping_method);

        // $_COOKIE['wc_shipping_method'] = $wc_shipping_method;
        // setcookie('wc_shipping_method', $wc_shipping_method, time() + (21600), "/", "", false, true); // 6 hour expiration
    }

   
    $coupons = get_applied_coupons();
    if (isset($coupons[0]) && isset($coupons[0]['code'])){

        $coupon_code = $coupons[0]['code'];
        if ($coupon_code) {
            $coupon_post_id = get_coupon_id_by_title($coupon_code);

            if ($coupon_post_id) {
                $coupon_usage_limit = get_post_meta($coupon_post_id, 'usage_limit', true);
                
                if ($coupon_usage_limit && $coupon_usage_limit != 99999) {
                    

                    $decrypted_rental_start_date = "";
                    if (isset($_COOKIE['rental_start_date']) && $_COOKIE['rental_start_date']) {
                        $decrypted_rental_start_date = decrypt_data($_COOKIE['rental_start_date'], get_option('rental_encryption_key'));
                    }

                    if ($decrypted_rental_start_date) {

                        // check for coupons with usage limitation 
                        // if the usage limit has been reached, the order will not proceed
                        rental_curl('coupons/check', get_option('rental_api_key'), false, [
                            'coupon_code' => $coupon_code,
                            'start_date' => $decrypted_rental_start_date,
                        ]);

                    } else {

                        wc_add_notice(__('Rental start date is required.', 'rentopian-sync'), 'error');
                    }
                }
            }
        }
    }

}

function rental_validate_payjunction_gateway_plugin() {
            
    if (class_exists('WC_Gateway_PayJunction') && get_option('rental_direct_only_bookings')) {

        $fees = rental_calculate_order_total();
        $coupons = get_applied_coupons();

        $coupon_discount = 0;
        if(isset($coupons[0])){
            $couponDiscount = get_rental_session_data('rental_coupon_discount', 0);

            if (empty($couponDiscount)) {

                if ($coupons[0]['discount_type'] == 'percent') {
                    $coupon_discount = $fees['total'] * $coupons[0]['amount'] / 100;
                } else if ($coupons[0]['discount_type'] == 'fixed_cart') {
                    $coupon_discount = $coupons[0]['amount'];
                }

            } else {

                $coupon_discount = $couponDiscount;
            }
           
        }

        if ($fees['total'] == $coupon_discount) {
            return true;
        }

        $error_msg = 'The payment required fields must be filled!';
        if (
            !isset($_POST['payjunction-card-number']) 
            || !isset($_POST['payjunction-card-expiry']) 
            || !isset($_POST['payjunction-card-cvc']) 
        ) {

            wc_add_notice(__($error_msg, 'rentopian-sync'), 'error');

        } else {

            if (
                empty($_POST['payjunction-card-number']) 
                || empty($_POST['payjunction-card-expiry']) 
                || empty($_POST['payjunction-card-cvc']) 
            ) {
                wc_add_notice(__($error_msg, 'rentopian-sync'), 'error');
            }

        }
        
    }
}

// Our hooked in function - $fields is passed via the filter!
function rental_override_checkout_fields($fields) {

    $fields['billing']['billing_phone']['required'] = true;

    if ( isset( $fields['order']['coupon_code'] ) ) {
        $rental_coupon_label_text = get_option('rental_coupon_label_text', 'Coupon');
        $fields['order']['coupon_code']['label']       = $rental_coupon_label_text;
        $fields['order']['coupon_code']['placeholder'] = sprintf(
            /* translators: %s = label */
            __( 'Enter your %s', 'dynamic-promo-label' ),
            strtolower( $rental_coupon_label_text )
        );
    }

    $rental_street_address_label_text = get_option('rental_street_address_label_text', 'Street address');
    if ( isset( $fields['billing']['billing_address_1']['label'] ) ) { 
        $fields['billing']['billing_address_1']['label']       = $rental_street_address_label_text;
        // $fields['billing']['billing_address_1']['placeholder'] = '';
    }

    if ( isset( $fields['shipping']['shipping_address_1']['label'] ) ) {
        $fields['shipping']['shipping_address_1']['label']       = $rental_street_address_label_text;
        // $fields['shipping']['shipping_address_1']['placeholder'] = '';
    }

    return $fields;
}

function rental_override_checkout_fields_labels() {
    $rental_street_address_label_text = get_option('rental_street_address_label_text', 'Street address');
    if ($rental_street_address_label_text) {
        wp_send_json_success(['label' => $rental_street_address_label_text]);
    }
    wp_send_json_success(['label' => '']);
}

// Check api key
function rental_check_api_key ($api_key) {

    $opt_api_key_is_valid = get_option('rental_api_key_is_valid', 0);
    // if key is set valid in WP then don't check with the API
    if ($opt_api_key_is_valid == 1) {
        return true;
    }

    try {
        $rental_check_api_key = rental_curl('check/api_key', $api_key);
        update_option('rental_api_key_is_valid', 1);
    } catch (RentalException $e) {
        $rental_check_api_key = false;
    }

    return $rental_check_api_key;
}

// function ajax which is responsible for damage waiver
function wp_ajax_rental_damage_waiver() {
    if (isset($_POST['damage_waiver'])) {
        if ($_POST['damage_waiver'] == 'exempt') {
            $_COOKIE['rental_exempt_waiver'] = 1;
            setcookie('rental_exempt_waiver', 1, time() + (10800), "/", "", false, true);
            wp_send_json('exempt', 200);
            wp_die();
        } elseif ($_POST['damage_waiver'] == 'buy') {
            $_COOKIE['rental_exempt_waiver'] = 0;
            setcookie('rental_exempt_waiver', 0, time() + (10800), "/", "", false, true);
            wp_send_json('take', 200);
            wp_die();
        }
    }
    wp_send_json('error', 400);
    wp_die();
}

// function ajax which is responsible for applying coupon
function wp_ajax_rental_apply_coupon() {
    if (isset($_POST['coupon_code']) && $_POST['coupon_code']) {
        try {

            if (!WC()->cart->add_discount(sanitize_text_field($_POST['coupon_code']))) {
                unset($_COOKIE['rental_rentpro_coupon_code']);
                setcookie('rental_rentpro_coupon_code', false, time() - (31556952), "/", "", false, false);
    
                $error_msg = "The coupon code is invalid!";
                $_COOKIE['rental_rentpro_coupon_code_is_invalid_error'] = $error_msg;
                setcookie('rental_rentpro_coupon_code_is_invalid_error', $error_msg, time() + (3600), "/", "", false, true); // 1 hour expiration

                wp_send_json(['message' => 'The coupon code is not valid!']);
                wp_die();
            }

            $encrypted_rental_rentpro_coupon_code = encrypt_data($_POST['coupon_code'], get_option('rental_encryption_key'));
            $_COOKIE['rental_rentpro_coupon_code'] = $encrypted_rental_rentpro_coupon_code;
            setcookie('rental_rentpro_coupon_code', $encrypted_rental_rentpro_coupon_code, time() + (3600), "/", "", false, true); // 1 hour expiration

            wp_send_json(['message' => __('Coupon code applied successfully.', 'rentopian-sync')], 200);
            wp_die();
        } catch (RentalException $e) {

            unset($_COOKIE['rental_rentpro_coupon_code']);
            setcookie('rental_rentpro_coupon_code', false, time() - (31556952), "/", "", false, false);

            wp_send_json(['message' => $e->getMessage()], $e->getStatusCode());
            wp_die();
        }
    }
    wp_send_json(['message' => __('Error', 'rentopian-sync')], 400);
    wp_die();
}

// function ajax which is responsible for removing coupon
function wp_ajax_rental_remove_coupon() {
    if (isset($_POST['coupon_code']) && !empty($_POST['coupon_code'])) {
        $coupon_code = sanitize_text_field($_POST['coupon_code']);

        WC()->cart->remove_coupon($coupon_code);
        do_action( 'woocommerce_removed_coupon', $coupon_code );
        WC()->cart->calculate_totals();

        setcookie('rental_rentpro_coupon_code', '', time() - 3600, '/');

        wp_send_json([
            'message' => __('Coupon code removed successfully.', 'rentopian-sync'),
        ], 200);
    }

    wp_send_json(['message' => __('Invalid request.', 'rentopian-sync')], 400);
}

// function ajax which is responsible for getting multipliers
function wp_ajax_rental_get_multiplier() {

    if (isset($_GET['product_id']) && isset($_GET['variant_id'])) {

        $product_id = intval($_GET['product_id']);
        $variant_id = intval($_GET['variant_id']);
        $days = null;

        if ( 
            !get_option('rental_hide_product_price') && !get_option('rental_show_product_price_only_in_cart') &&
            !get_post_meta($product_id, '_rental_is_sale', true) 
        ) {

            // get price multiplier items of the current variant 
            $price_multipliers = get_price_multiplier_items_by_post_id($variant_id);
            if (isset($price_multipliers) && $price_multipliers) {
                $price_multiplier_items = isset($price_multipliers['price_multiplier_items']) && $price_multipliers['price_multiplier_items'] ? $price_multipliers['price_multiplier_items'] : [];
                if (!empty($price_multiplier_items)) {
                    $days = rental_get_daily_prices($price_multiplier_items);
                }
            }
            
        }

        wp_send_json(['days' => $days], 200);
        wp_die();
    }

    wp_send_json(['message' => __('Error', 'rentopian-sync')], 400);
    wp_die();
}

// function ajax which is responsible for setting rental dates
function wp_ajax_rental_dates() {
    if (isset($_POST['start_date'])) {

        unset_delivery_times_data();
        
        $opt_default_start_time = get_option('rental_default_start_time', '09:00 AM');
        $opt_default_end_time = get_option('rental_default_end_time', '05:00 PM');
        $opt_hide_time_pickers = get_option('rental_hide_time_pickers');

        $opt_hide_zip = get_option('rental_hide_zip');
        $opt_show_location = get_option('rental_show_location');
        
        // handling the ZIP code
        $zip = false;
        if ($opt_hide_zip) {
            $zip = true;
        } else {
            $zip = isset($_POST['zip']) && $_POST['zip'] ? $_POST['zip'] : false;
        }

        // handeling delivery input address
        $address = '';
        if ($opt_show_location) {
            if (isset($_POST['address']) && $_POST['address']) {
                $address = trim($_POST['address']);
            }
        }

        // handeling start/end date
        $rental_end_date = isset($_POST['end_date']) && $_POST['end_date'] ? $_POST['end_date'] : '';
        $rental_start_date = $_POST['start_date'] ? $_POST['start_date'] : '';

        $error = rental_validate_dates_form_and_get_products_data_init($opt_hide_time_pickers, $opt_hide_zip, $opt_show_location, $rental_start_date, $rental_end_date, $address, $zip); 
        if (is_null($error)) {

            // set start date time as start delivery time and end date time as pickup start time
            rental_set_selected_delivery_pickup_start_end_times($rental_start_date, $rental_end_date, $opt_default_start_time, $opt_default_end_time, $opt_hide_time_pickers);

            $add_to_cart_msg_success = $add_to_cart_msg_failure = $current_url ="";

            if (isset($_POST['pid']) && $_POST['pid'] && isset($_POST['url'])) {

                $current_url = $_POST['url'].'&added_to_cart=0';
                $product_id = intval($_POST['pid']);

                // check if rental is set then return
                if (get_post_meta($product_id, '_rental_is_set', true)) {
                    wp_send_json([
                        "current_url" => $current_url,
                        "shop_page_url" => get_permalink(wc_get_page_id('shop')),
                        "data" => '',
                        "add_to_cart_msg_success" => $add_to_cart_msg_success,
                        "add_to_cart_msg_failure" => $add_to_cart_msg_failure,
                        "message" => 'success'
                    ], 200);
                    wp_die();
                }
                 

                $cart = WC()->cart;
                $validate = rental_validate_cart_item($product_id, 0, 1, null, false, true);

                
                // check product options validity before add to cart
                $options_check = rental_check_selected_options_of_product($product_id);

                if ($validate == 'success' && $options_check) {

                    $current_url = $_POST['url'].'&added_to_cart=1';
                    $cart->add_to_cart($product_id, 1, 0);
                    calculate_cart_totals($cart);
                    $add_to_cart_msg_success = wc_add_to_cart_message([$product_id => 1], true, true);

                } else {

                    if (!$options_check) {
                         $custom_cart_label = get_option('rental_cart_button_text') ? lcfirst(get_option('rental_cart_button_text')) : 'cart'; 
                        $add_to_cart_msg_failure = 'Please review the options before adding to '.$custom_cart_label.'.';
                    } else {
                        $add_to_cart_msg_failure = $validate;
                    }

                }

            }

            $rental_unavailable_items_opt = get_option('rental_unavailable_items');

            wp_send_json([
                "current_url" => $current_url,
                "shop_page_url" => get_permalink(wc_get_page_id('shop')),
                "data" => $rental_unavailable_items_opt && is_array($rental_unavailable_items_opt) ? $rental_unavailable_items_opt : '',
                "add_to_cart_msg_success" => $add_to_cart_msg_success,
                "add_to_cart_msg_failure" => $add_to_cart_msg_failure,
                "message" => 'success'
            ], 200);
            wp_die();

        } else {

            wp_send_json(['message' => $error], 400);
            wp_die();
        }
    }
    wp_send_json(['message' => __('Error', 'rentopian-sync')], 400);
    wp_die();
}

function wp_ajax_rental_date_form_api() {
    if (isset($_POST['start_date'])) {

        unset_delivery_times_data();
        
        $opt_default_start_time = get_option('rental_default_start_time', '09:00 AM');
        $opt_default_end_time = get_option('rental_default_end_time', '05:00 PM');
        $opt_hide_time_pickers = get_option('rental_hide_time_pickers');

        $opt_hide_zip = get_option('rental_hide_zip');
        $opt_show_location = get_option('rental_show_location');
        
        // handling zip code
        $zip = false;
        if ($opt_hide_zip) {
            $zip = true;
        } else {
            $zip = isset($_POST['zip']) && $_POST['zip'] ? $_POST['zip'] : false;
        }

        // handling delivery input address
        $address = '';
        if ($opt_show_location) {
            if (isset($_POST['address']) && $_POST['address']) {
                $address = trim($_POST['address']);
            }
        }

        // handling start/end date
        $rental_end_date = isset($_POST['end_date']) && $_POST['end_date'] ? $_POST['end_date'] : '';
        $rental_start_date = $_POST['start_date'] ? $_POST['start_date'] : '';
        
        $error = rental_validate_dates_form_and_get_products_data_init($opt_hide_time_pickers, $opt_hide_zip, $opt_show_location, $rental_start_date, $rental_end_date, $address, $zip);
        if (!is_null($error)) {
            // submit button class
            if(isset($_COOKIE['rental_form_filled'])) {
                unset($_COOKIE['rental_form_filled']);
                setcookie('rental_form_filled', '', time() - (31556952), "/", "", false);
            }

            wp_send_json(['message_title'=> __('Please check the following:', 'rentopian-sync'), 'message_txt' => $error, 'type' => 'error'], 400);
            wp_die();
        }


        // set start date time as start delivery time and end date time as pickup start time
        rental_set_selected_delivery_pickup_start_end_times($rental_start_date, $rental_end_date, $opt_default_start_time, $opt_default_end_time, $opt_hide_time_pickers);

    } else {
        wp_send_json(['message_title'=> __('Please check the following:', 'rentopian-sync'), 'message_txt' => 'Start date is required!', 'type' => 'error'], 400);
        wp_die();
    }

    // submit button class
    $_COOKIE['rental_form_filled'] = ' rntp-form-filled';
    setcookie('rental_form_filled', ' rntp-form-filled', time() + (10800), "/", "", false);

    $skip_add_to_cart = false;
    $add_to_cart_msg_success = $add_to_cart_msg_failure = $current_url ="";
    if (isset($_POST['pid']) && $_POST['pid'] && isset($_POST['url'])) {
        $current_url = $_POST['url'].'&added_to_cart=0';
        $product_id = intval($_POST['pid']);

        if (get_post_meta($product_id, '_rental_add_ons', true)) {
            $skip_add_to_cart = true;
        }

        if (!$skip_add_to_cart) {
            $cart = WC()->cart;
            $validate = rental_validate_cart_item($product_id, 0, 1, null, false, true);
            $options_check = rental_check_selected_options_of_product($product_id);
            if ($validate == 'success' && $options_check) {
                // $cart->add_to_cart($product_id, 1, $product_variant_id);
                $current_url = $_POST['url'].'&added_to_cart=1';
                $cart->add_to_cart($product_id, 1, 0);
                calculate_cart_totals($cart);
                // $cart->calculate_totals();
                $add_to_cart_msg_success = wc_add_to_cart_message([$product_id => 1], true, true);
            } else {
                if (!$options_check) {
                    $add_to_cart_msg_failure = 'Please review the options before adding to cart.';
                } else {
                    $add_to_cart_msg_failure = $validate;
                }
            }
        }
    }

    $rental_unavailable_items_opt = get_option('rental_unavailable_items');

    wp_send_json([
        "current_url" => $current_url,
        "shop_page_url" => get_permalink(wc_get_page_id('shop')),
        "data" => $rental_unavailable_items_opt && is_array($rental_unavailable_items_opt) ? $rental_unavailable_items_opt : '',
        "add_to_cart_msg_success" => $add_to_cart_msg_success,
        "add_to_cart_msg_failure" => $add_to_cart_msg_failure,
        "message" => 'success'
    ], 200);
    wp_die();
}

function wp_ajax_rental_get_date_form() {
    header('Content-Type: text/html; charset=UTF-8');
    include_once('components/rental_date_form.php');
    wp_die();
}

function wp_ajax_rental_collect_hourly_product_data() {
    if (isset($_POST['product_id']) && isset($_POST['type'])) {

        if ($_POST['type'] == "rental_by_interval") {
            $session_name = $_POST['product_id']."_rental_by_interval";
        } else if ($_POST['type'] == "rental_by_slot") {
            $session_name = $_POST['product_id']."_rental_by_slot";
        }

        $rental_hourly_opt = get_option($session_name);
        if ($rental_hourly_opt !== false) {
            // update
            
            $session_name = $session_name."_updated";

            $_POST['active'] = 0;
            update_option($session_name, $_POST);

        } else {
            // create
            $_POST['active'] = 0;
            update_option($session_name, $_POST);
        }

        wp_send_json("success!");
        wp_die();
    }
}


function wp_ajax_rental_get_hourly_product_variation_id() {
    if (isset($_POST['var_id'])) {
        $product_id = intval($_POST['var_id']);

        $rental_by_interval_product = (bool) get_post_meta($product_id, '_rental_by_interval', true);
        $rental_by_slot_product = (bool) get_post_meta($product_id, '_rental_by_slot', true);

        // getting main division working hours
        $divisions = get_option("rental_divisions");
        $main_division_working_days = [];
        $week_days = [1,2,3,4,5,6,7];
        // can change it to work with product division work day-hours
        foreach ($divisions as $division) {
            if (get_option('rental_select_division') && isset($_COOKIE['rental_division_id']) && !empty($_COOKIE['rental_division_id'])) {
                if ( is_array($divisions) && count($divisions) > 1 && ($_COOKIE['rental_division_id'] == $division->id)) {
                    // getting selected division work hours
                    $main_division_working_days = $division->working_hours;
                }
            } else {
                // default : getting main division work hours
                if ($division->main_division) {
                    $main_division_working_days = $division->working_hours;
                }
            }
        }

        $main_division_working_days_diff=[];
        if (!empty($main_division_working_days)) {
            foreach($main_division_working_days as $work_day) {
                if (in_array($work_day->week_day, $week_days)) {
                    $main_division_working_days_diff[] = $work_day->week_day;
                }
            }
        }
        // $disabled_working_days = !empty($main_division_working_days_diff) ? json_encode(array_values(array_diff($week_days,$main_division_working_days_diff))) : json_encode([]);
        $disabled_working_days = !empty($main_division_working_days_diff) ? array_values(array_diff($week_days,$main_division_working_days_diff)) : [];

        // getting the hourly data
        $hourly_data = [];
        if ($rental_by_interval_product) {
            $hourly_data['rental_interval'] = get_post_meta($product_id, '_rental_interval', true);
            $hourly_data['rental_interval_steps'] = get_post_meta($product_id, '_rental_interval_steps', true);
            $hourly_data['rental_interval_price'] = get_post_meta($product_id, '_rental_interval_price', true);
            $hourly_data['rental_interval_sale_price'] = get_post_meta($product_id, '_rental_interval_sale_price', true);
            $hourly_data['rental_by_interval'] = true;
            $hourly_data['rental_by_slot'] = false;

        } else if ($rental_by_slot_product) {
            $hourly_data['rental_additional_hourly_price'] = get_post_meta($product_id, '_rental_additional_hourly_price', true);
            $hourly_data['rental_time_slots'] = json_decode(get_post_meta($product_id, '_rental_time_slots', true));
            $hourly_data['rental_by_interval'] = false;
            $hourly_data['rental_by_slot'] = true;

        }

        wp_send_json([
            'disabled_week_days' => $disabled_working_days
            , 'work_days' => $main_division_working_days
            , 'hourly' => $hourly_data
            , 'product_id' => $product_id
        ]);
        wp_die();
    }
}


function rental_check_selected_options() {
    $check = true;
    $once_per_order_option_ids = [];
    $once_per_order_option_ids_of_sets = [];
    foreach (WC()->cart->get_cart() as $cart_item) {
        $product_id = $cart_item['variation_id'] ? $cart_item['variation_id'] : $cart_item['product_id'];
        $options = [];
        $is_set = false;
        if (get_post_meta($product_id, '_rental_is_set', true)) {
            $options = get_set_options($product_id);
            $is_set = true;
        } else {
            if (!isset($cart_item['rental_set_id'])) {
                // not a set's item
                $options = get_product_options($product_id);    
            }
        }
        
        if (!empty($options)) {
            foreach($options as $option) {
                // collecting once per order option ids related to cart products
                if ($option["once_per_order"] == 1) {
                    if ($is_set) {
                        $once_per_order_option_ids_of_sets[] = $option["id"];
                    } else {
                        $once_per_order_option_ids[] = $option["id"];
                    }
                    
                }
            }

            foreach($options as $option) {
                if ($option["once_per_order"] == 1) {
                    $check = true;
                    continue;
                } else {

                    // $rental_product_options_valuables = get_option('rental_product_options_valuables', []);
                    $rental_product_options_valuables = get_rental_session_data('rental_product_options_valuables', []);

                    if (
                        !isset($rental_product_options_valuables[$product_id][$option["id"]])
                        || $rental_product_options_valuables[$product_id][$option["id"]]["value_id"] == -1
                    ) {
                        $check = false;
                        break;
                    }
                }
            }
        }
    }

    if ($check) {
        if ($once_per_order_option_ids) {
            // check order options of products
            foreach(array_unique($once_per_order_option_ids) as $option_id) {

                // $rental_order_selected_options_opt = get_option("rental_order_selected_options", []);
                $rental_order_selected_options_opt = get_rental_session_data('rental_order_selected_options', []);
                
                if (
                    !isset($rental_order_selected_options_opt[$option_id])
                    || $rental_order_selected_options_opt[$option_id]["selected_value_id"] == -1
                ) {
                    $check = false;
                    break;
                }
            }
        }

        if ($once_per_order_option_ids_of_sets) {
            // check order options of sets
            foreach(array_unique($once_per_order_option_ids_of_sets) as $option_id) {

                $rental_order_selected_options_of_sets = get_rental_session_data('rental_order_selected_options_of_sets', []);
                
                if (
                    !isset($rental_order_selected_options_of_sets[$option_id])
                    || $rental_order_selected_options_of_sets[$option_id]["selected_value_id"] == -1
                ) {
                    $check = false;
                    break;
                }
            }
        }
    }
    return ["check" => $check, "url" => wc_get_cart_url()."?rntp_opt_err"];
} 

function wp_ajax_rental_get_all_options_of_cart_products() {
    $options_all = [];
    foreach (WC()->cart->get_cart() as $cart_item) {
        $product_id = $cart_item['variation_id'] ? $cart_item['variation_id'] : $cart_item['product_id'];
        $options = [];
        if (get_post_meta($product_id, '_rental_is_set', true)) {
            $options = get_set_options($product_id);

        } else {
            if (!isset($cart_item['rental_set_id'])) {
                // not a set's item
                $options = get_product_options($product_id);
            }
        }
        
        if (!empty($options)) {
            foreach($options as $option) {
                array_unshift($option["option_values"], [
                    "id" => -1,
                    "is_default" => 0,
                    "option_id" => 0,
                    "price" => -1,
                    "title" => "Please select an option",
                ]);

                // $rental_product_options_valuables = get_option('rental_product_options_valuables', []);
                $rental_product_options_valuables = get_rental_session_data('rental_product_options_valuables', []);
                if (
                    isset($rental_product_options_valuables[$product_id][$option["id"]])
                    && $rental_product_options_valuables[$product_id][$option["id"]]["value_id"] != -1
                ) {
                    $options_all[] = [
                        "key" => $cart_item["key"],
                        "product_id" => $product_id,
                        "option_id" => $option["id"],
                        "option_title" => $option["title"],
                        "option_values" => $option["option_values"],
                        "selected_value_id" => $rental_product_options_valuables[$product_id][$option["id"]]["value_id"],
                        "is_selected" => 1,
                        "once_per_order" => $option["once_per_order"] == 1 ? 1 : 0,
                        "currency" => get_woocommerce_currency_symbol()
                    ];
                } else {
                    $options_all[] = [
                        "key" => $cart_item["key"],
                        "product_id" => $product_id,
                        "option_id" => $option["id"],
                        "option_title" => $option["title"],
                        "option_values" => $option["option_values"],
                        "selected_value_id" => 0,
                        "is_selected" => 0,
                        "once_per_order" => $option["once_per_order"] == 1 ? 1 : 0,
                        "currency" => get_woocommerce_currency_symbol()
                    ];
                }
            }
        }
    }
    wp_send_json($options_all);
    wp_die();
}

// must be modified
function wp_ajax_rental_get_all_options_of_product() {

    if (isset($_POST["product_id"])) {

        $options_all = [];
        $product_id = intval($_POST["product_id"]);
        $options = [];
        $is_set = false;

        if (isset($_POST["is_set"]) && intval($_POST["is_set"]) === 1) {
            $is_set = true;
            $options = get_set_options($product_id);
        } else {
            $options = get_product_options($product_id);
        }
        
        if ($options) {

            $options_session_name = $product_id."_selected_options";
            if ($is_set) {
                $options_session_name = $product_id."_selected_options_of_set";
            }

            foreach($options as $option) {
                
                array_unshift($option["option_values"], [
                    "id" => -1,
                    "is_default" => 0,
                    "option_id" => 0,
                    "price" => -1,
                    "title" => "Please select an option",
                ]);

                $item_selected_option = get_rental_session_data($options_session_name, []);

                if (
                    isset($item_selected_option[$option["id"]])
                    && $item_selected_option[$option["id"]]["selected_value_id"] != -1
                ) {

                    $options_all[] = [
                        "product_id" => $product_id,
                        "option_id" => $option["id"],
                        "option_title" => $option["title"],
                        "option_values" => $option["option_values"],
                        "selected_value_id" => $item_selected_option[$option["id"]]["selected_value_id"],
                        "is_selected" => 1,
                        "once_per_order" => $option["once_per_order"] == 1 ? 1 : 0,
                        "currency" => get_woocommerce_currency_symbol(),
                    ];
                        
                } else {

                    // if a default value exists, select it
                    foreach($option["option_values"] as $option_value) {
                        
                        if (
                            $option_value["is_default"] == 1
                            && !isset($item_selected_option[$option["id"]])
                        ) {


                            $item_selected_option[$option["id"]] = [
                                'selected_value_id' => $option_value["id"]
                                , 'price' => $option_value["price"]
                            ];
                        }
                    }

                    set_rental_session_data($options_session_name, $item_selected_option);
                   
                    $options_all[] = [
                        "product_id" => $product_id,
                        "option_id" => $option["id"],
                        "option_title" => $option["title"],
                        "option_values" => $option["option_values"],
                        "selected_value_id" => 0,
                        "is_selected" => 0,
                        "once_per_order" => $option["once_per_order"] == 1 ? 1 : 0,
                        "currency" => get_woocommerce_currency_symbol()
                    ];
                }
            }
        }
        wp_send_json($options_all);

    }
    wp_die();
}

function wp_ajax_rental_check_selected_options_of_product() {

    if (isset($_POST["product_id"])) {
        $product_id = intval($_POST["product_id"]); 
        $check = true;
        $options = [];

        $options_session_name = $product_id."_selected_options";

        if (isset($_POST["is_set"]) && intval($_POST["is_set"]) === 1) {
            $options = get_set_options($product_id);
            $options_session_name = $product_id."_selected_options_of_set";
        } else {
            if (!isset($cart_item['rental_set_id'])) {
                // not a set's item
                $options = get_product_options($product_id);
            }
            
        }
        
        if ($options) {

            // $item_selected_option = get_option($options_session_name, []);
            $item_selected_option = get_rental_session_data($options_session_name, []);

            foreach($options as $option) {
                // check once per order selection
                if ($option["once_per_order"] == 1) {
                    $check = true;
                    break;
                } else {

                    if (
                        !isset($item_selected_option[$option["id"]])
                        || $item_selected_option[$option["id"]]["selected_value_id"] == -1
                    ) {
                        $check = false;
                        break;
                    }

                }
            }
        }
    }
    wp_send_json(["check" => $check]);
    wp_die();
}

function rental_check_selected_options_of_product($product_id) {
    if (isset($product_id)) {
        $product_id = intval($product_id); 
        $check = true;
        $options = [];

        $options_session_name = $product_id."_selected_options";

        if (isset($_POST["is_set"]) && intval($_POST["is_set"]) === 1 || get_post_meta($product_id, '_rental_is_set', true)) {
            $options = get_set_options($product_id);
            $options_session_name = $product_id."_selected_options_of_set";
        } else {
            $options = get_product_options($product_id);
        }
        
        if ($options) {

            // $item_selected_option = get_option($options_session_name, []);
            $item_selected_option = get_rental_session_data($options_session_name, []);

            foreach($options as $option) {
                // check once per order selection
                if ($option["once_per_order"] == 1) {
                    $check = true;
                    break;
                } else {

                    if (
                        !isset($item_selected_option[$option["id"]])
                        || $item_selected_option[$option["id"]]["selected_value_id"] == -1
                    ) {
                        $check = false;
                        break;
                    }

                }
            }
        }
    }
    return $check;
}

function wp_ajax_rental_check_selected_options() {
    $check = true;
    $once_per_order_option_ids = [];
    $once_per_order_option_ids_of_sets = [];

    foreach (WC()->cart->get_cart() as $cart_item) {

        $product_id = $cart_item['variation_id'] ? $cart_item['variation_id'] : $cart_item['product_id'];
        
        $options = [];
        $is_set = false;
        if (get_post_meta($product_id, '_rental_is_set', true)) {
            $options = get_set_options($product_id);
            $is_set = true;
        } else {
            if (!isset($cart_item['rental_set_id'])) {
                // not a set's item
                $options = get_product_options($product_id);
            }
        }

        if (!empty($options)) {
            foreach($options as $option) {
                // collecting once per order option ids related to cart products
                if ($option["once_per_order"] == 1) {
                    if ($is_set) {
                        $once_per_order_option_ids_of_sets[] = $option["id"];
                    } else {
                        $once_per_order_option_ids[] = $option["id"];
                    }
                    
                }
            }

            // $rental_product_options_valuables = get_option('rental_product_options_valuables', []);
            $rental_product_options_valuables = get_rental_session_data('rental_product_options_valuables', []);

            foreach($options as $option) {
                if ($option["once_per_order"] == 1) {
                    $check = true;
                    continue;
                } else {

                    if (
                        !isset($rental_product_options_valuables[$product_id][$option["id"]])
                        || $rental_product_options_valuables[$product_id][$option["id"]]["value_id"] == -1
                    ) {
                        $check = false;
                        break;
                    }
                }
            }
        }
    }

    if ($check) {
        if ($once_per_order_option_ids) {

            // $rental_order_selected_options_opt = get_option("rental_order_selected_options", []);
            $rental_order_selected_options_opt = get_rental_session_data('rental_order_selected_options', []);

            // check order options
            foreach(array_unique($once_per_order_option_ids) as $key => $option_id) {

                if (
                    !isset($rental_order_selected_options_opt[$option_id])
                    || $rental_order_selected_options_opt[$option_id]["selected_value_id"] == -1
                ) {
                    $check = false;
                    break;
                }
            }
        }

        if ($once_per_order_option_ids_of_sets) {

            // $rental_order_selected_options_of_sets = get_option('rental_order_selected_options_of_sets', []);
            $rental_order_selected_options_of_sets = get_rental_session_data('rental_order_selected_options_of_sets', []);
            
            // check order options of sets
            foreach(array_unique($once_per_order_option_ids_of_sets) as $option_id) {

                if (
                    !isset($rental_order_selected_options_of_sets[$option_id])
                    || $rental_order_selected_options_of_sets[$option_id]["selected_value_id"] == -1
                ) {
                    $check = false;
                    break;
                }
            }
        }
    }
    wp_send_json(["check" => $check, "url" => wc_get_checkout_url(), "url_cart" => wc_get_cart_url()."?rntp_opt_err"]);
    wp_die();
}   

function calculate_cart_totals($cart_instance = '') {
    if (get_option('rental_synchronized_product_type') == "hourly") {
        $product_options_valuables = [];
        $subtotal = 0;
        $subtotalOrderOption = 0;
        // hourly products (rental by interval/time slot)
        foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
            $product_id = $cart_item['variation_id'] ? $cart_item['variation_id'] : $cart_item['product_id'];
            $session_name_interval = $product_id."_rental_by_interval";
            $session_name_slot = $product_id."_rental_by_slot";
            $session_name_interval_removed = $product_id."_rental_by_interval_removed";
            $session_name_slot_removed = $product_id."_rental_by_slot_removed";

            $rental_by_interval_opt = get_option($session_name_interval);
            $rental_by_slot_opt = get_option($session_name_slot);

            $rental_by_interval_removed_opt = get_option($session_name_interval_removed);
            $rental_by_slot_removed_opt = get_option($session_name_slot_removed);


            $price = 0;
            // calculate price with product options additional cost (if exists)
            $options = get_product_options($product_id);
            if (!empty($options)) {
                foreach($options as $option) {
                    $value_price = 0;
                    // check once per order options

                    // $rental_order_selected_options_opt = get_option("rental_order_selected_options", []);
                    $rental_order_selected_options_opt = get_rental_session_data('rental_order_selected_options', []);

                    if (isset($rental_order_selected_options_opt[$option["id"]])) {
                        $subtotalOrderOption += $rental_order_selected_options_opt[$option["id"]]["price"] >= 0 ? $rental_order_selected_options_opt[$option["id"]]["price"] : 0;
                        continue;
                    } 

                    foreach($option["option_values"] as $key => $value) {

                        $rental_product_selected_options = get_option($product_id."_selected_options");

                        if ($rental_product_selected_options !== false && isset($rental_product_selected_options[$option["id"]]["price"])
                        ) {

                            $value_price = $rental_product_selected_options[$option["id"]]["price"];
                            $product_options_valuables[$product_id][$option["id"]] = [
                                'value_id' => $rental_product_selected_options[$option["id"]]["selected_value_id"],
                                'price' => $value_price,
                            ];

                        } else {

                            if ($value['is_default'] == 1) {
                                
                                $value_price = $value['price'];
                                $product_options_valuables[$product_id][$option["id"]] = [
                                    'value_id' => $value["id"],
                                    'price' => $value_price,
                                ];
                            }
                        }
                    }
                    $price += $value_price; // sum options price
                }
            }

            
            if (
                $rental_by_interval_opt !== false
                && $rental_by_interval_opt
                && $rental_by_interval_opt['active'] == 1 
            ) {

                // $rental_product_price_total_opt = get_option('rental_product_price_total', []);
                $rental_product_price_total_opt = get_rental_session_data('rental_product_price_total', []);

                // intervals total price
                $price = $rental_by_interval_opt['total'] + $price; // add option price to rental price
                
                $rental_product_price_total_opt[$product_id] = $cart_item["quantity"] * $price;
                // update_option('rental_product_price_total', $rental_product_price_total_opt);
                set_rental_session_data('rental_product_price_total', $rental_product_price_total_opt);
                
                $subtotal += ($cart_item["quantity"] * $price);
                // intervals
                $cart_item['data']->set_price(format_value_to_fixed_precision($price, 2));
            } 

            
            if (
                $rental_by_interval_removed_opt !== false
                && $rental_by_interval_removed_opt
                && $rental_by_interval_removed_opt['active'] == 1 
            ) {
                // removed intervals restore
                $cart_item['data']->set_price($rental_by_interval_removed_opt['total']);

                $rental_by_interval_opt = $rental_by_interval_removed_opt;
                update_option($session_name_interval, $rental_by_interval_opt);

                delete_option($rental_by_interval_removed_opt);
            }
            
            
            if (
                $rental_by_slot_opt !== false
                && $rental_by_slot_opt
                && $rental_by_slot_opt['active'] == 1
            ) {

                // $rental_product_price_total_opt = get_option('rental_product_price_total', []);
                $rental_product_price_total_opt = get_rental_session_data('rental_product_price_total', []);

                // time slots total price
                $price = $rental_by_slot_opt['total'] + $price; // add option price to rental price
                
                $rental_product_price_total_opt[$product_id] = $cart_item["quantity"] * $price;
                // update_option('rental_product_price_total', $rental_product_price_total_opt);
                set_rental_session_data('rental_product_price_total', $rental_product_price_total_opt);
                
                $subtotal += ($cart_item["quantity"] * $price);
                // time slots
                $cart_item['data']->set_price(format_value_to_fixed_precision($price, 2));

            }

            if (
                $rental_by_slot_removed_opt !== false
                && $rental_by_slot_removed_opt
                && $rental_by_slot_removed_opt['active'] == 1
            ) {
                // removed time slots restore

                $cart_item['data']->set_price( $rental_by_slot_removed_opt['total']);

                $rental_by_slot_opt = $rental_by_slot_removed_opt;
                update_option($session_name_slot, $rental_by_slot_removed_opt);

                delete_option($session_name_slot_removed);
            } 
        }
        if ($subtotalOrderOption) {
            $subtotal = $subtotal + $subtotalOrderOption;
        }

        set_rental_session_data('rental_product_subtotal', format_value_to_fixed_precision($subtotal, 2));
        // update_option('rental_product_subtotal' . get_new_unique_id(), format_value_to_fixed_precision($subtotal, 2));

        // update_option('rental_product_options_valuables', $product_options_valuables);
        set_rental_session_data('rental_product_options_valuables', $product_options_valuables);
        
        set_hourly_start_end_date();

    } else {

        if (get_option('rental_dates_on_checkout', 0) == 1 && get_option('rental_allow_overbook', 0) == 1) {
            // if we have allow overbook and rental dates on checkout page
            rental_dates_on_checkout_page_option_effect();
        }

        // daily products (rental by day)
        if (isset($_COOKIE['rental_start_date']) && $_COOKIE['rental_start_date'] && isset($_COOKIE['rental_zip']) && $_COOKIE['rental_zip']) {
            $product_options_valuables = [];
            $subtotal = 0;
            $subtotalOrderOption = 0;
            $order_selected_options_already_calculated = [];
            $order_selected_options_of_sets_already_calculated = [];
            $_cart = WC()->cart;
            foreach ($_cart->get_cart() as $cart_item_key => $cart_item) {


                $price = format_value_to_fixed_precision(rental_calculate_cart_item_price($cart_item),2);
                $product_id = $cart_item['variation_id'] ? $cart_item['variation_id'] : $cart_item['product_id'];

                // if (rental_check_product_availability($product_id) == 0) {
                //     $_cart->remove_cart_item($cart_item_key);
                //     continue;
                // }

                // set item related (child)
                if (
                    isset($cart_item['rental_add_on_of']) 
                    && isset($cart_item['set_id']) 
                    && $cart_item['set_id']
                    && $cart_item['rental_add_on_of']
                    // && $cart_item['variation_id']
                ) {

                    $item_based_total = get_post_meta($cart_item['set_id'], '_rental_item_based_total', true);

                    // calculate set total price based on each item's price
                    if ($item_based_total) { 

                        $price = rental_calculate_rental_item_price($cart_item['variation_id'] ? $cart_item['variation_id'] : $cart_item['product_id']);
                        
                        if ($cart_item['rental_add_on_price']) {
                            $price = rental_calculate_rental_item_price($cart_item['variation_id'] ? $cart_item['variation_id'] : $cart_item['product_id'], $cart_item['rental_add_on_price']);
                        }
                    }
                }

                $options = [];
                $options_session_name = "";
                $is_set = false;
                // $set_items = [];
                if (get_post_meta($product_id, '_rental_is_set', true)) {
                    $is_set = true;

                    $options = get_set_options($product_id);
                    $options_session_name = $product_id."_selected_options_of_set";
                    

                } else {
                    if (!isset($cart_item['rental_set_id'])) {
                        // not a set's item
                        $options = get_product_options($product_id);
                        $options_session_name = $product_id."_selected_options";
                    }
                    
                }



                // calculate price with product or set options additional cost (if exists)
                if (!empty($options)) {
                    foreach($options as $option) {
                        $value_price = 0;

                        $rental_order_selected_options_opt = get_rental_session_data('rental_order_selected_options', []);

                        // check once per order options of products
                        if (isset($rental_order_selected_options_opt[$option["id"]]) && !$is_set) {
                            if (!isset($order_selected_options_already_calculated[$option["id"]])
                                && !isset($order_selected_options_already_calculated[$option["id"]]["price"])
                                && !isset($order_selected_options_already_calculated[$option["id"]]["selected_value_id"])
                            ) {
                                
                                $subtotalOrderOption += $rental_order_selected_options_opt[$option["id"]]["price"] >= 0 ? $rental_order_selected_options_opt[$option["id"]]["price"] : 0;
                                $order_selected_options_already_calculated[$option["id"]] = [
                                    "price" => $rental_order_selected_options_opt[$option["id"]]["price"],
                                    "selected_value_id" => $rental_order_selected_options_opt[$option["id"]]["selected_value_id"],
                                ];
                            }
                            continue;
                        } 

                        $rental_order_selected_options_of_sets = get_rental_session_data('rental_order_selected_options_of_sets', []);

                        // check once per order options of sets
                        if (isset($rental_order_selected_options_of_sets[$option["id"]])) {
                            if (!isset($order_selected_options_of_sets_already_calculated[$option["id"]])
                                && !isset($order_selected_options_of_sets_already_calculated[$option["id"]]["price"])
                                && !isset($order_selected_options_of_sets_already_calculated[$option["id"]]["selected_value_id"])
                            ) {
                                
                                $subtotalOrderOption += $rental_order_selected_options_of_sets[$option["id"]]["price"] >= 0 ? $rental_order_selected_options_of_sets[$option["id"]]["price"] : 0;
                                
                                $order_selected_options_of_sets_already_calculated[$option["id"]] = [
                                    "price" => $rental_order_selected_options_of_sets[$option["id"]]["price"],
                                    "selected_value_id" => $rental_order_selected_options_of_sets[$option["id"]]["selected_value_id"],
                                ];
                            }
                            continue;
                        } 


                        $item_selected_option = get_rental_session_data($options_session_name, []);

                        foreach($option["option_values"] as $key => $value) {
                            
                            if ( isset($item_selected_option[$option["id"]]["price"]) ) {

                                $value_price = $item_selected_option[$option["id"]]["price"];
                                $product_options_valuables[$product_id][$option["id"]] = [
                                    'value_id' => $item_selected_option[$option["id"]]["selected_value_id"],
                                    'price' => $value_price,
                                ];

                            } else {

                                if ($value['is_default'] == 1) {
                                    $value_price = $value['price'];
                                    $product_options_valuables[$product_id][$option["id"]] = [
                                        'value_id' => $value["id"],
                                        'price' => $value_price,
                                    ];
                                }
                            }
                        }
                        
                        $price += $value_price; // add option price to rental price
                    }
                }


                $rental_product_price_total_opt = get_rental_session_data('rental_product_price_total', []);

                $rental_product_price_total_opt[$product_id] = $cart_item["quantity"] * $price;
                set_rental_session_data('rental_product_price_total', $rental_product_price_total_opt);

                $subtotal += ($cart_item["quantity"] * $price);
                $cart_item['data']->set_price(format_value_to_fixed_precision($price, 2));
            }
            if ($subtotalOrderOption) {
                $subtotal = $subtotal + $subtotalOrderOption;
            }

            set_rental_session_data('rental_product_subtotal', format_value_to_fixed_precision($subtotal, 2));
            set_rental_session_data('rental_product_options_valuables', $product_options_valuables);
        }

    }
}

function wp_ajax_rental_update_product_option() {
    if (
        isset($_POST["product_id"]) 
        && isset($_POST["option_id"]) 
        && isset($_POST["value_id"])
        && isset($_POST["price"])
    ) {
        $product_id = intval($_POST["product_id"]);
        $option_id = intval($_POST["option_id"]);
        $value_id = intval($_POST["value_id"]);
        $price = $_POST["price"];

        $options_session_name = $product_id."_selected_options";
        if (isset($_POST["is_set"]) && intval($_POST["is_set"]) === 1 || get_post_meta($product_id, '_rental_is_set', true) ) {
            $options_session_name = $product_id."_selected_options_of_set";
        }

        // $item_selected_option = get_option($options_session_name, []);
        $item_selected_option = get_rental_session_data($options_session_name, []);

        $item_selected_option[$option_id] = [
            'selected_value_id' => $value_id
            , 'price' => $price
        ];

        // update_option($options_session_name, $item_selected_option);
        set_rental_session_data($options_session_name, $item_selected_option);


        if (!isset($_POST["single_product"])) {
            // in cart product option update
            
            calculate_cart_totals('');

            $fees = rental_calculate_order_total();
            $security_deposit_updated = 0;
            $security_deposit_title = '';
            if (get_option('rental_allow_to_pay_security_deposit') && !empty($security_deposit = rental_get_security_deposit())) {
                $security_deposit_updated = $fees['security_deposit_fee'];
                $security_deposit_title = $security_deposit['title'];
            }
    
            $tax_value = $is_auto_tax = 0;
            $tax_title = '';
            // if (get_option('rental_combine_shipping_tax')) {
            $delivery_settings = rental_get_delivery_settings();
            if ($delivery_settings && $delivery_settings['enable_combined_shipping_tax_for_website']) {
                $tax_value = $fees['shipping_tax'];
            } 
                        
            if ($tax_value && !isset($fees['is_auto_tax'])) {
                $tax_value += $fees['rental_tax'] + $fees['sale_tax'];
                $tax_title = get_option('rental_tax_text')? : __('Tax', 'rentopian-sync');
            }
            

            $custom_tax_label = get_option('rental_tax_text');
            if (isset($fees['is_auto_tax']) && $fees['is_auto_tax'] == 1 && isset($fees['auto_tax'])) {

                $is_auto_tax = 1;
                $tax_value += $fees['auto_tax'];
                $tax_title = 'Auto '.$custom_tax_label;
                $tax_title = ($custom_tax_label == '') ? __('Auto Tax', 'rentopian-sync') : $custom_tax_label;

            }
            
    
            $damage_waiver_value = $damage_waiver_tax_value = 0;
            $damage_waiver_title = $damage_waiver_tax_title = '';
            if ($fees['damage_waiver']) {
                
                $damage_waiver_value = $fees['damage_waiver'];
                $damage_waiver_title = __('Damage Waiver', 'rentopian-sync');
                if ($fees['damage_waiver_tax']) {
                    $damage_waiver_tax_value = $fees['damage_waiver_tax'];
                    $damage_waiver_tax_title = __('Damage Waiver '.$custom_tax_label, 'rentopian-sync');
                }
               
            }
    
            if ( !empty($fees['order_fees'])) {
                foreach ($fees['order_fees'] as $key => $order_fee) {
                    $fees['order_fees'][$key]["amount"] = format_value_to_fixed_precision($order_fee['amount'], 2);
                }
            }
            
            $subtotal = get_rental_session_data('rental_product_subtotal', 0);
            // $subtotal = get_option('rental_product_subtotal' . get_new_unique_id(), 0);
            // $rental_product_price_total_opt = get_option('rental_product_price_total', []);
            $rental_product_price_total_opt = get_rental_session_data('rental_product_price_total', []);

            wp_send_json(
                [
                    'currency' => get_woocommerce_currency_symbol(), 
                    'subtotal' => format_value_to_fixed_precision($subtotal ,2),
                    'total' => format_value_to_fixed_precision( rental_calculate_order_total()['total'], 2),
                    'price_total' => format_value_to_fixed_precision($rental_product_price_total_opt[$product_id], 2),
                    'security_deposit_value' => format_value_to_fixed_precision($security_deposit_updated, 2),
                    'security_deposit_title' => $security_deposit_title,
                    'tax_value' => format_value_to_fixed_precision($tax_value, 2),
                    'tax_title' => $tax_title,
                    'is_auto_tax' => $is_auto_tax,
                    'damage_waiver_value' => format_value_to_fixed_precision($damage_waiver_value, 2),
                    'damage_waiver_title' => $damage_waiver_title,
                    'damage_waiver_tax_value' => format_value_to_fixed_precision($damage_waiver_tax_value, 2),
                    'damage_waiver_tax_title' => $damage_waiver_tax_title,
                    'auto_applied_fees' => $fees['order_fees'],
                    'rush_fee' => $fees['rush_fee'],
                ]
            );

        } else {

            // single product option update
            wp_send_json("success");
        }
        
    }
    wp_die();
}

function wp_ajax_rental_update_order_option() {
    if (
        isset($_POST["option_id"]) 
        && isset($_POST["value_id"])
        && isset($_POST["price"])
    ) {

        // $rental_order_selected_options = get_option("rental_order_selected_options", []);
        $rental_order_selected_options = get_rental_session_data('rental_order_selected_options', []);

        $option_id = intval($_POST["option_id"]);
        $value_id = intval($_POST["value_id"]);
        $price = $_POST["price"];

        $rental_order_selected_options[$option_id] = [
            'selected_value_id' => $value_id,
            'price' => $price
        ];

        // Serialize the updated options and update the option in the database
        // update_option("rental_order_selected_options", $rental_order_selected_options);
        set_rental_session_data("rental_order_selected_options", $rental_order_selected_options);

        calculate_cart_totals('');

        $fees = rental_calculate_order_total();
        $security_deposit_updated = 0;
        $security_deposit_title = '';
        if (get_option('rental_allow_to_pay_security_deposit') && !empty($security_deposit = rental_get_security_deposit())) {
            $security_deposit_updated = $fees['security_deposit_fee'];
            $security_deposit_title = $security_deposit['title'];
        }

        $tax_value = 0;
        // if (get_option('rental_combine_shipping_tax')) {
        $delivery_settings = rental_get_delivery_settings();
        if ($delivery_settings && $delivery_settings['enable_combined_shipping_tax_for_website']) {
            $tax_value = $fees['shipping_tax'];
        } 
        $tax_value += $fees['rental_tax'] + $fees['sale_tax'];
        $tax_title = get_option('rental_tax_text')?: __('Tax', 'rentopian-sync');

        $damage_waiver_value = $damage_waiver_tax_value = 0;
        $damage_waiver_title = $damage_waiver_tax_title = '';
        if ($fees['damage_waiver']) {
            $damage_waiver_value = $fees['damage_waiver'];
            $damage_waiver_title = __('Damage Waiver', 'rentopian-sync');
            if ($fees['damage_waiver_tax']) {
                $damage_waiver_tax_value = $fees['damage_waiver_tax'];
                $damage_waiver_tax_title = __('Damage Waiver Tax', 'rentopian-sync');
            }
            
        }

        $rush_fee_value = $rush_fee_title = "";
        if ($fees['rush_fee']) {
            $rush_fee_value = $fees['rush_fee'];
            $rush_fee_title = __('Rush Fee', 'rentopian-sync');
        }

        if ( !empty($fees['order_fees'])) {
            foreach ($fees['order_fees'] as $key => $order_fee) {
                $fees['order_fees'][$key]["amount"] = format_value_to_fixed_precision($order_fee['amount'], 2);
            }
        }
        
        $subtotal = get_rental_session_data('rental_product_subtotal', 0);
        // $subtotal = get_option('rental_product_subtotal' . get_new_unique_id(), 0);
        
        // $rental_order_selected_options_total = get_option("rental_order_selected_options_total", 0);
        $rental_order_selected_options_total = get_rental_session_data("rental_order_selected_options_total", 0);

        foreach($rental_order_selected_options as $order_selected_option) {
            $rental_order_selected_options_total += $order_selected_option["price"] >= 0 ? $order_selected_option["price"] : 0;
        }

        // update_option('rental_order_selected_options_total', $rental_order_selected_options_total);
        set_rental_session_data('rental_order_selected_options_total', $rental_order_selected_options_total);

        wp_send_json(
            [
                'currency' => get_woocommerce_currency_symbol(), 
                'subtotal' => format_value_to_fixed_precision($subtotal ,2),
                'total' => format_value_to_fixed_precision( rental_calculate_order_total()['total'], 2),
                'price_total' => format_value_to_fixed_precision($rental_order_selected_options_total, 2),
                'security_deposit_value' => format_value_to_fixed_precision($security_deposit_updated, 2),
                'security_deposit_title' => $security_deposit_title,
                'tax_value' => format_value_to_fixed_precision($tax_value, 2),
                'tax_title' => $tax_title,
                'damage_waiver_value' => format_value_to_fixed_precision($damage_waiver_value, 2),
                'damage_waiver_title' => $damage_waiver_title,
                'damage_waiver_tax_value' => format_value_to_fixed_precision($damage_waiver_tax_value, 2),
                'damage_waiver_tax_title' => $damage_waiver_tax_title,
                'auto_applied_fees' => $fees['order_fees'],
                'rush_fee_value' => format_value_to_fixed_precision($rush_fee_value, 2),
                'rush_fee_title' => $rush_fee_title,
            ]
        );
    }
    wp_die();
}

function wp_ajax_rental_update_order_option_of_set() {
    if (
        isset($_POST["option_id"]) 
        && isset($_POST["value_id"])
        && isset($_POST["price"])
    ) {
        
        // $rental_order_selected_options_of_sets = get_option('rental_order_selected_options_of_sets', []);
        $rental_order_selected_options_of_sets = get_rental_session_data('rental_order_selected_options_of_sets', []);

        $rental_order_selected_options_of_sets[intval($_POST["option_id"])] = [
            'selected_value_id' => intval($_POST["value_id"])
            , 'price' => $_POST["price"]
        ];

        // update_option('rental_order_selected_options_of_sets', $rental_order_selected_options_of_sets);
        set_rental_session_data('rental_order_selected_options_of_sets', $rental_order_selected_options_of_sets);

        calculate_cart_totals('');

        $fees = rental_calculate_order_total();
        $security_deposit_updated = 0;
        $security_deposit_title = '';
        if (get_option('rental_allow_to_pay_security_deposit') && !empty($security_deposit = rental_get_security_deposit())) {
            $security_deposit_updated = $fees['security_deposit_fee'];
            $security_deposit_title = $security_deposit['title'];
        }

        $tax_value = 0;
        // if (get_option('rental_combine_shipping_tax')) {
        $delivery_settings = rental_get_delivery_settings();
        if ($delivery_settings && $delivery_settings['enable_combined_shipping_tax_for_website']) {
            $tax_value = $fees['shipping_tax'];
        } 
        $tax_value += $fees['rental_tax'] + $fees['sale_tax'];
        $tax_title = get_option('rental_tax_text')?: __('Tax', 'rentopian-sync');

        $damage_waiver_value = $damage_waiver_tax_value = 0;
        $damage_waiver_title = $damage_waiver_tax_title = '';
        if ($fees['damage_waiver']) {
            $damage_waiver_value = $fees['damage_waiver'];
            $damage_waiver_title = __('Damage Waiver', 'rentopian-sync');
            if ($fees['damage_waiver_tax']) {
                $damage_waiver_tax_value = $fees['damage_waiver_tax'];
                $damage_waiver_tax_title = __('Damage Waiver Tax', 'rentopian-sync');
            }
            
        }

        $rush_fee_value = $rush_fee_title = "";
        if ($fees['rush_fee']) {
            $rush_fee_value = $fees['rush_fee'];
            $rush_fee_title = __('Rush Fee', 'rentopian-sync');
        }

        if ( !empty($fees['order_fees'])) {
            foreach ($fees['order_fees'] as $key => $order_fee) {
                $fees['order_fees'][$key]["amount"] = format_value_to_fixed_precision($order_fee['amount'], 2);
            }
        }
        
        
        $subtotal = get_rental_session_data('rental_product_subtotal', 0);
        // $subtotal = get_option('rental_product_subtotal' . get_new_unique_id(), 0);

        // $rental_order_selected_options_total_of_sets = get_option('rental_order_selected_options_total_of_sets', 0);
        $rental_order_selected_options_total_of_sets = get_rental_session_data('rental_order_selected_options_total_of_sets', 0);

        foreach($rental_order_selected_options_of_sets as $order_selected_option) {
            $rental_order_selected_options_total_of_sets += $order_selected_option["price"] >= 0 ? $order_selected_option["price"] : 0;
        }

        // update_option('rental_order_selected_options_total_of_sets', $rental_order_selected_options_total_of_sets);
        set_rental_session_data('rental_order_selected_options_total_of_sets', $rental_order_selected_options_total_of_sets);

        wp_send_json(
            [
                'currency' => get_woocommerce_currency_symbol(), 
                'subtotal' => format_value_to_fixed_precision($subtotal ,2),
                'total' => format_value_to_fixed_precision( rental_calculate_order_total()['total'], 2),
                'price_total' => format_value_to_fixed_precision($rental_order_selected_options_total_of_sets ,2),
                'security_deposit_value' => format_value_to_fixed_precision($security_deposit_updated, 2),
                'security_deposit_title' => $security_deposit_title,
                'tax_value' => format_value_to_fixed_precision($tax_value, 2),
                'tax_title' => $tax_title,
                'damage_waiver_value' => format_value_to_fixed_precision($damage_waiver_value, 2),
                'damage_waiver_title' => $damage_waiver_title,
                'damage_waiver_tax_value' => format_value_to_fixed_precision($damage_waiver_tax_value, 2),
                'damage_waiver_tax_title' => $damage_waiver_tax_title,
                'auto_applied_fees' => $fees['order_fees'],
                'rush_fee_value' => format_value_to_fixed_precision($rush_fee_value, 2),
                'rush_fee_title' => $rush_fee_title,
            ]
        );
    }
    wp_die();
}

function check_options_existance() {
    global $woocommerce;
    foreach ($woocommerce->cart->cart_contents as $cart_item) {
        if (get_post_meta($cart_item['product_id'], '_rental_is_set', true)) {
            if (!empty(get_set_options($cart_item['product_id']))) {
                return true;
            }
        } else {
            if (!isset($cart_item['rental_set_id']) && !empty(get_product_options($cart_item['product_id']))) {
                // not a set's item
                return true;
            }
        }
    }
    return false;
}

function get_product_options($product_id) {
    $is_add_on = get_post_meta($product_id, '_rental_is_add_on', true);
    if ($is_add_on) {
        return [];
    }
    $is_set = get_post_meta($product_id, '_rental_is_set', true);
    if ($is_set) {
        return [];
    }
    global $wpdb, $rental_tables;
    $rental_product_options = $wpdb->prefix . $rental_tables["product_options"];

    // all variants
    // get variant ids' parent id(main product id which may have option relations)
    $sql = "
        SELECT 
            post_parent
        FROM 
            {$wpdb->posts}
        WHERE 
            id = %d
            AND post_type = 'product_variation'
    ";
    $product_variant = $wpdb->get_row($wpdb->prepare($sql, [$product_id]), ARRAY_A);
    
    $product_ids[] = $product_id;
    if (!empty($product_variant)) {
        $product_ids[] = $product_variant["post_parent"];
    }

    $options=[];
    $option_ids_list=[];
    $option_ids=[];
    foreach($product_ids as $pid) {
        $option_ids_list = get_post_meta($pid, '_product_options');
        // if options found, break out!
        if (isset($option_ids_list[0]) && $option_ids_list[0]) {
            break;
        }
    }
    if ($option_ids_list) {
        $option_ids = json_decode($option_ids_list[0], true);
        $placeholders = array_fill(0, count($option_ids), '%d');
        $placeholders_format = implode(', ', $placeholders);
        $sql = "
            SELECT 
                op.* 
            FROM 
                {$rental_product_options} op
            WHERE 
                id IN ({$placeholders_format})
        ";
        $options = $wpdb->get_results($wpdb->prepare($sql, $option_ids), ARRAY_A);
        if ($options) {
            foreach($options as $key=>$option) {
                $options[$key]["option_values"] = json_decode($option["option_values"], true);
            }
        }
    }
    return $options;
}

// product specific once per order options
function get_once_per_order_options_by_option_ids($option_ids) {
    if ($option_ids) {
        global $wpdb, $rental_tables;
        $rental_product_options = $wpdb->prefix . $rental_tables["product_options"];
        $placeholders = array_fill(0, count($option_ids), '%d');
        $placeholders_format = implode(', ', $placeholders);
        $sql = "
            SELECT 
                op.* 
            FROM 
                {$rental_product_options} op
            WHERE 
                once_per_order = 1
                AND id IN ({$placeholders_format})
        ";
        $options = $wpdb->get_results($wpdb->prepare($sql, $option_ids), ARRAY_A);
        if ($options) {
            foreach($options as $key=>$option) {
                $options[$key]["option_values"] = json_decode($option["option_values"], true);
            }
        }
        return $options;
    }

    return [];
}

// product specific order options
function rental_order_options_check() {
    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
        if (!isset($cart_item['rental_set_id'])) {
            // not a set's item
            $product_id = $cart_item['variation_id'] ? $cart_item['variation_id'] : $cart_item['product_id'];
            $options = get_product_options($product_id);
            foreach($options as $option) {
                if ($option["once_per_order"]) {
                    return true;
                }
            }
        }
    }
    return false;
}
// product specific order options
function wp_ajax_rental_get_order_options() {
    $options_all = [];
    $products_option_ids = [];
    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
        if (!isset($cart_item['rental_set_id'])) {
            // not a set's item
            $product_id = $cart_item['variation_id'] ? $cart_item['variation_id'] : $cart_item['product_id'];
            $options = get_product_options($product_id);
            if ($options) {
                foreach($options as $option) {
                    $products_option_ids[] = $option["id"];
                }
            }
        }
    }
    $products_option_ids = array_unique($products_option_ids);
    $all_options_data = get_once_per_order_options_by_option_ids($products_option_ids);

    if (!empty($all_options_data)) {
        foreach($all_options_data as $key => $option) {
            array_unshift($option["option_values"], [
                "id" => -1,
                "is_default" => 0,
                "option_id" => 0,
                "price" => -1,
                "title" => "Please select an option",
            ]);

            // $rental_order_selected_options_opt = get_option("rental_order_selected_options", []);
            $rental_order_selected_options_opt = get_rental_session_data("rental_order_selected_options", []);

            if ($rental_order_selected_options_opt && $rental_order_selected_options_opt[$option["id"]]
            ) {

                $options_all[] = [
                    "option_id" => $option["id"],
                    "option_title" => $option["title"],
                    "option_values" => $option["option_values"],
                    "selected_value_id" => $rental_order_selected_options_opt[$option["id"]]["selected_value_id"],
                    "is_selected" => 1,
                    "currency" => get_woocommerce_currency_symbol()
                ];
                        
            } else {

                // if a default value exists, select it
                $selected_option_value_id = 0;
                foreach($option["option_values"] as $option_value) {
                    if ($option_value["is_default"] == 1) {
                        $selected_option_value_id = $option_value["id"];

                        // $rental_order_selected_options = get_option("rental_order_selected_options", []);
                        $rental_order_selected_options = get_rental_session_data("rental_order_selected_options", []);

                        $rental_order_selected_options[$option["id"]] = [
                            'selected_value_id' => $selected_option_value_id,
                            'price' => $option_value["price"]
                        ];
                
                        // Serialize the updated options and update the option in the database
                        // update_option("rental_order_selected_options", $rental_order_selected_options);
                        set_rental_session_data("rental_order_selected_options", $rental_order_selected_options);
                    }
                }
                
                $options_all[] = [
                    "option_id" => $option["id"],
                    "option_title" => $option["title"],
                    "option_values" => $option["option_values"],
                    "selected_value_id" => $selected_option_value_id,
                    "is_selected" => $selected_option_value_id != 0 ? 1 : 0,
                    "currency" => get_woocommerce_currency_symbol()
                ];
            }
        }
    }
    wp_send_json($options_all);
    wp_die();
}

function wp_ajax_rental_get_order_options_effected_subtotal() {

    // if ($subtotal = get_option('rental_product_subtotal' . get_new_unique_id(), 0)) {
    if ($subtotal = get_rental_session_data('rental_product_subtotal', 0)) {
        wp_send_json([ "subtotal" => $subtotal, "currency" => get_woocommerce_currency_symbol()]);
    } else {
        wp_send_json([ "subtotal" => ""]);
    }

    wp_die();
}

function get_set_options($set_id) {
    $is_add_on = get_post_meta($set_id, '_rental_is_add_on', true);
    if ($is_add_on) {
        return [];
    }
    global $wpdb, $rental_tables;
    $rental_set_options = $wpdb->prefix . $rental_tables["set_options"];

    $options = [];
    $option_ids_list_json_encoded = get_post_meta($set_id, '_set_options', true);
    if ($option_ids_list_json_encoded) {
        $option_ids = json_decode($option_ids_list_json_encoded, true);
        $option_ids_placeholders = array_fill(0, count($option_ids), '%d');
        $option_ids_bind_format = implode(', ', $option_ids_placeholders);
        $sql = "
            SELECT 
                op.* 
            FROM 
                {$rental_set_options} op
            WHERE 
                id IN ({$option_ids_bind_format})
        ";
        $options = $wpdb->get_results($wpdb->prepare($sql, $option_ids), ARRAY_A);
        if ($options) {
            foreach($options as $key=>$option) {
                $options[$key]["option_values"] = json_decode($option["option_values"], true);
            }
        }
    }
    return $options;
}

// set specific order options
function rental_order_options_of_sets_check() {
    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
        $product_id = $cart_item['variation_id'] ? $cart_item['variation_id'] : $cart_item['product_id'];
        if (get_post_meta($product_id, '_rental_is_set', true)) {
            $options = get_set_options($product_id);
            if ($options) {
                foreach($options as $option) {
                    if ($option["once_per_order"]) {
                        return true;
                    }
                }
            }
        }
    }
    return false;
}
// set specific order options
function wp_ajax_rental_get_order_options_of_sets() {
    $options_all = [];
    $sets_option_ids = [];
    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
        $product_id = $cart_item['variation_id'] ? $cart_item['variation_id'] : $cart_item['product_id'];
        if (get_post_meta($product_id, '_rental_is_set', true)) {
            $options = get_set_options($product_id);
            if ($options) {
                foreach($options as $option) {
                    $sets_option_ids[] = $option["id"];
                }
            }
        }
    }

    $all_options_data = [];
    if ($sets_option_ids) {
        $sets_option_ids = array_unique($sets_option_ids);
        $all_options_data = get_once_per_order_set_options_by_option_ids($sets_option_ids);
    }
    if (!empty($all_options_data)) {
        foreach($all_options_data as $key => $option) {
            array_unshift($option["option_values"], [
                "id" => -1,
                "is_default" => 0,
                "option_id" => 0,
                "price" => -1,
                "title" => "Please select an option",
            ]);


            // $rental_order_selected_options_of_sets = get_option('rental_order_selected_options_of_sets', []);
            $rental_order_selected_options_of_sets = get_rental_session_data('rental_order_selected_options_of_sets', []);


            if ( isset($rental_order_selected_options_of_sets[$option["id"]]) ) {

                $options_all[] = [
                    "option_id" => $option["id"],
                    "option_title" => $option["title"],
                    "option_values" => $option["option_values"],
                    "selected_value_id" => $rental_order_selected_options_of_sets[$option["id"]]["selected_value_id"],
                    "is_selected" => 1,
                    "currency" => get_woocommerce_currency_symbol()
                ];
                        
            } else {

                // if a default value exists, select it
                $selected_option_value_id = 0;
                foreach($option["option_values"] as $option_value) {
                    if ($option_value["is_default"] == 1) {
                        $selected_option_value_id = $option_value["id"];

                        $rental_order_selected_options_of_sets[$option["id"]] = [
                            'selected_value_id' => $selected_option_value_id,
                            'price' => $option_value["price"]
                        ];

                        // update_option('rental_order_selected_options_of_sets', $rental_order_selected_options_of_sets);
                        set_rental_session_data('rental_order_selected_options_of_sets', $rental_order_selected_options_of_sets);
                    }
                }
                
                $options_all[] = [
                    "option_id" => $option["id"],
                    "option_title" => $option["title"],
                    "option_values" => $option["option_values"],
                    "selected_value_id" => $selected_option_value_id,
                    "is_selected" => $selected_option_value_id != 0 ? 1 : 0,
                    "currency" => get_woocommerce_currency_symbol()
                ];
            }
        }
    }
    wp_send_json($options_all);
    wp_die();
}

// set specific once per order options
function get_once_per_order_set_options_by_option_ids($set_option_ids) {
    if ($set_option_ids) {
        global $wpdb, $rental_tables;
        $rental_set_options = $wpdb->prefix . $rental_tables["set_options"];
        $placeholders = array_fill(0, count($set_option_ids), '%d');
        $placeholders_format = implode(', ', $placeholders);
        $sql = "
            SELECT 
                op.* 
            FROM 
                {$rental_set_options} op
            WHERE 
                once_per_order = 1
                AND id IN ({$placeholders_format})
        ";
        $options = $wpdb->get_results($wpdb->prepare($sql, $set_option_ids), ARRAY_A);
        if ($options) {
            foreach($options as $key=>$option) {
                $options[$key]["option_values"] = json_decode($option["option_values"], true);
            }
        }
        return $options;
    }

    return [];
}


function wp_ajax_rental_replace_full_address_in_checkout() {
    // $uid = get_current_user_id();

    if( get_option('rental_show_location') && isset($_COOKIE["rental_google_map_address"]) && $_COOKIE["rental_google_map_address"] && isset($_COOKIE["rental_address"]) && $_COOKIE["rental_address"]) {
        
        $decrypted_rental_address = decrypt_data($_COOKIE['rental_address'], get_option('rental_encryption_key'));

        $address = '';
        $full_address_array = explode(',', $decrypted_rental_address);
        $full_address_length = count($full_address_array);
        if ($full_address_length == 1) {
            $address = implode($full_address_array);
        }

        // $zip = '';
        // if (!get_option('rental_hide_zip') && isset($_COOKIE['rental_zip']) && $_COOKIE['rental_zip'] && $_COOKIE['rental_zip'] != 1 ) {
        //     $zip = $_COOKIE['rental_zip'];
        // }
        // wp_send_json(['user_logged_in' => 0, 'zip' => $zip, 'address' => $address]);
        wp_send_json(['zip' => '', 'address' => $address]);

    } else {

        $zip = '';
        if (!get_option('rental_hide_zip') && isset($_COOKIE['rental_zip']) && $_COOKIE['rental_zip'] ) {
            
            $decrypted_rental_zip = decrypt_data($_COOKIE['rental_zip'], get_option('rental_encryption_key'));

            if ($decrypted_rental_zip != 1) {
                $zip = $decrypted_rental_zip;
            }
            // $zip = $_COOKIE['rental_zip'];
        }
        wp_send_json(['zip' => $zip, 'address' => '']);
    }
    
    wp_die();
}


function wp_ajax_rental_replace_cart_page_textual_labels() {
    $custom_text = get_option('rental_cart_button_text');
    wp_send_json(['cart_label' => !empty($custom_text) ? $custom_text : ""]);
    wp_die();
}

function wp_ajax_rental_replace_mini_cart_textual_labels_values() {

    $custom_checkout_button_text = get_option('rental_checkout_button_text');
    $custom_checkout_label = empty($custom_checkout_button_text) ? 'Checkout' : $custom_checkout_button_text;

    $response = [
        'checkout_label' => $custom_checkout_label,
        'subtotal' => 0,
        'total' => 0,
        'currency_symbol' => get_woocommerce_currency_symbol()
    ];

    if (WC()->cart->is_empty()) {
        wp_send_json($response);
        wp_die();
    }

    calculate_cart_totals();

    $cached_totals = get_transient('user_cart_totals_' . get_current_user_id());
    if ($cached_totals) {
        $fees = $cached_totals;
    } else {
        $fees = rental_calculate_order_total();
        set_transient('user_cart_totals_' . get_current_user_id(), $fees, 60); // Cache for 60 seconds
    }
   
    // $fees = rental_calculate_order_total();
    // $subtotal = get_option('rental_product_subtotal' . get_new_unique_id(), 0);
    $subtotal = get_rental_session_data('rental_product_subtotal', 0);

    $response['subtotal'] = $subtotal;
    $response['total'] = $fees ? format_value_to_fixed_precision($fees['total'], 2)  : 0;

    wp_send_json($response);
    wp_die();
}

function rental_replace_coupon_text_label() {
    $coupon_label = get_option('rental_coupon_label_text', 'Coupon');

    wp_send_json_success([
        'coupon_label' => $coupon_label,
    ]);
}

function rental_get_invalid_coupon_response() {
    $error_msg = '';
    if (isset($_COOKIE['rental_rentpro_coupon_code_is_invalid_error']) && $_COOKIE['rental_rentpro_coupon_code_is_invalid_error']) {

        $error_msg = $_COOKIE['rental_rentpro_coupon_code_is_invalid_error'];

        unset($_COOKIE['rental_rentpro_coupon_code_is_invalid_error']);
        setcookie('rental_rentpro_coupon_code_is_invalid_error', false, time() - (31556952), "/", "", false, false);
    }

    wp_send_json_success([
        'msg' => $error_msg,
    ]);
}


function rental_check_blacklisted_client($billing_email, $billing_phone, $client_fname, $client_lname) {
    $email = rental_sanitize($billing_email);
    $phone = !empty($billing_phone) ? rental_sanitize($billing_phone) : null;
    
    try {
        $result_msg = json_decode(rental_curl('clients/blacklist-check', get_option('rental_api_key'), false, [
            'email' => $email,
            'phone' => $phone
        ]), true);

        
        if ($result_msg && isset($result_msg['message']) && $result_msg['message'] !== 'no_match_found') {

            // send email to notify admin(s)
            if (get_option('rental_client_blacklisted_notif_email')) {

                $main_admin_email = get_option('admin_email', null);
                $main_admin_new_email = get_option('new_admin_email', null);
                if ($main_admin_email) {
                    // main admin
                    $products = [];
                    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
                        $_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
                        $products[] = esc_html( $_product->get_name() );
                    }
                    if ($products) {
                        $products = implode(', ', $products);
                    }
                    
                    $full_name = "";
                    if ($client_fname) {
                        $full_name .= $client_fname;
                    }
                    if ($client_lname) {
                        $full_name .= ' '.$client_lname;
                    }
                    $phone_number_text = "";
                    if ($phone) {
                        $phone_number_text = "and phone number $phone";
                    }
                    $message = "Hello, a blacklisted client $full_name with email $email $phone_number_text tried to place an order with the following products : $products. The attempt was prevented by the website.";
                    wp_mail( sanitize_email($main_admin_email), "Blacklisted Client Activity", $message );
                    if ($main_admin_new_email && ($main_admin_new_email != $main_admin_email)) {
                        wp_mail( sanitize_email($main_admin_new_email), "Blacklisted Client Activity", $message );
                    }

                    // other admins
                    $query_part = $query_part2 = '';
                    $query_part = "AND `user`.user_email <> '$main_admin_email'";
                    if ($main_admin_new_email && ($main_admin_new_email != $main_admin_email)) {
                        $query_part2 = "AND `user`.user_email <> '$main_admin_new_email'";
                    }
                    global $wpdb;
                    $sql = "
                        SELECT 
                            `user`.user_email
                        FROM 
                            `$wpdb->users` `user` " .
                        "LEFT JOIN `$wpdb->usermeta` `meta` ON `meta`.`user_id` = `user`.`ID` AND `meta`.`meta_key` = 'wp_user_level' " .
                        "WHERE 
                            meta.meta_value = 10
                            $query_part
                            $query_part2
                    ";
                    $other_admins = $wpdb->get_results($sql, ARRAY_A);
                    if ($other_admins) {
                        foreach($other_admins as $admin_email) {
                            if ($admin_email["user_email"]) {
                                wp_mail( sanitize_email($admin_email["user_email"]), "Blacklisted Client Activity", $message );
                            }
                        }
                    }

                }
            }

            // blacklistedd client rejection message generate
            return ['message' => get_option('rental_client_blacklisted_reject_msg', 'Sorry, your request has been declined')];
        }

    } catch (Exception $e) {
        $error_msg = json_decode($e->getMessage(), true);
        return ['message' => is_array($error_msg) ? $error_msg[0] : $error_msg];
    }
}

function get_add_on_ids($rental_product_relations, $left_join_post_meta_product, $left_join_add_ons_post_meta_product) {

    if ($data = get_rental_cache('rental_addon_ids', 'rental_addon_ids_expiration_date')) {
        return $data;
    }

    global $wpdb;

    $result = [];
    $add_ons_sql = "
        select
            id
        from 
            {$rental_product_relations} product_rel
        {$left_join_post_meta_product}
        {$left_join_add_ons_post_meta_product}
        where
            pm.meta_value = 'instock'
            AND pm_add_ons.meta_value = 1
    ";
    $result = $wpdb->get_col($add_ons_sql);

    set_rental_cache($result, 'rental_addon_ids', 'rental_addon_ids_expiration_date');

    return $result ? $result : [];
}



function get_unavailable_items_sql_conditions($rental_unavailable_items, $unavailable_variant_sql, $unavailable_product_sql) {

    if ($rental_unavailable_items) {
        $unavailable_variant_ids_with_divs = !empty($rental_unavailable_items['unavailable_variant_ids_with_divs']) ? $rental_unavailable_items['unavailable_variant_ids_with_divs'] : [];
        if ($unavailable_variant_ids_with_divs) {
            foreach($unavailable_variant_ids_with_divs as $variant_id_with_div) {
                $unavailable_variant_sql .= " OR (rental_id = {$variant_id_with_div["variant_id"]} AND rental_division_id = {$variant_id_with_div["division_id"]} ) ";
            }
        }
        $unavailable_product_ids_with_divs = !empty($rental_unavailable_items['unavailable_product_ids_with_divs']) ? $rental_unavailable_items['unavailable_product_ids_with_divs'] : [];
        if ($unavailable_product_ids_with_divs) {
            foreach($unavailable_product_ids_with_divs as $product_id_with_div) {
                $unavailable_product_sql .= " OR (rental_id = {$product_id_with_div["product_id"]} AND rental_division_id = {$product_id_with_div["division_id"]} ) ";
            }
        }
    }

    return [
        'unavailable_variant_sql' => $unavailable_variant_sql,
        'unavailable_product_sql' => $unavailable_product_sql,
    ];
}

function get_unavailable_variant_ids($division_id, $unavailable_variant_sql, $rental_variant_relations, $left_join_post_meta_variant) {
    global $wpdb;

    $division_sql = '';
    if ($division_id) {
        $division_sql = " AND rental_division_id = $division_id ";
    }

    $needle = 'OR ';
    $pos = strpos($unavailable_variant_sql, $needle);
    if ($pos !== false) {
        $unavailable_variant_sql = substr_replace($unavailable_variant_sql, 'AND (', $pos, strlen($needle));
        $unavailable_variant_sql .= ')';
    }

    $sql = "
        select
            id
        from 
            {$rental_variant_relations} variant_rel
        {$left_join_post_meta_variant}
        where
            pm.meta_value = 'instock'
            $unavailable_variant_sql
            $division_sql
    ";
    $unavailable_variant_post_ids = $wpdb->get_col($sql);

    return $unavailable_variant_post_ids;
}

function get_unavailable_variant_ids_with_only_division_filter($division_id, $rental_variant_relations, $left_join_post_meta_variant) {
    global $wpdb;

    $division_id = intval($division_id);
    $division_sql = " AND rental_division_id <> $division_id ";

    $sql = "
        select
            id
        from 
            {$rental_variant_relations} variant_rel
        {$left_join_post_meta_variant}
        where
            pm.meta_value = 'instock'
            $division_sql
    ";
    $unavailable_variant_post_ids = $wpdb->get_col($sql);

    return $unavailable_variant_post_ids;
}

function get_unavailable_product_ids($division_id, $unavailable_product_sql, $rental_product_relations, $left_join_post_meta_product) {
    global $wpdb;

    $division_sql = '';
    if ($division_id) {
        $division_sql = " AND rental_division_id = $division_id ";
    }

    $needle = 'OR ';
    $pos = strpos($unavailable_product_sql, $needle);
    if ($pos !== false) {
        $unavailable_product_sql = substr_replace($unavailable_product_sql, 'AND (', $pos, strlen($needle));
        $unavailable_product_sql .= ')';
    }

    $sql = "
        select
            id
        from 
            {$rental_product_relations} product_rel
        {$left_join_post_meta_product}
        where
            pm.meta_value = 'instock'
            $unavailable_product_sql
            $division_sql
    ";
    $unavailable_product_post_ids = $wpdb->get_col($sql);

    return $unavailable_product_post_ids;
}

function get_unavailable_product_ids_with_only_division_filter($division_id, $rental_product_relations, $left_join_post_meta_product) {
    global $wpdb;

    $division_id = intval($division_id);
    $division_sql = " AND rental_division_id <> $division_id ";

    $sql = "
        select
            id
        from 
            {$rental_product_relations} product_rel
        {$left_join_post_meta_product}
        where
            pm.meta_value = 'instock'
            $division_sql
    ";
    $unavailable_product_post_ids = $wpdb->get_col($sql);

    return $unavailable_product_post_ids;
}

function get_published_products($unavailable_ids_all = []) {
    global $wpdb;

    $exclude_ids_condition = '';
    if ($unavailable_ids_all) {
        $exclude_ids_condition = " AND ID NOT IN ($unavailable_ids_all) ";
    }

    $sql = "
        select
            *
        from 
            $wpdb->posts
        where
            post_status = 'publish'
            AND post_type in ('product', 'product_variation')
            $exclude_ids_condition
    ";
    $available_ids_all = $wpdb->get_col($sql);

    return $available_ids_all;
}

function getInventoryBlockedRanges($rental_inventory_blocks, $start_date, $end_date) {
    global $wpdb;

    $sql = "
        select
            COUNT(*) 
        from 
            {$rental_inventory_blocks}
        where
            type = 1
            AND ( (%d >= start_date AND %d <= end_date) OR (%d >= start_date AND %d <= end_date) )
    ";
    $blocked_ranges = $wpdb->get_var($wpdb->prepare($sql, [$start_date, $start_date ,$end_date, $end_date]));

    return $blocked_ranges;
}

function getInventoryBlockedItems($rental_inventory_blocks, $rental_inventory_block_relations, $start_date, $end_date) {
    global $wpdb;

    $sql = "
        select
            block_rel.id as product_variant_id
        from 
            {$rental_inventory_blocks} as block
        LEFT JOIN {$rental_inventory_block_relations} as block_rel ON block_rel.block_id = block.id
        where
            type = 2
            AND ( (%d >= start_date AND %d <= end_date) OR (%d >= start_date AND %d <= end_date) )
    ";
    $blocked_product_variant_ids = $wpdb->get_col($wpdb->prepare($sql, [$start_date, $start_date ,$end_date, $end_date]));

    return $blocked_product_variant_ids;
}

function get_unavailable_product_ids_with_blocked_inventory_items_filter($rental_product_relations, $left_join_post_meta_product,
    $placeholders_format, $unavailable_product_sql, $division_sql, $bind_data) {
    global $wpdb;

    $sql = "
        select
            id
        from 
            {$rental_product_relations} product_rel
        {$left_join_post_meta_product}
        where
            id IN ({$placeholders_format})
            {$unavailable_product_sql}
            AND pm.meta_value = 'instock'
            {$division_sql}
    ";
    $unavailable_product_ids = $wpdb->get_col($wpdb->prepare($sql, $bind_data));

    return $unavailable_product_ids;
}


function get_unavailable_variant_ids_with_blocked_inventory_items_filter($rental_variant_relations, $left_join_post_meta_variant,
    $placeholders_format, $unavailable_variant_sql, $division_sql, $bind_data) {
    global $wpdb;

    $sql = "
        select
            id
        from 
            {$rental_variant_relations} variant_rel
        {$left_join_post_meta_variant}
        where
            id IN ({$placeholders_format})
            {$unavailable_variant_sql}
            AND pm.meta_value = 'instock'
            {$division_sql}
    ";
    $unavailable_variant_ids = $wpdb->get_col($wpdb->prepare($sql, $bind_data));

    return $unavailable_variant_ids;
}



// check product availability functionality
function product_variant_list_filter($rental_unavailable_items, $division_id, $array = [], $item_id = 0, $duplicate_products_filter = []) {

    try {
        global $wpdb, $rental_tables;
        $rental_product_relations = $wpdb->prefix . $rental_tables["product_relations"];
        $rental_variant_relations = $wpdb->prefix . $rental_tables["variant_relations"];
        $rental_set_relations = $wpdb->prefix . $rental_tables["set_relations"];
                
        $rental_inventory_blocks = $wpdb->prefix . $rental_tables["inventory_blocks"];
        
        $left_join_post_meta_set = "LEFT JOIN {$wpdb->postmeta} pm ON pm.post_id = set_rel.id AND pm.meta_key = '_stock_status'";
        $left_join_post_meta_set_check = "LEFT JOIN {$wpdb->postmeta} pm_set ON pm_set.post_id = set_rel.id AND pm_set.meta_key = '_rental_is_set'";

        $left_join_post_meta_product = "LEFT JOIN {$wpdb->postmeta} pm ON pm.post_id = product_rel.id AND pm.meta_key = '_stock_status'";
        $left_join_post_meta_variant = "LEFT JOIN {$wpdb->postmeta} pm ON pm.post_id = variant_rel.id AND pm.meta_key = '_stock_status'";

        $left_join_post_meta_product_duplicate = "LEFT JOIN {$wpdb->postmeta} pm2 ON pm2.post_id = product_rel.id AND pm2.meta_key = '_rental_is_duplicate'";
        $left_join_post_meta_variant_duplicate = "LEFT JOIN {$wpdb->postmeta} pm2 ON pm2.post_id = variant_rel.id AND pm2.meta_key = '_rental_is_duplicate'";
        $left_join_add_ons_post_meta_product = "LEFT JOIN {$wpdb->postmeta} pm_add_ons ON pm_add_ons.post_id = product_rel.id AND pm_add_ons.meta_key = '_rental_is_add_on'";
        
        $add_on_ids_to_exclude = get_add_on_ids($rental_product_relations, $left_join_post_meta_product, $left_join_add_ons_post_meta_product);

        $start_date = $end_date = 0;

        if ($item_id) {
            $is_set = false;
            if (get_post_meta($item_id, '_rental_is_set', true)) {
                $is_set = true;
            }
        }
        

        // inventory blocked items
        if ($wpdb->get_var("show tables like '$rental_inventory_blocks'") == $rental_inventory_blocks) {
            $rental_inventory_block_relations = $wpdb->prefix . $rental_tables["inventory_block_relations"];

            if (get_option('rental_synchronized_product_type') != "hourly") {
                // daily mode

                $decrypted_rental_start_date = "";
                if (isset($_COOKIE['rental_start_date']) && $_COOKIE['rental_start_date']) {
                    $decrypted_rental_start_date = decrypt_data($_COOKIE['rental_start_date'], get_option('rental_encryption_key'));
                }

                $decrypted_rental_end_date = "";
                if (isset($_COOKIE['rental_end_date']) && $_COOKIE['rental_end_date']) {
                    $decrypted_rental_end_date = decrypt_data($_COOKIE['rental_end_date'], get_option('rental_encryption_key'));
                }

                $start_date = $decrypted_rental_start_date ? strtotime($decrypted_rental_start_date) : 0;
                $end_date = isset($_COOKIE['rental_start_date']) && isset($_COOKIE['rental_end_date']) && $_COOKIE['rental_end_date'] ? strtotime($decrypted_rental_end_date) : $start_date;
            } 

            // else {
            //     // hourly mode
            //     $start_date = isset($_COOKIE["rental_hourly_start_date"]) && $_COOKIE["rental_hourly_start_date"] ? strtotime($_COOKIE["rental_hourly_start_date"]) : 0;
            //     $end_date = isset($_COOKIE["rental_hourly_start_date"]) && $_COOKIE["rental_hourly_end_date"] ? strtotime($_COOKIE["rental_hourly_end_date"]) : 0;
            // }

            if (empty($start_date) && !empty($item_id)) {
                return 2; // no selected date
            } 


            $blocked_ranges = getInventoryBlockedRanges($rental_inventory_blocks, $start_date, $end_date);
            if ( !($blocked_ranges > 0) ) {

                // check for specific blocked items
                $blocked_product_variant_ids = getInventoryBlockedItems($rental_inventory_blocks, $rental_inventory_block_relations, $start_date, $end_date);

                if ($blocked_product_variant_ids) {
                    $placeholders_format = implode(', ', array_fill(0, count($blocked_product_variant_ids), '%d'));
                    $division_sql = "";
                    $bind_data = $blocked_product_variant_ids;
                    if ($division_id) {
                        $division_sql = " AND rental_division_id = {$division_id} ";
                    }


                    // start/end date + zip code filter
                    $unavailable_variant_sql = $unavailable_product_sql = '';
                    if ($rental_unavailable_items) {
                        $unavailable_variant_ids_with_divs = !empty($rental_unavailable_items['unavailable_variant_ids_with_divs']) ? $rental_unavailable_items['unavailable_variant_ids_with_divs'] : [];
                        if ($unavailable_variant_ids_with_divs) {
                            foreach($unavailable_variant_ids_with_divs as $variant_id_with_div) {
                                $unavailable_variant_sql .= " OR (rental_id = {$variant_id_with_div["variant_id"]} AND rental_division_id = {$variant_id_with_div["division_id"]} ) ";
                            }
                        }
                        $unavailable_product_ids_with_divs = !empty($rental_unavailable_items['unavailable_product_ids_with_divs']) ? $rental_unavailable_items['unavailable_product_ids_with_divs'] : [];
                        if ($unavailable_product_ids_with_divs) {
                            foreach($unavailable_product_ids_with_divs as $product_id_with_div) {
                                $unavailable_product_sql .= " OR (rental_id = {$product_id_with_div["product_id"]} AND rental_division_id = {$product_id_with_div["division_id"]} ) ";
                            }
                        }
                    }


                    $unavailable_product_ids = get_unavailable_product_ids_with_blocked_inventory_items_filter($rental_product_relations, $left_join_post_meta_product,
                                                $placeholders_format, $unavailable_product_sql, $division_sql, $bind_data);
                    
                    $unavailable_variant_ids = get_unavailable_variant_ids_with_blocked_inventory_items_filter($rental_variant_relations, $left_join_post_meta_variant,
                                                $placeholders_format, $unavailable_variant_sql, $division_sql, $bind_data);
                    
                    $unavailable_ids_all = implode(',', array_merge($unavailable_product_ids, $unavailable_variant_ids, $add_on_ids_to_exclude));
                    $available_ids_all = [];


                    if (empty($duplicate_products_filter['location_based_duplicate_filter'])) {
                        if ($unavailable_ids_all) {

                            $available_ids_all = get_published_products($unavailable_ids_all);
                        }
                    }

                    // duplicate products/variants filter
                    $available_ids_duplicate_filtered = duplicate_products_filter($duplicate_products_filter, $rental_variant_relations, 
                    $left_join_post_meta_variant_duplicate, $left_join_post_meta_variant, $unavailable_ids_all,
                    $rental_product_relations, $left_join_post_meta_product_duplicate, $left_join_post_meta_product,
                    $rental_set_relations, $left_join_post_meta_set, $left_join_post_meta_set_check);

                    if ($available_ids_duplicate_filtered) {
                        $available_ids_all = $available_ids_duplicate_filtered;
                    }

                    if (!empty($item_id)) {

                        if (empty($available_ids_all)) {
                            return 1;
                        }
                        // if current product is not included in available/not blocked products, then return 0
                        if (!in_array($item_id, $available_ids_all)) {
                            return 0;
                        }

                    } else {
                        return $available_ids_all;
                    }
                    
                }
                
            } else {
                // all items must be blocked
                if (!empty($item_id)) {
                    return 0;
                } else {
                    return "";
                }
            }

        }


        // If no blocked inventory items exist check the set item availability
        if (!empty($item_id) && $is_set) {
                
            // start/end date + zip code filter
            $unavailable_set_ids = $available_set_ids = [];
            $unavailable_set_placeholders_format = $division_sql = '';
            if ($rental_unavailable_items) {
                $unavailable_set_ids = !empty($rental_unavailable_items['unavailable_sets']) ? $rental_unavailable_items['unavailable_sets'] : [];
                if ($unavailable_set_ids)
                    $unavailable_set_placeholders_format = implode(', ', array_fill(0, count($unavailable_set_ids), '%d'));
            }

            if ($unavailable_set_placeholders_format) {
                // select division mode
                $bind_data_set = $unavailable_set_ids;
                if ($division_id) {
                    $division_sql = " AND rental_division_id = $division_id ";
                }

                $sql = "
                    select
                        id
                    from 
                        {$rental_set_relations} set_rel
                    {$left_join_post_meta_set}
                    where
                        rental_id NOT IN ({$unavailable_set_placeholders_format})
                        AND pm.meta_value = 'instock'
                        $division_sql
                ";
                $available_set_ids = $wpdb->get_col($wpdb->prepare($sql, $bind_data_set));

            } else {
                // no filter - just check for specific location select option  
                $bind_data_set = $division_sql = '';
                if ($division_id) {
                    $division_sql = " AND rental_division_id = %d ";
                    $bind_data_set = $division_id;
                }

                $sql = "
                    select
                        id
                    from 
                        {$rental_set_relations} set_rel
                    {$left_join_post_meta_set}
                    where
                        pm.meta_value = 'instock'
                        $division_sql
                ";
                if ($bind_data_set) {
                    $available_set_ids = $wpdb->get_col($wpdb->prepare($sql, $bind_data_set));
                } else {
                    $available_set_ids = $wpdb->get_col($sql);
                }
            }

            if (!in_array($item_id, $available_set_ids)) {
                return 0;
            }
        }
        
        // If no blocked inventory items exist
        $unavailable_variant_sql = $unavailable_product_sql = '';
        $unavailable_items_sql_conditions = get_unavailable_items_sql_conditions($rental_unavailable_items, $unavailable_variant_sql, $unavailable_product_sql);
        if ($unavailable_items_sql_conditions) {
            $unavailable_variant_sql = $unavailable_items_sql_conditions['unavailable_variant_sql'];
            $unavailable_product_sql = $unavailable_items_sql_conditions['unavailable_product_sql'];
        }

        $unavailable_variant_post_ids = $unavailable_product_post_ids = [];
        if ($unavailable_variant_sql) {

            $unavailable_variant_post_ids = get_unavailable_variant_ids($division_id, $unavailable_variant_sql, $rental_variant_relations, $left_join_post_meta_variant);
        } else {

            // location / division filter - check for specific location/division selected option 
            if ($division_id) {

                $unavailable_variant_post_ids = get_unavailable_variant_ids_with_only_division_filter($division_id, $rental_variant_relations, $left_join_post_meta_variant);
            }
        }

       
        if ($unavailable_product_sql) {

            $unavailable_product_post_ids = get_unavailable_product_ids($division_id, $unavailable_product_sql, $rental_product_relations, $left_join_post_meta_product);
        } else {

            // location / division filter - check for specific location/division selected option 
            if ($division_id) {

                $unavailable_product_post_ids = get_unavailable_product_ids_with_only_division_filter($division_id, $rental_product_relations, $left_join_post_meta_product);
            }
        }

        $unavailable_ids_all = implode(',', array_merge($unavailable_variant_post_ids, $unavailable_product_post_ids, $add_on_ids_to_exclude));
        $available_ids_all = [];

        if (empty($duplicate_products_filter['location_based_duplicate_filter'])) {
            if ($unavailable_ids_all) {

                $available_ids_all = get_published_products($unavailable_ids_all);
            }
        }

        // duplicate products/variants filter
        $available_ids_duplicate_filtered = duplicate_products_filter($duplicate_products_filter, $rental_variant_relations, 
        $left_join_post_meta_variant_duplicate, $left_join_post_meta_variant, $unavailable_ids_all,
        $rental_product_relations, $left_join_post_meta_product_duplicate, $left_join_post_meta_product, 
        $rental_set_relations, $left_join_post_meta_set, $left_join_post_meta_set_check);

        if ($available_ids_duplicate_filtered) {
            $available_ids_all = $available_ids_duplicate_filtered;
        }

        if (!empty($item_id)) {

            if (empty($available_ids_all)) {
                return 1;
            }

            // if current product is not included in available/not blocked products, then return 0
            if (!in_array($item_id, $available_ids_all)) {
                return 0;
            }

        } else {

            return $available_ids_all;
        }
            

        if (!empty($item_id)) {
            return 1;
        }

    } catch (Throwable $th) {
        if (!empty($item_id)) {
            return 1;
        } else {
            return $array;
        }
    }
}

function duplicate_products_filter($duplicate_products_filter, $rental_variant_relations, 
    $left_join_post_meta_variant_duplicate, $left_join_post_meta_variant, $unavailable_ids_all,
    $rental_product_relations, $left_join_post_meta_product_duplicate, $left_join_post_meta_product,
    $rental_set_relations, $left_join_post_meta_set, $left_join_post_meta_set_check) {
    

    if ($data = get_rental_cache('rental_available_ids_duplicate_filtered', 'rental_available_ids_duplicate_filtered_expiration_date')) {
        return $data;
    }


    global $wpdb;
    $available_ids_duplicate_filtered = [];

    // duplicate products/variants filter
    if ($duplicate_products_filter["location_based_duplicate_filter"]) {
        $primary_division_id = $duplicate_products_filter["location_based_duplicate_filter_division_id"];

        $sql_set = "
            select
                id
            from 
                {$rental_set_relations} set_rel
            {$left_join_post_meta_set}
            {$left_join_post_meta_set_check}
            where
                pm.meta_value = 'instock'
                AND pm_set.meta_value = 1
        ";
        $available_set_ids = $wpdb->get_col($sql_set);

        $available_variant_post_ids_duplicate_filtered = [];
        // variants duplicate check
        if ($primary_division_id) {
            $primary_division_id = intval($primary_division_id);
            $division_duplicate_sql1 = " AND rental_division_id = $primary_division_id";
            $division_duplicate_sql2 = " AND (rental_division_id <> $primary_division_id AND pm2.meta_value <> 1 )";

            $sql1 = "
                select
                    id
                from 
                    {$rental_variant_relations} variant_rel
                {$left_join_post_meta_variant_duplicate}
                {$left_join_post_meta_variant}
                where
                    pm.meta_value = 'instock'
                    $division_duplicate_sql1
            ";
            $available_variant_post_ids_1 = $wpdb->get_col($sql1);

            $sql2 = "
                select
                    id
                from 
                    {$rental_variant_relations} variant_rel
                {$left_join_post_meta_variant_duplicate}
                {$left_join_post_meta_variant}
                where
                    pm.meta_value = 'instock'
                    $division_duplicate_sql2
            ";
            $available_variant_post_ids_2 = $wpdb->get_col($sql2);

            $available_variant_post_ids_duplicate_filtered = array_merge($available_variant_post_ids_1, $available_variant_post_ids_2);
        }

        $available_variant_post_ids_duplicate_filtered_formatted = implode(',',$available_variant_post_ids_duplicate_filtered);
        $unavailable_ids_all_query = "";
        if ($unavailable_ids_all) {
            $unavailable_ids_all_query = "AND ID NOT IN ($unavailable_ids_all)";
        }

        $available_variant_ids_duplicate_filtered = [];
        if ($available_variant_post_ids_duplicate_filtered) {
            $sql = "
                select
                    *
                from 
                    $wpdb->posts
                where
                    post_status = 'publish'
                    AND ID IN ($available_variant_post_ids_duplicate_filtered_formatted)
                    $unavailable_ids_all_query
            ";
            $available_variant_ids_duplicate_filtered = $wpdb->get_col($sql);
        }

        $available_product_post_ids_duplicate_filtered = [];
        // products duplicate check
        if ($primary_division_id) {
            $primary_division_id = intval($primary_division_id);
            $division_duplicate_sql1 = " AND rental_division_id = $primary_division_id";
            $division_duplicate_sql2 = " AND (rental_division_id <> $primary_division_id AND pm2.meta_value <> 1 )";

            $sql1 = "
                select
                    id
                from 
                    {$rental_product_relations} product_rel
                {$left_join_post_meta_product_duplicate}
                {$left_join_post_meta_product}
                where
                    pm.meta_value = 'instock'
                    $division_duplicate_sql1
            ";
            $available_product_post_ids_1 = $wpdb->get_col($sql1);

            $sql2 = "
                select
                    id
                from 
                    {$rental_product_relations} product_rel
                {$left_join_post_meta_product_duplicate}
                {$left_join_post_meta_product}
                where
                    pm.meta_value = 'instock'
                    $division_duplicate_sql2
            ";
            $available_product_post_ids_2 = $wpdb->get_col($sql2);

            $available_product_post_ids_duplicate_filtered = array_merge($available_product_post_ids_1, $available_product_post_ids_2);
        }

        $available_product_post_ids_duplicate_filtered_formatted = implode(',',$available_product_post_ids_duplicate_filtered);
        $unavailable_ids_all_query = "";
        if ($unavailable_ids_all) {
            $unavailable_ids_all_query = "AND ID NOT IN ($unavailable_ids_all)";
        }
        $available_product_ids_duplicate_filtered = [];
        if ($available_product_post_ids_duplicate_filtered) {
            $sql = "
                select
                    *
                from 
                    $wpdb->posts
                where
                    post_status = 'publish'
                    AND ID IN ($available_product_post_ids_duplicate_filtered_formatted)
                    $unavailable_ids_all_query
            ";
            $available_product_ids_duplicate_filtered = $wpdb->get_col($sql);
        }

        $available_ids_duplicate_filtered = array_unique(array_merge($available_product_ids_duplicate_filtered, $available_variant_ids_duplicate_filtered, $available_set_ids));
    }


    set_rental_cache($available_ids_duplicate_filtered, 'rental_available_ids_duplicate_filtered', 'rental_available_ids_duplicate_filtered_expiration_date');

    return $available_ids_duplicate_filtered;
}

// check product availability in single product page
function wp_ajax_rental_check_product_availability() {
    if(get_option('rental_allow_overbook', 1) == 1){
        wp_send_json(['is_available' => 1]);
    }

    if (isset($_POST["product_id"])) {

        if (!$_POST["product_id"]) {
            wp_send_json(['is_available' => 0]);
            wp_die();
        }

        $current_product_id = intval($_POST["product_id"]);
        $division_id = null;
        if (isset($_POST['rental_division_id'])) {
            $division_id = intval($_POST['rental_division_id']);
        } elseif (isset($_COOKIE['rental_division_id'])) {
            $division_id = intval($_COOKIE['rental_division_id']);
        } 


        $decrypted_rental_zip = '';
        if (isset($_COOKIE['rental_zip'])) {
            $decrypted_rental_zip = decrypt_data($_COOKIE['rental_zip'], get_option('rental_encryption_key'));
        }

        $location_based_duplicate_filter = 0;
        $location_based_duplicate_filter_division_id = 0;
        if (empty($division_id) && (get_option('rental_hide_zip') 
        || (isset($_COOKIE['rental_zip']) && (empty($_COOKIE['rental_zip']) || $decrypted_rental_zip == 1)) ) 
        ) {
            $location_based_duplicate_filter = get_option('rental_location_based_duplicate_filter', 0);
            $location_based_duplicate_filter_division_id = get_option('rental_location_based_duplicate_filter_division_id', 0);
        }

        $duplicate_filter = ["location_based_duplicate_filter" => $location_based_duplicate_filter,
        "location_based_duplicate_filter_division_id" => $location_based_duplicate_filter_division_id];

        $rental_unavailable_items = [];
        $rental_unavailable_items_opt = get_option('rental_unavailable_items');
        if ($rental_unavailable_items_opt && is_array($rental_unavailable_items_opt)) {
            $rental_unavailable_items = $rental_unavailable_items_opt;
        }

        $is_available = 0;
        if ($data = get_rental_cache('rental_product_variant_list_filter_av', 'rental_product_variant_list_filter_av_expiration_date')) {
            $is_available = $data;
            wp_send_json(['is_available' => $is_available]);
            wp_die();
        }

        $is_available = product_variant_list_filter($rental_unavailable_items, $division_id, [], $current_product_id, $duplicate_filter);
        
        set_rental_cache($is_available, 'rental_product_variant_list_filter_av', 'rental_product_variant_list_filter_av_expiration_date');
        
        
        wp_send_json(['is_available' => $is_available]);
        wp_die();
    }
    wp_send_json(['is_available' => -1]);
    wp_die();
}

// check product availability in checkout process and cart
function rental_check_product_availability($product_id_to_check) {
    if (isset($product_id_to_check) && !empty($product_id_to_check)) {
        $current_product_id = intval($product_id_to_check);
        $division_id = null;
        if (isset($_POST['rental_division_id'])) {
            $division_id = intval($_POST['rental_division_id']);
        } elseif (isset($_COOKIE['rental_division_id'])) {
            $division_id = intval($_COOKIE['rental_division_id']);
        } 

        $decrypted_rental_zip = '';
        if (isset($_COOKIE['rental_zip'])) {
            $decrypted_rental_zip = decrypt_data($_COOKIE['rental_zip'], get_option('rental_encryption_key'));
        }

        $location_based_duplicate_filter = 0;
        $location_based_duplicate_filter_division_id = 0;
        if (empty($division_id) && (get_option('rental_hide_zip') 
        || (isset($_COOKIE['rental_zip']) && (empty($_COOKIE['rental_zip']) || $decrypted_rental_zip == 1)) ) 
        ) {
            $location_based_duplicate_filter = get_option('rental_location_based_duplicate_filter', 0);
            $location_based_duplicate_filter_division_id = get_option('rental_location_based_duplicate_filter_division_id', 0);
        }

        $duplicate_filter = ["location_based_duplicate_filter" => $location_based_duplicate_filter,
        "location_based_duplicate_filter_division_id" => $location_based_duplicate_filter_division_id];

        $rental_unavailable_items = [];
        $rental_unavailable_items_opt = get_option('rental_unavailable_items');
        if ($rental_unavailable_items_opt && is_array($rental_unavailable_items_opt)) {
            $rental_unavailable_items = $rental_unavailable_items_opt;
        }

        
        if ($data = get_rental_cache('rental_product_variant_list_filter', 'rental_product_variant_list_filter_expiration_date')) {
            return $data;
        }

        $product_variant_list_filter = product_variant_list_filter($rental_unavailable_items, $division_id, [], $current_product_id, $duplicate_filter);

        set_rental_cache($product_variant_list_filter, 'rental_product_variant_list_filter', 'rental_product_variant_list_filter_expiration_date');

        return $product_variant_list_filter;
    }
}

// set product catalog visibility
function rental_set_product_catalog_visibility($product_id, $visibility) {
    $product = wc_get_product($product_id);

    if ($product) {
        
        $product->set_catalog_visibility($visibility);

        $product->save();
    }
}

// set product status
function rental_set_product_general_visibility($product_id, $visibility) {
    wp_update_post([
        'ID'            => $product_id,
        'post_status'   => $visibility,
    ]);
}

function encrypt_data($data, $key) {
    return $data;

    $cipher = "aes-256-cbc";
    $iv_length = openssl_cipher_iv_length($cipher);
    $iv = openssl_random_pseudo_bytes($iv_length);

    // Ensure IV is exactly the required length
    if (strlen($iv) < $iv_length) {
        $iv = str_pad($iv, $iv_length, "\0");
    }

    $encrypted_data = openssl_encrypt(serialize($data), $cipher, $key, 0, $iv);
    return base64_encode($iv . $encrypted_data);
}

function decrypt_data($encrypted_data, $key) {
    return $encrypted_data;

    $cipher = "aes-256-cbc";
    $data = base64_decode($encrypted_data);
    $iv_length = openssl_cipher_iv_length($cipher);

    $iv = substr($data, 0, $iv_length);
    $encrypted_data = substr($data, $iv_length);

    // Ensure IV is exactly the required length
    if (strlen($iv) < $iv_length) {
        $iv = str_pad($iv, $iv_length, "\0");
    }

    $decrypted_data = openssl_decrypt($encrypted_data, $cipher, $key, 0, $iv);
    return unserialize($decrypted_data);
}

function get_variant_data($product_id, $variant_id) {
   
    $product = wc_get_product($product_id);
    $variation = new WC_Product_Variation($variant_id);

    $data = [];
    if (!$variation || $variation->get_parent_id() != $product_id) {

        $data = [
            'name'      => $product->get_name(),  
            'item_url'  => $product->get_permalink(), 
            'image_url' => $product->get_image('medium'),  
            'product_id' => $product_id,
            'variant_id' => $variant_id,
            'price' => rental_calculate_rental_item_price($product_id, null, true)
        ];

        return $data;
    }

    $variation_attributes = $variation->get_attributes();
    $variation_attributes_data = [];
    if ($variation_attributes) {
        foreach ($variation_attributes as $attribute_name => $attribute_value) {
            
            $attribute_label = wc_attribute_label($attribute_name);
            $attribute_term_name = get_term_by('slug', $attribute_value, $attribute_name)->name;
            
            $variation_attributes_data[] = esc_html($attribute_label) . ': ' . esc_html($attribute_term_name);
        }
    }

    // Get variant data
    $data = [
        'name'      => $variation->get_title(),  
        'item_url'  => $variation->get_permalink(), 
        'image_url' => $variation->get_image('medium'), 
        'attrs' => $variation_attributes_data, 
        'product_id' => $product_id,
        'variant_id' => $variant_id,
        'price' => rental_calculate_rental_item_price($variant_id, null, true)
        // 'quantity'  => $variation->get_stock_quantity(),  // Stock quantity
        // 'image_url' => wp_get_attachment_url($variation->get_image_id()),  // Image URL
    ];

    return $data;
}

function wp_ajax_rental_update_set_items() {

    if (!isset($_POST["set_id"]) || !isset($_POST["product_id"]) || !isset($_POST["variant_id"])) {
        wp_send_json(['error' => 'The request is not valid'], 400);
        wp_die();
    }

    $set_id = intval($_POST["set_id"]);
    $item_product_id = intval($_POST["product_id"]);
    $item_variant_id = intval($_POST["variant_id"]);

    store_set_ids_with_optional_items($set_id,  $item_product_id, $item_variant_id ?: 0);
    $optional_item_price = rental_calculate_rental_item_price($item_variant_id ?: $item_product_id, null, true);

    $current_set_items = get_post_meta($set_id, '_rental_set_items', true);

    foreach($current_set_items as $key => $current_set_item) {

        if (
            $current_set_item['product_id'] == $item_product_id
            // && $current_set_item['variant_id'] == 0
            && isset($current_set_item['optional_items'])
            && $current_set_item['optional_items']
        ) {
           
            $current_set_items[$key]['variant_id'] = $item_variant_id ?: $item_product_id;
            
            $current_set_items[$key]['has_selected'] = 1;

            $current_set_items[$key]['price'] = $optional_item_price;
            $current_set_items[$key]['attribute'] = $optional_item_price;

            $opt_items = $current_set_items[$key]['optional_items'];
            foreach($opt_items as $opt_item_key => $opt_item) {
                
                if ($opt_item['variant_id']) {

                    if ($opt_item['variant_id'] == $item_variant_id) {

                        $opt_items[$opt_item_key]['is_selected'] = 1;
                        $opt_items[$opt_item_key]['price'] = $optional_item_price;
    
                        // needed data to create an order for rentopian
                        $current_set_items[$key]['rental_variant_id'] = $opt_item['rental_variant_id'] ?? 0;
                        $current_set_items[$key]['rental_product_id'] = $opt_item['rental_product_id'] ?? 0;
                    }
    
                    if ($opt_item['variant_id'] != $item_variant_id) {
    
                        $opt_items[$opt_item_key]['is_selected'] = 0;
                        $opt_items[$opt_item_key]['price'] = 0;
                    }

                } else {

                    if ($opt_item['product_id']) {

                        if ($opt_item['product_id'] == $item_product_id) {

                            $opt_items[$opt_item_key]['is_selected'] = 1;
                            $opt_items[$opt_item_key]['price'] = $optional_item_price;

                            // needed data to create an order for rentopian
                            $current_set_items[$key]['rental_variant_id'] = $opt_item['rental_variant_id'] ?? 0;
                            $current_set_items[$key]['rental_product_id'] = $opt_item['rental_product_id'] ?? 0;
                        }


                        if ($opt_item['product_id'] != $item_product_id) {
    
                            $opt_items[$opt_item_key]['is_selected'] = 0;
                            $opt_items[$opt_item_key]['price'] = 0;
                        }
                    }
                }
               
            }

            $current_set_items[$key]['optional_items'] = $opt_items;
        }
    }

    update_post_meta($set_id, '_rental_set_items', $current_set_items);
    
    // removing the set from cart having items with optional items on any optional item update
    $item_removed = false;
    $_cart = WC()->cart;
    foreach ($_cart->get_cart() as $cart_item_key => $cart_item) {

        if ($set_id == $cart_item['product_id']) {
            $_cart->remove_cart_item($cart_item_key);
            $item_removed = true;
        }
    }

    wp_send_json(['success' => true, 'item_remove_notif' => $item_removed ? 'Please add the current Set of items to the cart to proceed' : '']);
    wp_die();
}


function wp_ajax_rental_update_set_items_addon_with_variants_optional() {

    if (!isset($_POST["set_id"]) || !isset($_POST["product_id"]) || !isset($_POST["variant_id"]) 
        || !isset($_POST["set_item_id"]) || !isset($_POST["rental_inv_id"])        
    ) {
        wp_send_json(['error' => 'The request is not valid'], 400);
        wp_die();
    }

    $set_id = intval($_POST["set_id"]);
    $selected_item_product_id = intval($_POST["set_item_id"]);
    $selected_addon_product_id = intval($_POST["product_id"]);
    $selected_addon_variant_id = intval($_POST["variant_id"]);
    $selected_rental_inv_id = intval($_POST["rental_inv_id"]);

    $optional_item_price = rental_calculate_rental_item_price($selected_addon_variant_id ?: $selected_addon_product_id, null, true);

    $current_set_items = get_post_meta($set_id, '_rental_set_items', true);

    foreach($current_set_items as $key => $current_set_item) {

        if (
            $current_set_item['product_id'] == $selected_item_product_id
            && isset($current_set_item['addons'])
            && $current_set_item['addons']
        ) {


            foreach ($current_set_item['addons'] as $item_addon_key => $item_addon) {
                
                if (
                    isset($item_addon['variants_optional'])
                    && $item_addon['variants_optional']
                    && $item_addon['rental_inv_id'] == $selected_rental_inv_id
                ) {

                    $current_set_item['addons'][$item_addon_key]['has_selected'] = 1;
                    $current_set_item['addons'][$item_addon_key]['already_selected'] = 1;

                    $item_addon_optional_items = $item_addon['variants_optional'];
                    foreach($item_addon_optional_items as $item_addon_optional_item_key => $item_addon_optional_item) {

                        if ($item_addon_optional_item['variant_id'] && $selected_addon_variant_id) {

                            if ($item_addon_optional_item['variant_id'] == $selected_addon_variant_id) {
                                
                                $item_addon_optional_items[$item_addon_optional_item_key]['is_selected'] = 1;
                                $item_addon_optional_items[$item_addon_optional_item_key]['price'] = $optional_item_price;

                                $current_set_item['addons'][$item_addon_key]['variant_id'] = $selected_addon_variant_id;
                                $current_set_item['addons'][$item_addon_key]['product_id'] = $selected_addon_product_id;

                                // needed data to create an order for rentopian
                                $current_set_item['addons'][$item_addon_key]['rental_variant_id'] = $item_addon_optional_item['rental_variant_id'] ?? 0;
                                $current_set_item['addons'][$item_addon_key]['rental_product_id'] = $item_addon_optional_item['rental_product_id'] ?? 0;
                            }
            
                            if ($item_addon_optional_item['variant_id'] != $selected_addon_variant_id) {
            
                                $item_addon_optional_items[$item_addon_optional_item_key]['is_selected'] = 0;
                                $item_addon_optional_items[$item_addon_optional_item_key]['price'] = 0;
                            }
        
                        } else {
        
                            if ($item_addon_optional_item['product_id']) {
        
                                if ($item_addon_optional_item['product_id'] == $selected_addon_product_id) {
        
                                    $item_addon_optional_items[$item_addon_optional_item_key]['is_selected'] = 1;
                                    $item_addon_optional_items[$item_addon_optional_item_key]['price'] = $optional_item_price;
                                
                                    $current_set_item['addons'][$item_addon_key]['variant_id'] = $selected_addon_product_id;
                                    $current_set_item['addons'][$item_addon_key]['product_id'] = $selected_addon_product_id;

                                    // needed data to create an order for rentopian
                                    $current_set_item['addons'][$item_addon_key]['rental_variant_id'] = $item_addon_optional_item['rental_variant_id'] ?? 0;
                                    $current_set_item['addons'][$item_addon_key]['rental_product_id'] = $item_addon_optional_item['rental_product_id'] ?? 0;
                                }
        
        
                                if ($item_addon_optional_item['product_id'] != $selected_addon_product_id) {
            
                                    $item_addon_optional_items[$item_addon_optional_item_key]['is_selected'] = 0;
                                    $item_addon_optional_items[$item_addon_optional_item_key]['price'] = 0;
                                }
                            }
                        }

                    }

                    $current_set_item['addons'][$item_addon_key]['variants_optional'] = $item_addon_optional_items;
                
                } else {

                    if (!isset($current_set_item['addons'][$item_addon_key]['already_selected']) || (isset($current_set_item['addons'][$item_addon_key]['already_selected']) && $current_set_item['addons'][$item_addon_key]['already_selected'] != 1)) {
                        $current_set_item['addons'][$item_addon_key]['has_selected'] = 0;
                    }
                }

               
            }

            $current_set_items[$key]['addons'] = $current_set_item['addons'];

        }
    }

    $_rental_sets_with_variant_addons_exist_in_process_data = get_option('_rental_sets_with_variant_addons_exist_in_process', []);

    if (!in_array($set_id, $_rental_sets_with_variant_addons_exist_in_process_data)) {
        $_rental_sets_with_variant_addons_exist_in_process_data[] = $set_id;
        update_option('_rental_sets_with_variant_addons_exist_in_process', $_rental_sets_with_variant_addons_exist_in_process_data);
    }

    update_post_meta($set_id, '_rental_set_items', $current_set_items);
    
    // removing the set from cart having items with optional items on any optional item update
    $item_removed = false;
    $_cart = WC()->cart;
    foreach ($_cart->get_cart() as $cart_item_key => $cart_item) {

        if ($set_id == $cart_item['product_id']) {
            $_cart->remove_cart_item($cart_item_key);
            $item_removed = true;
        }
    }

    wp_send_json(['success' => true, 'item_remove_notif' => $item_removed ? 'Please add the current Set of items to the cart to proceed' : '']);
    wp_die();
}

// using this function when there are hidden addons with optional variants 
function wp_ajax_rental_set_items_addons_with_variants_optional_default_update() {

    if (!isset($_POST["set_id"])) {
        wp_send_json(['error' => 'The request is not valid'], 400);
        wp_die();
    }

    $set_id = intval($_POST["set_id"]);

    if (!get_option('rental_set_items_have_addons', false)) {
        wp_send_json(['success' => 'Sets do not have addons!']);
        wp_die();
    }


    $set_id = intval($_POST["set_id"]);

    $current_set_items = get_post_meta($set_id, '_rental_set_items', true);

    foreach($current_set_items as $key => $current_set_item) {

        if (
            isset($current_set_item['addons'])
            && $current_set_item['addons']
        ) {

            $current_set_item_addons_count = count($current_set_item['addons']);

            foreach ($current_set_item['addons'] as $item_addon_key => $item_addon) {
                
                if (
                    isset($item_addon['variants_optional'])
                    && $item_addon['variants_optional']
                    && 
                    (
                        (isset($item_addon['hidden']) 
                        && $item_addon['hidden'])
                        || $current_set_item_addons_count == 1
                    )
                ) {

                    if (
                        (isset($item_addon['has_selected'])
                        && $item_addon['has_selected'] == 1)
                        || (isset($item_addon['already_selected'])
                        && $item_addon['already_selected'] == 1)
                    ) {
                        continue;
                    }

                    $custom_price = $item_addon['inherit_price'] ? null : $item_addon['price'];
                        
                    $current_set_item['addons'][$item_addon_key]['has_selected'] = 1;
                    $current_set_item['addons'][$item_addon_key]['already_selected'] = 1;

                    $item_addon_optional_items = $item_addon['variants_optional'];
                    foreach($item_addon_optional_items as $item_addon_optional_item_key => $item_addon_optional_item) {

                        if ($item_addon_optional_item['variant_id']) {

                            if ($item_addon_optional_item_key == 0) {
                                
                                $optional_item_price = rental_calculate_rental_item_price($item_addon_optional_item['variant_id'], $custom_price);
                                
                                $item_addon_optional_items[$item_addon_optional_item_key]['is_selected'] = 1;
                                $item_addon_optional_items[$item_addon_optional_item_key]['price'] = $optional_item_price;

                                $current_set_item['addons'][$item_addon_key]['variant_id'] = $item_addon_optional_item['variant_id'];
                                $current_set_item['addons'][$item_addon_key]['product_id'] = $item_addon_optional_item['product_id'];

                                // needed data to create an order for rentopian
                                $current_set_item['addons'][$item_addon_key]['rental_variant_id'] = $item_addon_optional_item['rental_variant_id'] ?? 0;
                                $current_set_item['addons'][$item_addon_key]['rental_product_id'] = $item_addon_optional_item['rental_product_id'] ?? 0;
                            
                            } else {

                                $item_addon_optional_items[$item_addon_optional_item_key]['is_selected'] = 0;
                                $item_addon_optional_items[$item_addon_optional_item_key]['price'] = 0;
                            }
        
                        } 
                        else {
        
                            if ($item_addon_optional_item['product_id']) {
        
                                if ($item_addon_optional_item_key == 0) {
        
                                    $optional_item_price = rental_calculate_rental_item_price($item_addon_optional_item['product_id'], $custom_price);

                                    $item_addon_optional_items[$item_addon_optional_item_key]['is_selected'] = 1;
                                    $item_addon_optional_items[$item_addon_optional_item_key]['price'] = $optional_item_price;
                                
                                    $current_set_item['addons'][$item_addon_key]['variant_id'] = $item_addon_optional_item['product_id'];
                                    $current_set_item['addons'][$item_addon_key]['product_id'] = $item_addon_optional_item['product_id'];

                                    // needed data to create an order for rentopian
                                    $current_set_item['addons'][$item_addon_key]['rental_variant_id'] = $item_addon_optional_item['rental_variant_id'] ?? 0;
                                    $current_set_item['addons'][$item_addon_key]['rental_product_id'] = $item_addon_optional_item['rental_product_id'] ?? 0;
                                
                                } else {

                                    $item_addon_optional_items[$item_addon_optional_item_key]['is_selected'] = 0;
                                    $item_addon_optional_items[$item_addon_optional_item_key]['price'] = 0;
                                }
        
                            }
                        }

                    }

                    $current_set_item['addons'][$item_addon_key]['variants_optional'] = $item_addon_optional_items;

                    
                
                } else {

                    if (!isset($current_set_item['addons'][$item_addon_key]['already_selected']) || (isset($current_set_item['addons'][$item_addon_key]['already_selected']) && $current_set_item['addons'][$item_addon_key]['already_selected'] != 1)) {
                        $current_set_item['addons'][$item_addon_key]['has_selected'] = 0;
                    }
                }

               
            }

            $current_set_items[$key]['addons'] = $current_set_item['addons'];

        }
    }


    $_rental_sets_with_variant_addons_exist_in_process_data = get_option('_rental_sets_with_variant_addons_exist_in_process', []);

    if (!in_array($set_id, $_rental_sets_with_variant_addons_exist_in_process_data)) {
        $_rental_sets_with_variant_addons_exist_in_process_data[] = $set_id;
        update_option('_rental_sets_with_variant_addons_exist_in_process', $_rental_sets_with_variant_addons_exist_in_process_data);
    }

    update_post_meta($set_id, '_rental_set_items', $current_set_items);
    
    // removing the set from cart having items with optional items on any optional item update
    $item_removed = false;
    $_cart = WC()->cart;
    foreach ($_cart->get_cart() as $cart_item_key => $cart_item) {

        if ($set_id == $cart_item['product_id']) {
            $_cart->remove_cart_item($cart_item_key);
            $item_removed = true;
        }
    }

    wp_send_json(['success' => true, 'item_remove_notif' => $item_removed ? 'Please add the current Set of items to the cart to proceed' : '']);
    wp_die();
}


function store_set_ids_with_optional_items($id, $item_product_id, $selected_variant_id) {
    
    $stored_ids = get_option('_rental_set_ids_with_optional_items', []);

    if ($selected_variant_id) {
        if (!isset($stored_ids[$id][$item_product_id])) {
            $stored_ids[$id][$item_product_id] = 0;
        }
    
        if ($stored_ids[$id][$item_product_id] != $selected_variant_id) {
            $stored_ids[$id][$item_product_id] = $selected_variant_id;
        }

    } else {

        $stored_ids[$id][$item_product_id] = $item_product_id;
    }

    update_option('_rental_set_ids_with_optional_items', $stored_ids);
}

function get_set_ids_with_optional_items() {
    if ($stored_ids = get_option('_rental_set_ids_with_optional_items', [])) {
        return $stored_ids;
    }

    return [];
}


function wp_ajax_rental_calculate_set_price_based_on_items_price() {
    if (!isset($_POST["set_id"])) {
        wp_send_json(['error' => 'The request is not valid'], 400);
        wp_die();
    }

    $set_id = intval($_POST["set_id"]);

    $item_based_total = get_post_meta($set_id, '_rental_item_based_total', true);
    if (!$item_based_total) {
        wp_send_json(['msg' => 'The Set\'s price calculation is not based on items total'], 400);
        wp_die();
    }
    

    $set_total_price = 0;
    $current_set_items = get_post_meta($set_id, '_rental_set_items', true);

    foreach($current_set_items as $key => $current_set_item) {

        $optional_items_count = isset($current_set_item['optional_items']) && $current_set_item['optional_items'] ? count($current_set_item['optional_items']) : 0;
        $select_the_only_one_option = $optional_items_count == 1 ? true : false;

        // items with optional items (variants)
        if (
            isset($current_set_item['optional_items'])
            && $current_set_item['optional_items']
            && $current_set_item['optional_item_price_update_needed'] == 2 // the price is already set
            &&
            (
                $current_set_item['has_selected'] == 1
                || $select_the_only_one_option
            )
        ) {

            $opt_items = $current_set_items[$key]['optional_items'];
            foreach($opt_items as $opt_item_key => $opt_item) {
                
                if ($select_the_only_one_option) {
                    
                    if ($opt_item_key == 0) {
                        if ($opt_item['variant_id']) {

                            $optional_item_price = rental_calculate_rental_item_price($opt_item['variant_id'], null, 1);
                            $set_total_price += $optional_item_price;

                        } else {
        
                            if ($opt_item['product_id']) {
                                
                                $optional_item_price = rental_calculate_rental_item_price($opt_item['product_id'], null, 1);
                                $set_total_price += $optional_item_price;
                            }
                        }
                    }

                } else {

                    if ($opt_item['is_selected'] == 1) {

                        if ($opt_item['variant_id']) {

                            if ($opt_item['variant_id'] == $current_set_item['variant_id']) {

                                $optional_item_price = rental_calculate_rental_item_price($opt_item['variant_id'], null, 1);
                                $set_total_price += $optional_item_price;
                            }
        
                        } else {
        
                            if ($opt_item['product_id']) {

                                if ($opt_item['product_id'] == $current_set_item['product_id']) {
                                    
                                    $optional_item_price = rental_calculate_rental_item_price($opt_item['product_id'], null, 1);
                                    $set_total_price += $optional_item_price;
                                }
                            }
                        }
                    }

                }
            }
        }

        // simple items
        if (
            ($current_set_item['product_id'] || $current_set_item['variant_id'])
            && $current_set_item['price']
        ) {

            $set_total_price += rental_calculate_rental_item_price($current_set_item['variant_id'] ? $current_set_item['variant_id'] : $current_set_item['product_id'], $current_set_item['price']);
        }

        // addons
        if (
            isset($current_set_item['addons'])
            && $current_set_item['addons']
        ) {

            $current_set_item_addons_count = count($current_set_item['addons']);

            foreach ($current_set_item['addons'] as $item_addon_key => $item_addon) {
                
                $custom_price = $item_addon['inherit_price'] ? null : $item_addon['price'];

                if (
                    isset($item_addon['variants_optional'])
                    && $item_addon['variants_optional']
                ) {

                    $item_addon_optional_items = $item_addon['variants_optional'];

                    if (
                        (isset($item_addon['has_selected'])
                        && $item_addon['has_selected'] == 1)
                        || (isset($item_addon['already_selected'])
                        && $item_addon['already_selected'] == 1)
                    ) {
                        
                       
                        foreach($item_addon_optional_items as $item_addon_optional_item_key => $item_addon_optional_item) {
    
                            if ($item_addon_optional_item['variant_id']) {
    
                                if ($item_addon_optional_item['is_selected'] == 1) {
                                    
                                    $optional_item_price = rental_calculate_rental_item_price($item_addon_optional_item['variant_id'], $custom_price);
                                    $set_total_price += $optional_item_price;
                                
                                }
                            } 
                            else {
            
                                if ($item_addon_optional_item['product_id']) {
            
                                    if ($item_addon_optional_item['is_selected'] == 1) {
            
                                        $optional_item_price = rental_calculate_rental_item_price($item_addon_optional_item['product_id'], $custom_price);
                                        $set_total_price += $optional_item_price;
                                    
                                    } 
                                }
                            }
    
                        }

                    } else if ($current_set_item_addons_count == 1) {

                        foreach($item_addon_optional_items as $item_addon_optional_item_key => $item_addon_optional_item) {
    
                            if ($item_addon_optional_item['variant_id']) {
    
                                if ($item_addon_optional_item_key == 0) {
                                    
                                    $optional_item_price = rental_calculate_rental_item_price($item_addon_optional_item['variant_id'], $custom_price);
                                    $set_total_price += $optional_item_price;
                                
                                }
            
                            } 
                            else {
            
                                if ($item_addon_optional_item['product_id']) {
            
                                    if ($item_addon_optional_item_key == 0) {
            
                                        $optional_item_price = rental_calculate_rental_item_price($item_addon_optional_item['product_id'], $custom_price);
                                        $set_total_price += $optional_item_price;
                                    
                                    }
                                }
                            }
    
                        }
                    }
                
                } else {

                    if ($item_addon['product_id'] || $item_addon['variant_id']) {
                        // simple addons (no variants optional)
                        $item_addon_price = rental_calculate_rental_item_price($item_addon['variant_id'] ? $item_addon['variant_id'] : $item_addon['product_id'], $custom_price);
                        $set_total_price += $item_addon_price;
                    }
                }

               
            }
        }

    }

    if ($set_total_price) {
        // update_post_meta($set_id, '_price', $set_total_price);
        // will calculate the set total based on each item price
        update_post_meta($set_id, '_price', 0);
    }

    wp_send_json(['msg' => 'success', 'set_total' => $set_total_price, 'set_total_html' => wc_price( $set_total_price ),
        // 'current_set_items' => $current_set_items
    ]
    , 200);
    wp_die(); 
}


/* Sets Items' Optional Items default selection for hidden set items 
*  description : rental set items' optional items' default selection for when there is 
* '_rental_hide_items_on_website' setting enabled for a specific set
*/
function wp_ajax_rental_set_items_default_update() {

    if (!isset($_POST["set_id"])) {
        wp_send_json(['error' => 'The request is not valid'], 400);
        wp_die();
    }

    $set_id = intval($_POST["set_id"]);

    // if (!get_post_meta($set_id, '_rental_set_items_have_optional_items', true)) {
    //     wp_send_json(['success' => 'There are no optional items!']);
    //     wp_die();
    // }

    if (
        !get_post_meta($set_id, '_rental_hide_items_on_website', true) 
        && !get_post_meta($set_id, '_rental_some_hidden_items', true)
        && !get_option('rental_hide_set_items', 0)
    ) {
        wp_send_json(['success' => 'There are no hidden items!']);
        wp_die();
    }
  
    $current_set_items = get_post_meta($set_id, '_rental_set_items', true);
  

    if (get_post_meta($set_id, '_rental_hide_items_on_website', true) || get_option('rental_hide_set_items', 0)) {
        // hiding all the set items

        foreach($current_set_items as $key => $current_set_item) {

            if (
                get_post_meta($set_id, '_rental_set_items_have_optional_items', true)
                && isset($current_set_item['optional_items'])
                && $current_set_item['optional_items']
                && $current_set_item['has_selected'] != 1
            ) {
    
                $default_variant_id = 0;
                $default_product_id = 0;
    
                $opt_items = $current_set_item['optional_items'];
                foreach($opt_items as $opt_item_key => $opt_item) {
                    
                    if ($opt_item['variant_id']) {
    
                        if ($opt_item_key == 0) {
    
                            $opt_items[$opt_item_key]['is_selected'] = 1;
    
                            $current_set_items[$key]['has_selected'] = 1;
                            $current_set_items[$key]['variant_id'] = $opt_item['variant_id'];
    
                            $default_variant_id = $opt_item['variant_id'];
                            $default_product_id = $opt_item['product_id'];
    
                            $optional_item_price = rental_calculate_rental_item_price($default_variant_id);
        
                            $opt_items[$opt_item_key]['price'] = $optional_item_price;
                            
                            $current_set_items[$key]['price'] = $optional_item_price;
                            $current_set_items[$key]['attribute'] = $optional_item_price;

                            // needed data to create an order for rentopian
                            $current_set_items[$key]['rental_variant_id'] = $opt_item['rental_variant_id'] ?? 0;
                            $current_set_items[$key]['rental_product_id'] = $opt_item['rental_product_id'] ?? 0;
                        
                        } else {
    
                            $opt_items[$opt_item_key]['is_selected'] = 0;
                            $opt_items[$opt_item_key]['price'] = 0;
                        }
    
                    } else {
    
                        if ($opt_item['product_id']) {
    
                            if ($opt_item_key == 0) {
    
                                $opt_items[$opt_item_key]['is_selected'] = 1;
        
                                $current_set_items[$key]['has_selected'] = 1;
                                $current_set_items[$key]['variant_id'] = $opt_item['product_id'];
    
                                $default_variant_id = $opt_item['product_id'];
                                $default_product_id = $opt_item['product_id'];
        
                                $optional_item_price = rental_calculate_rental_item_price($default_variant_id);
            
                                $opt_items[$opt_item_key]['price'] = $optional_item_price;
                                
                                $current_set_items[$key]['price'] = $optional_item_price;
                                $current_set_items[$key]['attribute'] = $optional_item_price;

                                // needed data to create an order for rentopian
                                $current_set_items[$key]['rental_variant_id'] = $opt_item['rental_variant_id'] ?? 0;
                                $current_set_items[$key]['rental_product_id'] = $opt_item['rental_product_id'] ?? 0;
        
                            } else {
                                
                                $opt_items[$opt_item_key]['is_selected'] = 0;
                                $opt_items[$opt_item_key]['price'] = 0;
                            }
    
                        }
                    }
                   
                }
    
                $current_set_items[$key]['optional_items'] = $opt_items;
    
                store_set_ids_with_optional_items($set_id, $default_product_id, $default_variant_id);
            }



            // checking/processing hidden addons of set items
            if (
                isset($current_set_item['addons'])
                && $current_set_item['addons']
            ) {
    
                foreach ($current_set_item['addons'] as $item_addon_key => $item_addon) {
                    
                    if (
                        isset($item_addon['variants_optional'])
                        && $item_addon['variants_optional']
                        // && isset($item_addon['hidden']) 
                        // && $item_addon['hidden']
                    ) {
    
                        if (
                            (isset($item_addon['has_selected'])
                            && $item_addon['has_selected'] == 1)
                            || (isset($item_addon['already_selected'])
                            && $item_addon['already_selected'] == 1)
                        ) {
                            continue;
                        }
    
                            
                        $current_set_item['addons'][$item_addon_key]['has_selected'] = 1;
                        $current_set_item['addons'][$item_addon_key]['already_selected'] = 1;
    
                        $item_addon_optional_items = $item_addon['variants_optional'];
                        foreach($item_addon_optional_items as $item_addon_optional_item_key => $item_addon_optional_item) {
    
                            if ($item_addon_optional_item['variant_id']) {
    
                                if ($item_addon_optional_item_key == 0) {
                                    
                                    $optional_item_price = rental_calculate_rental_item_price($item_addon_optional_item['variant_id']);
    
                                    $item_addon_optional_items[$item_addon_optional_item_key]['is_selected'] = 1;
                                    $item_addon_optional_items[$item_addon_optional_item_key]['price'] = $optional_item_price;
    
                                    $current_set_item['addons'][$item_addon_key]['variant_id'] = $item_addon_optional_item['variant_id'];
                                    $current_set_item['addons'][$item_addon_key]['product_id'] = $item_addon_optional_item['product_id'];

                                    // needed data to create an order for rentopian
                                    $current_set_item['addons'][$item_addon_key]['rental_variant_id'] = $item_addon_optional_item['rental_variant_id'] ?? 0;
                                    $current_set_item['addons'][$item_addon_key]['rental_product_id'] = $item_addon_optional_item['rental_product_id'] ?? 0;
                                
                                } else {
    
                                    $item_addon_optional_items[$item_addon_optional_item_key]['is_selected'] = 0;
                                    $item_addon_optional_items[$item_addon_optional_item_key]['price'] = 0;
                                }
            
                            } 
                            else {
        
                                if ($item_addon_optional_item['product_id']) {
            
                                    if ($item_addon_optional_item_key == 0) {
            
                                        $optional_item_price = rental_calculate_rental_item_price($item_addon_optional_item['product_id']);
    
                                        $item_addon_optional_items[$item_addon_optional_item_key]['is_selected'] = 1;
                                        $item_addon_optional_items[$item_addon_optional_item_key]['price'] = $optional_item_price;
                                    
                                        $current_set_item['addons'][$item_addon_key]['variant_id'] = $item_addon_optional_item['product_id'];
                                        $current_set_item['addons'][$item_addon_key]['product_id'] = $item_addon_optional_item['product_id'];

                                        // needed data to create an order for rentopian
                                        $current_set_item['addons'][$item_addon_key]['rental_variant_id'] = $item_addon_optional_item['rental_variant_id'] ?? 0;
                                        $current_set_item['addons'][$item_addon_key]['rental_product_id'] = $item_addon_optional_item['rental_product_id'] ?? 0;
                                    
                                    } else {
    
                                        $item_addon_optional_items[$item_addon_optional_item_key]['is_selected'] = 0;
                                        $item_addon_optional_items[$item_addon_optional_item_key]['price'] = 0;
                                    }
            
                                }
                            }
                        }
    
                        $current_set_item['addons'][$item_addon_key]['variants_optional'] = $item_addon_optional_items;
                    
                    } else {
    
                        if (!isset($current_set_item['addons'][$item_addon_key]['already_selected']) || (isset($current_set_item['addons'][$item_addon_key]['already_selected']) && $current_set_item['addons'][$item_addon_key]['already_selected'] != 1)) {
                            $current_set_item['addons'][$item_addon_key]['has_selected'] = 0;
                        }
                    }
    
                   
                }
    
                $current_set_items[$key]['addons'] = $current_set_item['addons'];
    
            }
            
        }

    }



    if (
        ( !get_post_meta($set_id, '_rental_hide_items_on_website', true) && !get_option('rental_hide_set_items', 0) )
        && get_post_meta($set_id, '_rental_some_hidden_items', true)
    ) {
        // hiding some of the set items based on the "hidden flagged" items  

        foreach($current_set_items as $key => $current_set_item) {

            if (
                isset($current_set_item['hidden'])
                && $current_set_item['hidden']
            ) {
        

                if (
                    get_post_meta($set_id, '_rental_set_items_have_optional_items', true)
                    && isset($current_set_item['optional_items'])
                    && $current_set_item['optional_items']
                    && $current_set_item['has_selected'] != 1
                ) {
        
                    $default_variant_id = 0;
                    $default_product_id = 0;
        
                    $opt_items = $current_set_item['optional_items'];
                    foreach($opt_items as $opt_item_key => $opt_item) {
                        
                        if ($opt_item['variant_id']) {
        
                            if ($opt_item_key == 0) {
        
                                $opt_items[$opt_item_key]['is_selected'] = 1;
        
                                $current_set_items[$key]['has_selected'] = 1;
                                $current_set_items[$key]['variant_id'] = $opt_item['variant_id'];
        
                                $default_variant_id = $opt_item['variant_id'];
                                $default_product_id = $opt_item['product_id'];
        
                                $optional_item_price = rental_calculate_rental_item_price($default_variant_id);
            
                                $opt_items[$opt_item_key]['price'] = $optional_item_price;
                                
                                $current_set_items[$key]['price'] = $optional_item_price;
                                $current_set_items[$key]['attribute'] = $optional_item_price;

                                // needed data to create an order for rentopian
                                $current_set_items[$key]['rental_variant_id'] = $opt_item['rental_variant_id'] ?? 0;
                                $current_set_items[$key]['rental_product_id'] = $opt_item['rental_product_id'] ?? 0;
                            
                            } else {
        
                                $opt_items[$opt_item_key]['is_selected'] = 0;
                                $opt_items[$opt_item_key]['price'] = 0;
                            }
        
                        } else {
        
                            if ($opt_item['product_id']) {
        
                                if ($opt_item_key == 0) {
        
                                    $opt_items[$opt_item_key]['is_selected'] = 1;
            
                                    $current_set_items[$key]['has_selected'] = 1;
                                    $current_set_items[$key]['variant_id'] = $opt_item['product_id'];
        
                                    $default_variant_id = $opt_item['product_id'];
                                    $default_product_id = $opt_item['product_id'];
            
                                    $optional_item_price = rental_calculate_rental_item_price($default_variant_id);
                
                                    $opt_items[$opt_item_key]['price'] = $optional_item_price;
                                    
                                    $current_set_items[$key]['price'] = $optional_item_price;
                                    $current_set_items[$key]['attribute'] = $optional_item_price;

                                    // needed data to create an order for rentopian
                                    $current_set_items[$key]['rental_variant_id'] = $opt_item['rental_variant_id'] ?? 0;
                                    $current_set_items[$key]['rental_product_id'] = $opt_item['rental_product_id'] ?? 0;
            
                                } else {
                                    
                                    $opt_items[$opt_item_key]['is_selected'] = 0;
                                    $opt_items[$opt_item_key]['price'] = 0;
                                }
        
                            }
                        }
                    
                    }
        
                    $current_set_items[$key]['optional_items'] = $opt_items;
        
                    store_set_ids_with_optional_items($set_id, $default_product_id, $default_variant_id);
                }


                // checking/processing hidden addons of set items
                if (
                    isset($current_set_item['addons'])
                    && $current_set_item['addons']
                ) {
        
                    foreach ($current_set_item['addons'] as $item_addon_key => $item_addon) {
                        
                        if (
                            isset($item_addon['variants_optional'])
                            && $item_addon['variants_optional']
                            // && isset($item_addon['hidden']) 
                            // && $item_addon['hidden']
                        ) {
        
                            if (
                                (isset($item_addon['has_selected'])
                                && $item_addon['has_selected'] == 1)
                                || (isset($item_addon['already_selected'])
                                && $item_addon['already_selected'] == 1)
                            ) {
                                continue;
                            }
        
                                
                            $current_set_item['addons'][$item_addon_key]['has_selected'] = 1;
                            $current_set_item['addons'][$item_addon_key]['already_selected'] = 1;
        
                            $item_addon_optional_items = $item_addon['variants_optional'];
                            foreach($item_addon_optional_items as $item_addon_optional_item_key => $item_addon_optional_item) {
        
                                if ($item_addon_optional_item['variant_id']) {
        
                                    if ($item_addon_optional_item_key == 0) {
                                        
                                        $optional_item_price = rental_calculate_rental_item_price($item_addon_optional_item['variant_id']);
        
                                        $item_addon_optional_items[$item_addon_optional_item_key]['is_selected'] = 1;
                                        $item_addon_optional_items[$item_addon_optional_item_key]['price'] = $optional_item_price;
        
                                        $current_set_item['addons'][$item_addon_key]['variant_id'] = $item_addon_optional_item['variant_id'];
                                        $current_set_item['addons'][$item_addon_key]['product_id'] = $item_addon_optional_item['product_id'];

                                        // needed data to create an order for rentopian
                                        $current_set_item['addons'][$item_addon_key]['rental_variant_id'] = $item_addon_optional_item['rental_variant_id'] ?? 0;
                                        $current_set_item['addons'][$item_addon_key]['rental_product_id'] = $item_addon_optional_item['rental_product_id'] ?? 0;
                                    
                                    } else {
        
                                        $item_addon_optional_items[$item_addon_optional_item_key]['is_selected'] = 0;
                                        $item_addon_optional_items[$item_addon_optional_item_key]['price'] = 0;
                                    }
                
                                } 
                                else {
        
                                    if ($item_addon_optional_item['product_id']) {
                
                                        if ($item_addon_optional_item_key == 0) {
                
                                            $optional_item_price = rental_calculate_rental_item_price($item_addon_optional_item['product_id']);
        
                                            $item_addon_optional_items[$item_addon_optional_item_key]['is_selected'] = 1;
                                            $item_addon_optional_items[$item_addon_optional_item_key]['price'] = $optional_item_price;
                                        
                                            $current_set_item['addons'][$item_addon_key]['variant_id'] = $item_addon_optional_item['product_id'];
                                            $current_set_item['addons'][$item_addon_key]['product_id'] = $item_addon_optional_item['product_id'];
                                        
                                            // needed data to create an order for rentopian
                                            $current_set_item['addons'][$item_addon_key]['rental_variant_id'] = $item_addon_optional_item['rental_variant_id'] ?? 0;
                                            $current_set_item['addons'][$item_addon_key]['rental_product_id'] = $item_addon_optional_item['rental_product_id'] ?? 0;
                                       
                                        } else {
        
                                            $item_addon_optional_items[$item_addon_optional_item_key]['is_selected'] = 0;
                                            $item_addon_optional_items[$item_addon_optional_item_key]['price'] = 0;
                                        }
                
                                    }
                                }
                            }
        
                            $current_set_item['addons'][$item_addon_key]['variants_optional'] = $item_addon_optional_items;
        
                            
                        
                        } else {
        
                            if (!isset($current_set_item['addons'][$item_addon_key]['already_selected']) || (isset($current_set_item['addons'][$item_addon_key]['already_selected']) && $current_set_item['addons'][$item_addon_key]['already_selected'] != 1)) {
                                $current_set_item['addons'][$item_addon_key]['has_selected'] = 0;
                            }
                        }
        
                    
                    }
        
                    $current_set_items[$key]['addons'] = $current_set_item['addons'];
        
                }

            }

        }
    }
    

    update_post_meta($set_id, '_rental_set_items', $current_set_items);
    
    wp_send_json(['set\'s hidden optional items (and addons with hidden optional items) processed' => true]);
    wp_die();
}


/* Sets Items' Optional Items already selected action 
*  description : rental set items' optional items' already selected action for when there are
*  selectable items that have already a selected item (or set items with only one option) from the Rentopian system
*/
function wp_ajax_rental_update_set_already_selected_items() {

    if (!isset($_POST["set_id"])) {
        wp_send_json(['error' => 'The request is not valid'], 400);
        wp_die();
    }

    $set_id = intval($_POST["set_id"]);

    if (!get_post_meta($set_id, '_rental_set_items_have_optional_items', true)) {
        wp_send_json(['success' => 'There are no optional items!']);
        wp_die();
    }

    $current_set_items = get_post_meta($set_id, '_rental_set_items', true);
  
    foreach($current_set_items as $key => $current_set_item) {

        if ($current_set_item['optional_item_price_update_needed'] != 1) {
            continue;
        }

        
        $optional_items_count = isset($current_set_item['optional_items']) && $current_set_item['optional_items'] ? count($current_set_item['optional_items']) : 0;
        $select_the_only_one_option = $optional_items_count == 1 ? true : false;

        if (
            isset($current_set_item['optional_items'])
            && $current_set_item['optional_items']
            && $current_set_item['optional_item_price_update_needed'] == 1
            &&
            (
                $current_set_item['has_selected'] == 1
                || $select_the_only_one_option
            )
        ) {

            $current_set_items[$key]['optional_item_price_update_needed'] = 2;

            $already_selected_variant_id = 0;
            $already_selected_product_id = 0;

            $opt_items = $current_set_items[$key]['optional_items'];
            foreach($opt_items as $opt_item_key => $opt_item) {
                
                if ($select_the_only_one_option) {
                    
                    if ($opt_item_key == 0) {
                        if ($opt_item['variant_id']) {

                            $already_selected_variant_id = $opt_item['variant_id'];
                            $already_selected_product_id = $current_set_item['product_id'];
        
                            $optional_item_price = rental_calculate_rental_item_price($already_selected_variant_id);
        
                            $opt_items[$opt_item_key]['price'] = $optional_item_price;
                            
                            $current_set_items[$key]['price'] = $optional_item_price;
                            $current_set_items[$key]['attribute'] = '';

                            $opt_items[$opt_item_key]['is_selected'] = 1;
                            $current_set_items[$key]['has_selected'] = 1;

                            // needed data to create an order for rentopian
                            $current_set_items[$key]['rental_variant_id'] = $opt_item['rental_variant_id'] ?? 0;
                            $current_set_items[$key]['rental_product_id'] = $opt_item['rental_product_id'] ?? 0;

                        } else {
        
                            if ($opt_item['product_id']) {
                                
                                $already_selected_variant_id = $opt_item['product_id'];
                                $already_selected_product_id = $current_set_item['product_id'];
            
                                $optional_item_price = rental_calculate_rental_item_price($already_selected_variant_id);
            
                                $opt_items[$opt_item_key]['price'] = $optional_item_price;
                                
                                $current_set_items[$key]['price'] = $optional_item_price;
                                $current_set_items[$key]['attribute'] = '';

                                $opt_items[$opt_item_key]['is_selected'] = 1;
                                $current_set_items[$key]['has_selected'] = 1;

                                 // needed data to create an order for rentopian
                                $current_set_items[$key]['rental_variant_id'] = $opt_item['rental_variant_id'] ?? 0;
                                $current_set_items[$key]['rental_product_id'] = $opt_item['rental_product_id'] ?? 0;

                            }
                        }
                    }

                } else { 

                    if ($opt_item['is_selected'] == 1) {

                        if ($opt_item['variant_id']) {

                            if ($opt_item['variant_id'] == $current_set_item['variant_id']) {

                                $already_selected_variant_id = $current_set_item['variant_id'];
                                $already_selected_product_id = $current_set_item['product_id'];
            
                                $optional_item_price = rental_calculate_rental_item_price($already_selected_variant_id);
            
                                $opt_items[$opt_item_key]['price'] = $optional_item_price;
                                
                                $current_set_items[$key]['price'] = $optional_item_price;
                                $current_set_items[$key]['attribute'] = '';

                                // needed data to create an order for rentopian
                                $current_set_items[$key]['rental_variant_id'] = $opt_item['rental_variant_id'] ?? 0;
                                $current_set_items[$key]['rental_product_id'] = $opt_item['rental_product_id'] ?? 0;
                            }
        
                        } else {
        
                            if ($opt_item['product_id']) {

                                if ($opt_item['product_id'] == $current_set_item['product_id']) {
                                    
                                    $already_selected_variant_id = $current_set_item['product_id'];
                                    $already_selected_product_id = $current_set_item['product_id'];
                
                                    $optional_item_price = rental_calculate_rental_item_price($already_selected_variant_id);
                
                                    $opt_items[$opt_item_key]['price'] = $optional_item_price;
                                    
                                    $current_set_items[$key]['price'] = $optional_item_price;
                                    $current_set_items[$key]['attribute'] = '';

                                    // needed data to create an order for rentopian
                                    $current_set_items[$key]['rental_variant_id'] = $opt_item['rental_variant_id'] ?? 0;
                                    $current_set_items[$key]['rental_product_id'] = $opt_item['rental_product_id'] ?? 0;
                                }
                            }
                        }
                    }

                }
            }

            $current_set_items[$key]['optional_items'] = $opt_items;

            store_set_ids_with_optional_items($set_id, $already_selected_product_id, $already_selected_variant_id);
        }
    }

    update_post_meta($set_id, '_rental_set_items', $current_set_items);

    wp_send_json(['set\'s already selected optional items (and optional items with only one item) prices updated' => true]);
    wp_die();
}

function wp_ajax_rental_product_with_addons_fix_variants() {

    if (!isset($_POST["product_id"])) {
        wp_send_json(['error' => 'The request is not valid'], 400);
        wp_die();
    }

    $product_id = intval($_POST["product_id"]);
    if (!$add_ons = get_post_meta($product_id, '_rental_add_ons', true)) {
        wp_send_json(['success' => 'The product has no addons!']);
        wp_die();
    }

    foreach($add_ons as $key => $add_on) {

        $variant_id = 0;
        if ($add_on['variant_id'] != 0 ) {
            continue;
        }

        if (empty($add_on['variant_id']) && isset($add_on['rental_variant_id']) && $add_on['rental_variant_id'] != 0) {
            global $wpdb, $rental_tables;
            $rental_variant_relations = $wpdb->prefix . $rental_tables["variant_relations"];

            $variant_id = $wpdb->get_var("SELECT `id` FROM $rental_variant_relations WHERE `rental_id` = ".$add_on['rental_variant_id']);
            $add_ons[$key]['variant_id'] = $variant_id ? $variant_id : 0;
        }

    }

    update_post_meta($product_id, '_rental_add_ons', $add_ons);

    wp_send_json(['addons\' variants fixed' => true]);
    wp_die();
}

function extract_address_parts($full_address_array) {
    $city = '';
    $state = '';
    $country = '';
    $zip = '';
    $address = '';
    $address_2 = '';

    foreach ($full_address_array as $item) {
        switch ($item['key']) {
            case 'city':
                $city = $item['value'];
                break;
            case 'state':
                $state = $item['value'];
                break;
            case 'country':
                $country = $item['value'];
                break;
            case 'zip':
                $zip = $item['value'];
                break;
            case 'address':
                $address = $item['value'];
                break;
            case 'address_2':
                $address_2 = $item['value'];
                break;
        }
    }

    return [
        'city' => $city,
        'state' => $state,
        'country' => $country,
        'zip' => $zip,
        'address' => $address,
        'address_2' => $address_2,
    ];
}

function wp_ajax_update_rental_shipping_cost() {
    if( 
        get_option('rental_show_location') 
        && isset($_COOKIE["rental_google_map_address"]) 
        && $_COOKIE["rental_google_map_address"] 
        && isset($_COOKIE["rental_address"]) 
        && $_COOKIE["rental_address"]
    ) {
        
        // Initialize the WooCommerce shipping methods
        do_action('woocommerce_shipping_init');

        // if (get_option('woocommerce_miles_based_settings')['enabled'] === 'yes') {

            // Include the shipping method class file if not autoloaded
            require_once RENTOPIAN_SYNC_PATH . '/includes/class-miles-based-shipping.php';
            if (!class_exists('Miles_Based_Shipping_Method')) {
                do_action('woocommerce_shipping_init');
            }
                
            $shipping_instance = new Miles_Based_Shipping_Method();

            $rental_google_map_address_cookie = stripslashes($_COOKIE["rental_google_map_address"]);
            $data = json_decode($rental_google_map_address_cookie, true);
            
            $extracted_address = extract_address_parts($data);
            $shipping_instance->set_destination_address($extracted_address['address'], $extracted_address['state'], $extracted_address['city'], $extracted_address['country'], $extracted_address['zip'], $extracted_address['address_2']);

            $shipping_rate = $shipping_instance->calculate_shipping([], true);
            $shipping_cost = $shipping_rate['cost'];

            wp_send_json([
                'shipping_label_cost' => $shipping_cost ? $shipping_rate['label'] . ' ' . wc_price($shipping_cost) : 'Not available',
            ], 200);
                
        // }
        
    }
    

    wp_die();
}

// function wp_ajax_rental_trigger_calculate_shipping() {
    
//     $delivery_settings = rental_get_delivery_settings();
//     if ($delivery_settings['enable_different_pickup_delivery_address_for_website']) {
        
//         require_once RENTOPIAN_SYNC_PATH . '/includes/class-miles-based-shipping.php';
//         if (!class_exists('Miles_Based_Shipping_Method')) {
//             do_action('woocommerce_shipping_init');
//         }
        
//         $shipping_instance = new Miles_Based_Shipping_Method();
//         $shipping_instance->calculate_shipping();

//         wp_send_json(['shipping_calculation_triggered' => true,], 200);
//     }
//     wp_die();
// }


function set_rental_cache($data_to_be_cached, $key, $expiration_key, $expiration_time = 0) {
    update_option($key, $data_to_be_cached);
    $expiration_date = $expiration_time ? $expiration_time : time() + (12 * 60 * 60); // 12 hours
    update_option($expiration_key, $expiration_date);
}

function get_rental_cache($key, $expiration_key) {
    $rental_data = get_option($key, []);
    $exp_date = get_option($expiration_key, 0);
    if ($rental_data && $exp_date > time()) {
        return $rental_data;
    }

    return false;
}

function rental_clear_cache() {
    delete_option("rental_products_variants_divisions");
    delete_option("rental_products_variants_divisions_expiration_date");
    
    delete_option("rental_sets_divisions");
    delete_option("rental_sets_divisions_expiration_date");
    
    delete_option("rental_addon_ids");
    delete_option("rental_addon_ids_expiration_date");

    delete_option("rental_available_ids_duplicate_filtered");
    delete_option("rental_available_ids_duplicate_filtered_expiration_date");

    delete_option("rental_product_variant_list_filter_av");
    delete_option("rental_product_variant_list_filter_av_expiration_date");

    delete_option("rental_product_variant_list_filter");
    delete_option("rental_product_variant_list_filter_expiration_date");
}


function rental_update_checkout_address_fields() {

    if (isset($_POST['address']) && isset($_POST['city']) && isset($_POST['state']) && isset($_POST['zip'])) {
        
        WC()->customer->set_billing_address_1(sanitize_text_field($_POST['address']));
        WC()->customer->set_billing_address_2(sanitize_text_field($_POST['address_2'] ?? ''));
        WC()->customer->set_billing_city(sanitize_text_field($_POST['city']));
        WC()->customer->set_billing_state(sanitize_text_field($_POST['state']));
        WC()->customer->set_billing_postcode(sanitize_text_field($_POST['zip']));
        WC()->customer->set_billing_country(sanitize_text_field($_POST['country']));

        WC()->customer->set_shipping_address_1(sanitize_text_field($_POST['address']));
        WC()->customer->set_shipping_address_2(sanitize_text_field($_POST['address_2'] ?? ''));
        WC()->customer->set_shipping_city(sanitize_text_field($_POST['city']));
        WC()->customer->set_shipping_state(sanitize_text_field($_POST['state']));
        WC()->customer->set_shipping_postcode(sanitize_text_field($_POST['zip']));
        WC()->customer->set_shipping_country(sanitize_text_field($_POST['country']));

        WC()->customer->save();

        wp_send_json_success();

    } else {
        
        wp_send_json_error('Address data missing');
    }
    wp_die();
}


function ensure_wc_session() {
    if ( WC()->session && !WC()->session->has_session() ) {
        WC()->session->set_customer_session_cookie(true);
    }
}

function get_new_unique_id() {
    if ( is_user_logged_in() ) {
        return 'cart_' . get_current_user_id(); 
    }

    if ( WC()->session ) {
        ensure_wc_session();

        $guest_cart_id = WC()->session->get('guest_cart_id');
    
        if ( ! $guest_cart_id ) {
            $guest_cart_id = 'guest_' . wp_generate_uuid4();
            WC()->session->set('guest_cart_id', $guest_cart_id);
        }

        return $guest_cart_id;
    }

    return 'guest_cart_id_fallback';
}

function set_rental_session_data($key, $value) {
    if ( WC()->session ) {
        ensure_wc_session();
        $unique_id = get_new_unique_id();
        $session_key = "{$key}_{$unique_id}";
        WC()->session->set($session_key, $value);


        $tracked_keys = WC()->session->get('tracked_rental_keys', []);
        $tracked_keys[] = $session_key;
        WC()->session->set('tracked_rental_keys', $tracked_keys);
    }
}

function get_rental_session_data($key, $default = null) {
    if ( WC()->session ) {
        ensure_wc_session();
        $unique_id = get_new_unique_id();
        return WC()->session->get("{$key}_{$unique_id}", $default);
    }
    return $default;
}

function delete_rental_session_data($key) {
    if ( WC()->session ) {
        ensure_wc_session();
        $unique_id = get_new_unique_id();
        WC()->session->set("{$key}_{$unique_id}", NULL);
        WC()->session->__unset("{$key}_{$unique_id}");
    }
}




function wp_ajax_rental_update_total_on_tip_amount_change() {

    if (!isset($_POST["tip_id"])) {
        wp_send_json(['error' => 'tip id not found'], 400);
        wp_die();
    }

    $tip_amount_final = 0;
    if (
        get_option("rental_direct_only_bookings", 0)
        && get_option("rental_payment_tips_enabled", 0)
    ) {

        $tip_id = intval($_POST["tip_id"]);

        $expire_time = time() + RENTOPIAN_DATE_EXPIRE_TIME;
        setcookie('TIP_ID_SELECTED_BY_CUSTOMER' . get_new_unique_id(), $tip_id, $expire_time, "/", "", false, true);
        $_COOKIE['TIP_ID_SELECTED_BY_CUSTOMER' . get_new_unique_id()] = $tip_id;

        $tip_amount_final = calculate_tip_amount($tip_id);

        rental_calculate_order_total();
    }

    wp_send_json([
        "payment_tip_amount" => $tip_amount_final,
        "currency" => get_woocommerce_currency_symbol()
    ], 200);
}

function calculate_tip_amount($rental_payment_tip_id, $calculate_based_on_default_option = false) {

    set_rental_session_data('rental_payment_tip_id', 0);
    set_rental_session_data('rental_payment_tip_amount', 0);

    // update_option('rental_payment_tip_id' . get_new_unique_id(), 0);
    // update_option('rental_payment_tip_amount' . get_new_unique_id(), 0);

    $tip_id = $rental_payment_tip_id;
    $tip_amount = 0;
    $tip_is_percent = 0;
    $rental_payment_tips = get_option('rental_payment_tips', []);

    foreach ($rental_payment_tips as $key => $option) {

        if ($calculate_based_on_default_option) {
            // calc based on default value

            if ($option->default) {
                $tip_amount = $option->amount;
                $tip_id = $option->id;
    
                if ($option->is_percent) {
                    $tip_is_percent = 1;
                }
    
                break;
                
            } else if ($key == 0) {

                $tip_amount = $option->amount ?? 0;
                $tip_id = $option->id ?? 0;

                if (isset($option->is_percent) && $option->is_percent) {
                    $tip_is_percent = 1;
                }

                break;
            }

        } else {
            // calc based on selected tip value
            
            if ($tip_id == $option->id) {
                $tip_amount = $option->amount;
    
                if ($option->is_percent) {
                    $tip_is_percent = 1;
                }
    
                break;
            }
        }
    }

    $tip_amount_final = 0;
    if ($tip_id && $tip_amount) {

        set_rental_session_data('rental_payment_tip_id', $tip_id);

        $order_total = get_rental_session_data('total_excluded_extra_fees', 0);
        $tip_amount_formatted = number_format((float) $tip_amount, 2, '.', '');

        $tip_amount_final = $tip_amount_formatted;
        if ($tip_is_percent) {
            $tip_amount_final = ($order_total * $tip_amount_formatted / 100);
        }

        set_rental_session_data('rental_payment_tip_amount', number_format((float) $tip_amount_final, 2, '.', ''));
        // update_option('rental_payment_tip_amount' . get_new_unique_id(), number_format((float) $tip_amount_final, 2, '.', ''));
    }

    return number_format((float) $tip_amount_final, 2, '.', '');
}

function rental_get_min_order_notice() {
    $message = WC()->session->get('rental_min_order_message');
    if ($message) {
        wp_send_json_success(['message' => $message]);
    }
    wp_send_json_success(['message' => '']);
}

// get only the delivery settings (it has 15 minutes cache by default)
function rental_get_delivery_settings($force_refresh = false, $cache_duration = 15 * MINUTE_IN_SECONDS) {
    
    if (!$force_refresh) {
        $cached_settings = get_transient('rental_delivery_settings');
        if (false !== $cached_settings) {
            return $cached_settings;
        }
    }

    $shipping_data = json_decode(rental_curl('shipping/calculate-shipping-cost', get_option('rental_api_key'), false), true);
    $settings = $shipping_data['settings'] ?? '';

    if (!$force_refresh) {
        set_transient('rental_delivery_settings', $settings, $cache_duration);
    }

    return $settings;
}

function rental_update_selected_start_end_times() {

    if (!isset($_POST["selected_time_id"])) {
        wp_send_json(['error' => 'selected_time_id id not found'], 400);
        wp_die();
    }

    $time_type = isset($_POST["time_type"]) && $_POST["time_type"] == 'pickup_time' ? 'pickup_time' : 'delivery_time';

    $selected_delivery_selection_time = $selected_pickup_selection_time = [];
    if ($delivery_time_selections = get_option('delivery_time_selections', '')) {

        $selected_time = '';
        $selected_time_id = intval($_POST["selected_time_id"]);
        foreach ($delivery_time_selections as $option) {

            if ($option->id == $selected_time_id) {

                if ($time_type == 'delivery_time') {
                    $selected_time = $option->start_time;

                    $selected_delivery_selection_time = [
                        'id' => $option->id,
                        'start_time' => $option->start_time,
                        'end_time' => $option->end_time,
                    ];

                } else {
                    // pickup_time
                    $selected_time = $option->start_time;

                    $selected_pickup_selection_time = [
                        'id' => $option->id,
                        'start_time' => $option->start_time,
                        'end_time' => $option->end_time
                    ];

                    // $selected_time = $option->end_time;
                }
                
                break;
            }
        }
    }

    if ($selected_time) {

        $opt_hide_zip = get_option('rental_hide_zip');
        $opt_hide_time = get_option('rental_hide_time_pickers');

        $date_format = 'M j';
        if ( !$opt_hide_time) {
            $date_format .= ', g:i A';
        }

        $decrypted_rental_zip = false;
        if (isset($_COOKIE['rental_zip']) && $_COOKIE['rental_zip']) {
            $decrypted_rental_zip = decrypt_data($_COOKIE['rental_zip'], get_option('rental_encryption_key'));
        }
        $zip = $decrypted_rental_zip;

        $rental_start_date = isset($_COOKIE['rental_start_date']) && $_COOKIE['rental_start_date'] ? $_COOKIE['rental_start_date'] : '';
        $rental_end_date = isset($_COOKIE['rental_end_date']) && $_COOKIE['rental_end_date'] ? $_COOKIE['rental_end_date'] : '';

        if ($time_type == 'delivery_time') {


            if ($rental_start_date) {
    
                $date_part = DateTime::createFromFormat('Y/m/d h:i A', $rental_start_date);
                if (!$date_part) {
                    // If parsing failed, try with date-only
                    $date_part = DateTime::createFromFormat('Y/m/d', $rental_start_date);
                }
    
    
                if ($date_part) {
    
                    $new_datetime_str = $date_part->format('Y/m/d') . ' ' . $selected_time;
            
                    // Parse new datetime to ensure it's valid
                    $new_datetime = DateTime::createFromFormat('Y/m/d h:i A', $new_datetime_str);
                    $day_name = $new_datetime ? $new_datetime->format('l') : '';
                    $selected_delivery_selection_time['day'] = getDayNumberByDayName($day_name);

                    if ($new_datetime) {

                        $start_date = $new_datetime->format('Y/m/d h:i A');
                        $error = rental_validate_dates($opt_hide_time, $opt_hide_zip, $start_date, $rental_end_date, $zip);

                        if ($error) {

                            unset_delivery_times_data();

                            wp_send_json(['failure' => true, 'error' => $error], 400);
                            wp_die();
                        }
    
                        $encrypted_rental_start_date = encrypt_data($start_date, get_option('rental_encryption_key'));
                        $_COOKIE['rental_start_date'] = $encrypted_rental_start_date;
                        setcookie('rental_start_date', $encrypted_rental_start_date, time() + RENTOPIAN_DATE_EXPIRE_TIME, "/", "", false, true);
            

                        $_COOKIE['rental_selected_delivery_selection_time'] = json_encode($selected_delivery_selection_time);
                        setcookie('rental_selected_delivery_selection_time', json_encode($selected_delivery_selection_time), time() + RENTOPIAN_DATE_EXPIRE_TIME, "/", "", false, true);


                        // $checkout_dates_html = rntp_build_checkout_dates_html( 
                        //     $formatted_start_date, 
                        //     null, 
                        //     $rental_start_date, 
                        //     $rental_end_date, 
                        //     $date_format
                        // );

                        ob_start();
                        // do_action('woocommerce_checkout_before_order_review');
                        checkout_rental_dates();
                        $checkout_dates_html = ob_get_clean();

                        $formatted_start_date = date($date_format, strtotime($start_date));

                        wp_send_json([
                            'success' => true,
                            'checkout_dates_html' => $checkout_dates_html,
                            'rental_start_date' => $formatted_start_date,
                            'rental_end_date' => '',
                            'update_checkout_dates' => get_option('rental_dates_on_checkout', '') !== '' ? 1 : 0,
                        ], 200);

                    } else {
                        wp_send_json(['error' => 'Operation failed'], 400);
                    }
                    
                } else {
                    wp_send_json(['error' => 'Operation failed'], 400);
                }

                wp_die();
            }
    
        } else {


            if ($rental_end_date) {
    
                $date_part = DateTime::createFromFormat('Y/m/d h:i A', $rental_end_date);
                if (!$date_part) {
                    // If parsing failed, try with date-only
                    $date_part = DateTime::createFromFormat('Y/m/d', $rental_end_date);
                }
    
    
                if ($date_part) {
    
                    $new_datetime_str = $date_part->format('Y/m/d') . ' ' . $selected_time;
            
                    // Parse new datetime to ensure it's valid
                    $new_datetime = DateTime::createFromFormat('Y/m/d h:i A', $new_datetime_str);
                    $day_name_pickup = $new_datetime ? $new_datetime->format('l') : '';
                    $selected_pickup_selection_time['day'] = getDayNumberByDayName($day_name_pickup);
            
                    if ($new_datetime) {

                        $end_date = '';
                        if (!empty($selected_pickup_selection_time['end_time'])) {
                            $new_end_datetime_str = $date_part->format('Y/m/d') . ' ' . $selected_pickup_selection_time['end_time'];
                            $new_end_datetime = DateTime::createFromFormat('Y/m/d h:i A', $new_end_datetime_str);
                            $end_date = $new_end_datetime->format('Y/m/d h:i A');
                        }
                        if (empty($end_date)) {
                            wp_send_json(['failure' => true, 'error' => 'No pickup time selected.'], 400);
                            wp_die();
                        }
                       
                        $error = rental_validate_dates($opt_hide_time, $opt_hide_zip, $rental_start_date, $end_date, $zip);

                        if ($error) {

                            unset_delivery_times_data();

                            wp_send_json(['failure' => true, 'error' => $error], 400);
                            wp_die();
                        }

                        $encrypted_rental_end_date = encrypt_data($end_date, get_option('rental_encryption_key'));
                        $_COOKIE['rental_end_date'] = $encrypted_rental_end_date;
                        setcookie('rental_end_date', $encrypted_rental_end_date, time() + RENTOPIAN_DATE_EXPIRE_TIME, "/", "", false, true);
            
                        $_COOKIE['rental_selected_pickup_selection_time'] = json_encode($selected_pickup_selection_time);
                        setcookie('rental_selected_pickup_selection_time', json_encode($selected_pickup_selection_time), time() + RENTOPIAN_DATE_EXPIRE_TIME, "/", "", false, true);


                        // $checkout_dates_html = rntp_build_checkout_dates_html( 
                        //     null, 
                        //     $formatted_end_date, 
                        //     $rental_start_date, 
                        //     $rental_end_date, 
                        //     $date_format
                        // );

                        ob_start();
                        // do_action('woocommerce_checkout_before_order_review');
                        checkout_rental_dates();
                        $checkout_dates_html = ob_get_clean();

                        $formatted_end_date = date($date_format, strtotime($end_date));

                        wp_send_json([
                            'success' => true,
                            'checkout_dates_html' => $checkout_dates_html,
                            'rental_start_date' => '',
                            'rental_end_date' => $formatted_end_date,
                            'update_checkout_dates' => get_option('rental_dates_on_checkout', '') !== '' ? 1 : 0,
                        ], 200);

                    } else {
                        wp_send_json(['error' => 'Operation failed'], 400);
                    }
                    
                } else {
                    wp_send_json(['error' => 'Operation failed'], 400);
                }
    
                wp_die();
            }
        }
      
    } else {

        unset_delivery_times_data();
    }

}


function isEmptyPrice($price) {
    return $price === null || $price === '' || floatval($price) <= 0.0;
}

function parseWithDefaultTime(string $input, string $defaultTime = '00:00:00'): DateTime {
    // does it contain something that looks like "HH:MM"?
    if (preg_match('/\d{1,2}:\d{2}/', $input)) {
        // assume the date string has a time (24‑hour or with AM/PM)
        return new DateTime($input);
    } else {
        // no time found, append the default
        return new DateTime("$input $defaultTime");
    }
}

function getTimeFromDate(string $date, string $defaultTime = '00:00:00'): string
{
    // regex breakdown:
    // (\d{1,2}:\d{2}(?::\d{2})?)  — matches "H:MM", "HH:MM", or "HH:MM:SS"
    // (?:\s?([AP]M)?              — optionally matches a space then "AM" or "PM"
    $pattern = '/(\d{1,2}:\d{2}(?::\d{2})?)(?:\s?([AP]M))?/i';

    if (preg_match($pattern, $date, $matches)) {
        // $matches[1] is the time (HH:MM or HH:MM:SS)
        // $matches[2] is AM or PM (if present)
        $time = $matches[1];
        if (!empty($matches[2])) {
            // append AM/PM in uppercase
            $time .= ' ' . strtoupper($matches[2]);
        }
        return $time;
    }

    return $defaultTime;
}

function rental_set_selected_delivery_pickup_start_end_times($rental_start_date, $rental_end_date, $opt_default_start_time, $opt_default_end_time, $opt_hide_time_pickers) {
    
    $opt_hide_end_date = get_option('rental_hide_end_date');
    $finilizedStartEndDate = RTDelivery::extractFinalRentalStartEndDate($rental_start_date, $rental_end_date, $opt_hide_time_pickers, $opt_default_start_time, $opt_default_end_time, $opt_hide_end_date);

    $rental_start_date = $finilizedStartEndDate['rental_start_date'];
    $rental_end_date = $finilizedStartEndDate['rental_end_date'];
    
    // set start date time as start delivery time and end date time as pickup start time
    $delivery_start_time = getTimeFromDate($rental_start_date, $opt_default_start_time);

    $rental_start_date_obj = parseWithDefaultTime($rental_start_date, $opt_default_start_time);
    $start_date_day_name = $rental_start_date_obj->format('l'); // Full name of the day

    $selected_delivery_selection_time = [
        'id' => 0,
        'start_time' => $delivery_start_time,
        'end_time' => '',
        'day' => getDayNumberByDayName($start_date_day_name),
    ];

    $_COOKIE['rental_selected_delivery_selection_time'] = json_encode($selected_delivery_selection_time);
    setcookie('rental_selected_delivery_selection_time', json_encode($selected_delivery_selection_time), time() + RENTOPIAN_DATE_EXPIRE_TIME, "/", "", false, true);

    if ($rental_end_date) {
        $pickup_start_time = getTimeFromDate($rental_end_date, $opt_default_end_time);

        $rental_end_date_obj = parseWithDefaultTime($rental_end_date, $opt_default_end_time);
        $end_date_day_name = $rental_end_date_obj->format('l'); // Full name of the day
    }
    $selected_pickup_selection_time = [
        'id' => 0,
        'start_time' => $pickup_start_time,
        'end_time' => '',
        'day' => getDayNumberByDayName($end_date_day_name),
    ];

    $_COOKIE['rental_selected_pickup_selection_time'] = json_encode($selected_pickup_selection_time);
    setcookie('rental_selected_pickup_selection_time', json_encode($selected_pickup_selection_time), time() + RENTOPIAN_DATE_EXPIRE_TIME, "/", "", false, true);
}

function unset_delivery_times_data() {
    if (isset($_COOKIE['rental_selected_delivery_selection_time'])) {
        unset($_COOKIE['rental_selected_delivery_selection_time']);
        setcookie('rental_selected_delivery_selection_time', false, time() - (31556952), "/", "", false, false);
    }

    if (isset($_COOKIE['rental_selected_pickup_selection_time'])) {
        unset($_COOKIE['rental_selected_pickup_selection_time']);
        setcookie('rental_selected_pickup_selection_time', false, time() - (31556952), "/", "", false, false);
    }
}

/**
 * A simple stemming function to get singular and plural forms.
 * Note: This won't handle irregular plurals like 'goose'/'geese'.
 *
 * @param string $term The search term.
 * @return array An array containing the singular and plural versions.
 */
function rental_simple_stemmer($term) {
    $term = strtolower(trim($term));
    if (empty($term)) {
        return [];
    }

    $singular = '';
    $plural = '';

    // Check for words ending in 'ies', change to 'y' for singular
    if (preg_match('/ies$/', $term)) {
        $singular = preg_replace('/ies$/', 'y', $term);
        $plural = $term;
    } 

    // Check for words ending in 'es'
    elseif (preg_match('/es$/', $term)) {
        $singular = substr($term, 0, -2);
        $plural = $term;
    }

    // Check for words ending in 's'
    elseif (preg_match('/s$/', $term)) {
        $singular = substr($term, 0, -1);
        $plural = $term;
    } 
    // The word is likely already singular
    else {
        $singular = $term;
        $plural = $term . 's';
    }

    // Return unique values, in case singular and plural are the same
    return array_unique([$singular, $plural]);
}


function get_stemmed_search_result_ids( $search_term ) {
    global $wpdb;

    $search_matched_ids = [];

    if ( ! empty( $search_term ) ) {
        // Break into words, trim out any extra spaces (if no space, the whole phrase is added here)
        $raw_terms = array_filter( preg_split( '/\s+/', trim( $search_term ) ) );

        // Make sure we also include the entire phrase as one unit
        if ( count( $raw_terms ) > 1 ) {
            $raw_terms[] = trim( $search_term );
        }

        $all_variations = [];
        foreach ( array_unique( $raw_terms ) as $term ) {
            $vars = rental_simple_stemmer( $term );
            if ( !empty( $vars ) ) {
                $all_variations = array_merge( $all_variations, $vars );
            }
        }
        $all_variations = array_unique( $all_variations );

        if ( !empty( $all_variations ) ) {

            $rental_tables                 = isset( $rental_tables ) ? $rental_tables : [];
            $rental_product_relations      = $wpdb->prefix . ( $rental_tables['product_relations'] ?? '' );
            $left_join_post_meta_product   = "LEFT JOIN {$wpdb->postmeta} pm ON pm.post_id = product_rel.id AND pm.meta_key = '_stock_status'";
            $left_join_add_ons_post_meta_product = "LEFT JOIN {$wpdb->postmeta} pm_add_ons ON pm_add_ons.post_id = product_rel.id AND pm_add_ons.meta_key = '_rental_is_add_on'";

            $add_on_ids_to_exclude = get_add_on_ids($rental_product_relations, $left_join_post_meta_product, $left_join_add_ons_post_meta_product);
            $exclude_sql_clause = '';
            if ( !empty( $add_on_ids_to_exclude ) ) {
                $placeholders = implode( ', ', array_fill( 0, count( $add_on_ids_to_exclude ), '%d' ) );
                $exclude_sql_clause = $wpdb->prepare( "AND ID NOT IN ($placeholders)", $add_on_ids_to_exclude );
            }

            $like_clauses = [];
            foreach ( $all_variations as $var ) {
                $like_clauses[] = $wpdb->prepare( "post_title LIKE %s", '%' . $wpdb->esc_like( $var ) . '%' );
            }
            $like_sql = implode( ' OR ', $like_clauses );

            $search_matched_ids = $wpdb->get_col( "
                SELECT ID
                FROM {$wpdb->posts}
                WHERE post_type IN ('product', 'product_variation')
                  AND post_status = 'publish'
                  AND ( $like_sql )
                  $exclude_sql_clause
            " );
        }
    }

    return $search_matched_ids;
}


function rental_update_shipping_method() {
    if ( !isset($_POST['rental_shipping_method']) ) {
        wp_send_json_error( array('message' => 'Missing rental_shipping_method' ), 400);
    }

    $value = intval($_POST['rental_shipping_method'] );
    setcookie('rental_shipping_method', $value, time() + 3600, "/", "", false, true );
    $_COOKIE['rental_shipping_method'] = $value;

    wp_send_json_success( array( 'message' => 'Shipping method updated' ) );
}

// function rntp_build_checkout_dates_html(
//     $formatted_start_date = null,
//     $formatted_end_date   = null,
//     $rental_start_date    = '',
//     $rental_end_date      = '',
//     $date_format          = 'M j, g:i A',
//     $placeholder_text     = null
// ) {

//     if ($placeholder_text === null) {
//         $placeholder_text = __('No dates selected', 'rentopian-sync');
//     }

//     $start_display = '';
//     $end_display   = '';

//     // Start date (priority: formatted_start_date > rental_start_date parsed > raw)
//     if (isset($formatted_start_date) && $formatted_start_date) {
//         $start_display = $formatted_start_date;
//     } elseif (!empty($rental_start_date)) {
//         if ($rental_start_date) {
//             $ts = strtotime($rental_start_date);
//             if ($ts !== false) {
//                 $start_display = date($date_format, $ts);
//             } else {
//                 $start_display = $rental_start_date;
//             }
//         }
//     }

//     // End date (priority: formatted_end_date > rental_end_date parsed > raw)
//     if (isset($formatted_end_date) && $formatted_end_date) {
//         $end_display = $formatted_end_date;
//     } elseif (!empty($rental_end_date)) {
//         if ($rental_end_date) {
//             $ts = strtotime($rental_end_date);
//             if ($ts !== false) {
//                 $end_display = date($date_format, $ts);
//             } else {
//                 $end_display = $rental_end_date;
//             }
//         }
//     }

//     $checkout_dates_html = '<div id="rntp-rental-dates-summary-wrapper" class="rental-dates-summary-wrapper">';
//     $checkout_dates_html .= '<strong>' . esc_html(__('Rental Date(s)', 'rentopian-sync')) . '</strong>';

//     if ( ! get_option('rental_dates_on_checkout') && get_option('rental_form_layout') === 'in-cart' ) {
//         $checkout_dates_html .= '<span title="' . esc_attr__('Click here to change the dates!', 'rentopian-sync') . '" class="dates-edit dashicons dashicons-edit"></span>';
//     }

//     $checkout_dates_html .= '<ul class="rental-dates-summary">';

//     if ($start_display && $end_display) {
//         $checkout_dates_html .= '<li>' . esc_html($start_display) . ' &rarr; ' . esc_html($end_display) . '</li>';
//     } elseif ($start_display) {
//         $checkout_dates_html .= '<li>' . esc_html($start_display) . '</li>';
//     } elseif ($end_display) {
//         $checkout_dates_html .= '<li>' . esc_html($end_display) . '</li>';
//     } else {
//         // show placeholder if no dates selected
//         $checkout_dates_html .= '<li>' . esc_html($placeholder_text) . '</li>';
//     }

//     if ( ! get_option('rental_hide_zip') ) {

//         $dates_on_checkout = ( get_option('rental_dates_on_checkout', 0) == 1 && get_option('rental_allow_overbook', 0) == 1 ) ? 1 : 0;

//         $zip = '';

//         if ( (!isset($_COOKIE['rental_form_filled']) || empty($_COOKIE['rental_form_filled'])) && $dates_on_checkout == 1 ) {
//             $zip = '';
//         } else {
//             $decrypted_rental_zip = '';
//             if (isset($_COOKIE['rental_zip']) && $_COOKIE['rental_zip']) {
//                 $decrypted_rental_zip = decrypt_data($_COOKIE['rental_zip'], get_option('rental_encryption_key'));
//             }

//             $zip = $decrypted_rental_zip ? $decrypted_rental_zip : '';
//         }

//         $checkout_dates_html .= '<li><strong>' . esc_html__('ZIP Code', 'rentopian-sync') . '</strong> ' . esc_html($zip) . '</li>';
//     }

//     $checkout_dates_html .= '</ul></div>';

//     return $checkout_dates_html;
// }