<?php
/**
 * Plugin Name: Engage for WooCommerce
 * Plugin URI: https://docs.engage.zubi.ai/platforms/woocommerce
 * Version: 2023.9.2
 * Author: zubiai
 * Author URI: https://zubi.ai/
 * Description: AI-powered ecommerce optimization for WooCommerce. Automated product recommendations, event tracking, pixels, Google Analytics, Customer Segments and Customer Analytics via Engage
 * Copyright 2021-2023 ZubiLabs AB
 * License: GPL3
 */
// Exit if accessed directly
if (!defined('ABSPATH'))
{
    exit;
}
// Exit if WooCommerce is not active
if (!in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins'))))
{
    exit;
}
if (!defined('ZUBI_HOME_DIR'))
{
    define('ZUBI_HOME_DIR', plugin_dir_path(__FILE__));
}
global $rcid;
$rcid = uniqid();
global $positions;
$positions = array(
    'woocommerce_before_single_product',
    'woocommerce_before_single_product_summary',
    'woocommerce_product_thumbnails',
    'woocommerce_single_product_summary',
    'woocommerce_before_add_to_cart_form',
    'woocommerce_before_variations_form',
    'woocommerce_before_add_to_cart_button',
    'woocommerce_before_single_variation',
    'woocommerce_single_variation',
    'woocommerce_after_single_variation',
    'woocommerce_after_add_to_cart_button',
    'woocommerce_after_variations_form',
    'woocommerce_after_add_to_cart_form',
    'woocommerce_product_meta_start',
    'woocommerce_product_meta_end',
    'woocommerce_share',
    'woocommerce_after_single_product_summary',
    'woocommerce_after_single_product'
);

require_once plugin_dir_path(__FILE__) . 'includes/shortcode.php';

class eCommerceByZubi
{
    /**
     * Constructor
     */
    public function __construct()
    {
        // Plugin Details
        $this->plugin = new stdClass;
        $this
            ->plugin->name = 'engage-by-zubi'; // Plugin Folder
        $this
            ->plugin->displayName = 'Engage for WooCommerce'; // Plugin Name
        $this
            ->plugin->version = '2023.9.2';
        $this
            ->plugin->folder = plugin_dir_path(__FILE__);
        $this
            ->plugin->url = plugin_dir_url(__FILE__);
        $this
            ->plugin->db_welcome_dismissed_key = $this
            ->plugin->name . '_welcome_dismissed_key';



        // Hooks
        add_action('admin_init', array(
            $this,
            'registerSettings'
        ));

        add_action('wp_ajax_nopriv_zl_get_cart', array(
            $this,
            'zl_get_cart'
        ));

        add_action('wp_ajax_zl_get_cart', array(
            $this,
            'zl_get_cart'
        ));


        // add_action( 'admin_enqueue_scripts', array($this,'add_zubi_js_file_to_admin'),'',1 );

        add_action( 'woocommerce_before_checkout_form',  array(
            $this,
            'zl_checkout_started'
        ));

        add_action('admin_menu', array(
            $this,
            'adminPanelsAndMetaBoxes'
        ));
        add_action('admin_notices', array(
            $this,
            'dashboardNotices'
        ));
        add_action('wp_ajax_' . $this
            ->plugin->name . '_dismiss_dashboard_notices', array(
            $this,
            'dismissDashboardNotices'
        ));


        $tkey = esc_html(wp_unslash(get_option('ebz_tracker_key')));

        if($tkey != ""){

			// Shortcodes
			add_shortcode('zlt_rec', array(
				$this,
				'ebz_recommendation'
			));
			add_shortcode('zlt', array(
				$this,
				'ebz_recommendation'
			));
			add_shortcode('zlt_default', array(
				$this,
				'ebz_default_products'
			));

            // Frontend Hooks
            // add_action('wp_footer', array( $this, 'woo_add_to_cart' ));
            add_action('wp_enqueue_scripts', array(
                $this,
                'zubi_scripts'
            ) , -99999);


            // add_action( 'woocommerce_add_to_cart', array($this, 'zl_add_to_cart_event'), 40, 4 );
            add_action('woocommerce_before_single_product', array(
                $this,
                'productPages'
            ));

            add_action('woocommerce_thankyou', array(
                $this,
                'customReadOrder'
            ));
            add_action('wp_ajax_nopriv_zl_ajax_product', array(
                $this,
                'zl_ajax_get_product'
            ));
            add_action('wp_ajax_zl_ajax_product', array(
                $this,
                'zl_ajax_get_product'
            ));
            add_action('woocommerce_after_shop_loop_item', array(
                $this,
                'custom_products_displayed'
            ));

            /**
             * Product page placements
             */
            global $positions;
            foreach ($positions as $value)
            {
                add_action($value, array(
                    $this,
                    'ebz_' . $value
                ));
            }

            //Deactivation hook
            register_deactivation_hook(__FILE__, 'my_plugin_deactivation');
            function my_plugin_deactivation()
            {

            	global $positions;
            	foreach ($positions as $value)
            	{
    	            delete_option('ebz_' . $value);
    	        }

		delete_option('ebz_tracker_key');
		delete_option('ebz_user_token');

		delete_option('etKey');
		delete_option('euKey');

            }

        }
        /** codingkart action hook start */
        add_action('wp_ajax_engage_connection', array($this, 'engage_connection'));
        add_action('wp_ajax_engage_dashboard',array($this, 'engage_dashboard'));
        add_action('wp_ajax_engage_product_rec_submit',array($this, 'engage_product_rec_submit'));
        add_action('wp_ajax_engage_update_legacy_rec',array($this, 'engage_update_legacy_rec'));
        /** codingkart action hook end */

    }

    /**
     * codingkart : make connection with engage
     */
    function engage_connection(){
        $key = $_POST['token_key'];

        $exploded = explode('//', site_url());
        $store_id = end($exploded);

        $url  = 'https://api.zubi.ai/i/connect/plugin';
         $body = array(
                '_token' => $key,
                'platform' => "woo",
                'store_id' => $store_id,
            );

        $args = array(
            'method'      => 'POST',
            'body'        => ($body),
        );
        $response = wp_remote_post( $url, $args );
        if ( !is_wp_error( $response ) ) {
            $body = json_decode(wp_remote_retrieve_body( $response ));
            if($body->status == "success"){
                $user_id = $body->user_id;
                $tk_key = $body->tk_key;
                $uk_key = $body->uk_key;
                update_option('ebz_user_token', esc_html(wp_unslash($uk_key)));
                update_option('ebz_tracker_key', esc_html(wp_unslash($tk_key)));

                // Not using the temp key holders may cause error in connection if user aborts..
                //update_option('euKey', sanitize_text_field($_REQUEST['ebz_user_token']));
                //update_option('etKey', sanitize_text_field($_REQUEST['ebz_tracker_key']));

                $store_url = site_url();
                $endpoint = '/wc-auth/v1/authorize';
                $params = ['app_name' => 'engage by zubi', 'scope' => 'read', 'user_id' => $user_id , 'return_url' => site_url() . '/wp-admin/admin.php?page=engage-by-zubi', 'callback_url' => "https://api.zubi.ai/i/callback/nsRPyZZGfrQWx5eAwVgG3d/wc"];
                $params = http_build_query($params);
                $redirect_to_auth = $store_url . $endpoint . '?' . $params;
                //header("location:" . $redirect_to_auth);

                $data = array('status' => 1, 'body' => $body , 'message' => "Verified Key successfully. wait..", 'redirect_to' => $redirect_to_auth);
            }else{
                $data = array('status' => 0, 'body'=> $body , 'message' => "Unable to verify key.");
            }
        }else{
            $data = array('status' => 0, 'message' => 'Something went wrong. Please refresh the page.');
        }
        wp_send_json($data );
    }

    /**
     * codingkart : Show engage welcome page
     */
    function engage_dashboard(){

        $key = $_POST['token_key'];
        $url  = 'https://api.zubi.ai/i/plugin/woocommerce';
         $body = array(
                '_token' => $key,
                'path' => 'plugin_placements'
            );

        $args = array(
            'method'      => 'POST',
            'body'        => ($body),
        );
        $response = wp_remote_post( $url, $args );
        if ( !is_wp_error( $response ) && wp_remote_retrieve_response_code( $response ) == 200) {
            $body = json_decode(wp_remote_retrieve_body( $response ));
            $in_trial = $body->in_trial;
            $blocks = $body->blocks;

            global $positions;
        		$count = 1;
        		foreach ($positions as $value) {
        			$v = get_option('ebz_' . $value);
        			foreach ($v as $k => $setting) {
        				if ($setting != '' && strpos($setting, 'data-id') === false) {
        					$blocks[] = (object) array(
        						'option' => 'ebz_' . $value,
        						'key' => $k,
        						'shortcode' => $setting,
        						'position' => $value,
        						'block_id' => 'legacy_' . $count,
        						'block_name' => 'Legacy ' . $count,
        						'legacy' => 'legacy',
        					);
        					$count = $count + 1;
        				}
        			}
        		}

            $zubi_tab_lists_html = $this->get_zubi_tab_lists($blocks);
            $zubi_tab_data = $this->get_zubi_tab_containers($blocks);
            $data = array('status'=>1 ,'in_trial' => $in_trial, 'blocks' => $blocks, 'zubi_tab_titles'=>$zubi_tab_lists_html, 'zubi_tab_containers'=>$zubi_tab_data['tab_containers_html'], 'block_ids'=>$zubi_tab_data['block_ids']);
        }else{
            $data = array('status'=>0, 'response' => $response, 'message'=>'Something went wrong. Please refresh the page.');
        }
        wp_send_json($data);
    }

     /**
     * codingkart : Save product recommendation hook and shortcode
     *
     * Alex: Implemented array for multiple blocks on same hook
     */
    function engage_product_rec_submit(){
        global $positions;
        $block_id = $_POST['zubi_block_id']; // ['id_1', 'id_2']
        $hook = $_POST['zubi_placement_hook']; // ['woo_before...']
        $shortcode = $_POST['zubi_shortcode']; // ['[zlt_default ...]']
        $data = array('status'=>false);
        if(isset($block_id) && !empty($block_id) && isset($hook) && !empty($hook) && isset($shortcode) && !empty($shortcode) ){
          for($i=0; $i< count($block_id); $i++) {

              $current_block = $block_id[$i];
              $current_hook = $hook[$i];
              $current_shortcode = $shortcode[$i];
              update_option($current_block.'_hook', esc_html(wp_unslash($current_hook)));
              update_option($current_block.'_shortcode', esc_html(wp_unslash($current_shortcode)));

              foreach ($positions as $position) {
                update_option('ebz_' . $position . '_default', ''); // NOT IN USE

                $op_name = get_option('ebz_' . $position . '_name');
                // IMPORTANT - Ensure option is array
                if (!is_array($op_name)) { $op_name = array(); }
                // Backwards compatibility - Not needed
                /*foreach ($op_name as $key => $value) {
                  if (!in_array($key, $block_id) && $value != '') {
                      $op_name['legacy'] = $value;
                      unset($op_name[$key]);
                  }
                  if ( $value == '') {
                    unset($op_name[$key]);
                  }
                }*/

                $op = get_option('ebz_' . $position);
                // IMPORTANT - Ensure option is array
                if (!is_array($op)) { $op = array(); }
                // Backwards compatibility - Not needed
                /* foreach ($op as $key => $value) {
                  if (!in_array($key, $block_id) && $value != '') {
                      $op['legacy'] = $value;
                      unset($op[$key]);
                  }
                  if ( $value == '') {
                    unset($op_name[$key]);
                  }
                }*/

                if ($current_hook == $position) {
                  $op_name[$current_block] = isset($current_shortcode) ? $current_shortcode : '';
                  update_option('ebz_' . $position . '_name', $op_name);

                  $op[$current_block] = isset($current_shortcode) ? $current_shortcode : '';
                  update_option('ebz_' . $position, $op);
                } else {
                  $op_name[$current_block] = '';
                  update_option('ebz_' . $position . '_name', $op_name);

                  $op[$current_block] = '';
                  update_option('ebz_' . $position, $op);
                }


              }

            }
            $data['status'] = true;
            $data['block_ids'] = $block_id;

          }

          wp_send_json($data);
    }

    /**
    * Alex: Remove legacy recommendations
    *
    */
   function engage_update_legacy_rec(){
     $option_id = $_POST['zubi_block_name'];
     $block_id = $_POST['zubi_block_id'];
     $shortcode = $_POST['zubi_shortcode'];
     $data = array('status'=>false);
     if(isset($option_id) && !empty($option_id) && isset($block_id) && !empty($block_id) && isset($shortcode) && !empty($shortcode) ){
       for($i=0; $i< count($block_id); $i++) {
         $current_block = $block_id[$i];
         $current_option_id = $option_id[$i];
         $current_shortcode = $shortcode[$i];
         if (($current_shortcode == '' || strpos($setting, 'data-id') === false )&& strpos($current_option_id, 'ebz_') !== false) {
           $op = get_option($current_option_id);
           $op[$current_block] = $current_shortcode ;
           update_option($current_option_id, $op);

           $data = array('status'=>true);
         }
       }
     }

     wp_send_json($data);
   }


    /**
     * codingkart : get tab lists html
     */
    function get_zubi_tab_lists($blocks){
        $tab_lists_html = '';
        $i = 0;
        foreach($blocks as $key=>$value){
            $active = "";
            if ($key === array_key_first($blocks)){
                $active = "active";
            }
            $tab_lists_html .= '<li><a class="'.$active.'" href="javascript:void(0);" zubi-tab-id="'.$value->block_id.'">'.$value->block_name.'</a></li>' ;
            $i++;
        }
        return $tab_lists_html;

    }

    /**
     * codingkart : get tab containers html
     */
    function get_zubi_tab_containers($blocks){
        $tab_containers_html = "";
        $block_ids = array();
        $i = 0;
        $data = array();
        foreach($blocks as $key=>$value){

            $active = "";
            if ($key === array_key_first($blocks)){
                $active = "active";
            }
            $block_ids[] = $value->block_id;

            if (isset($value->legacy)) {
              $short_placeholder = $value->shortcode;
            } else {
              $short_placeholder = "[zlt_default data-id='".$value->block_id."']";
            }
            $block_hook = !empty(get_option($value->block_id.'_hook')) ? get_option($value->block_id.'_hook') : '';
            $block_shortcode = !empty(get_option($value->block_id.'_shortcode')) ? get_option($value->block_id.'_shortcode') : $short_placeholder;

            $options = $this->get_product_placement_options($block_hook);

            $tab_params = array(
                'i' => $i,
                'active'=> $active,
                'block_data' => $value,
                'block_hook' => $block_hook,
                'options' => $options,
                'shortcode_placeholder' => $short_placeholder,
                'block_shortcode' => $block_shortcode,
                'legacy' => isset($value->legacy) ? true : false

            );
            $tab_containers_html .= $this->get_tab_block_html($tab_params);
            $i++;
        }
        $data['block_ids'] = $block_ids;
        $data['tab_containers_html'] = $tab_containers_html;
        return $data;
    }

    /**
     * codingkart : get product placement options
     */
    function get_product_placement_options($block_hook){
        $options = '<optgroup label="product Page">';
        global $positions;
        foreach($positions as $key1=>$value1){

            if($value1 == $block_hook){
                $options .= '<option value="'.$value1.'" selected> '.ucfirst(str_replace("_", " ", $value1)).'</option>';
            }else{
                $options .= '<option value="'.$value1.'"> '.ucfirst(str_replace("_", " ", $value1)).'</option>';
            }
        }
        $options .= '</optgroup>';
        return $options;
    }

    /**
     * codingkart : get tab block's html
     */
    function get_tab_block_html($param){
        $block = $param['block_data'];
        $i = $param['i'];
        $block_hook = $param['block_hook'];
        $block_shortcode = $param['block_shortcode'];
        $hidden = '';
        if($block_hook){
            $hidden .= '<div class="im_the_zl_parent"><input class="input_hidden_zl" type="hidden" name="'.$block_hook.'['.$i.']" value="'.$block_shortcode.'"></div>';
        }
        if ($param['legacy']) {
          return '<div class="zubi-tab-contant '.$param['active'].'" id="'.$block->block_id.'">
                          <h3>'.$block->block_name.'</h3>
                          <div class="zubi-pro-page-block">
                              <h4>Shortcode</h4>
                              <p>Deploy this recommendation block anywhere using the shortcode</p>
                              <div class="zubi-pro-page-form zubi-pro-shortcode-form">
                                  <input type="text" name="zubi_shortcode['.$i.']" class="input-field-zubi shortcode-input-field" placeholder="'.$param['shortcode_placeholder'].'" value="'.$block_shortcode.'"/>
                                  <button class="shortcode-copy-zubi" type="button">Copy</button>
                              </div>
                          </div>
                          <input type="hidden" name="zubi_block_name['.$i.']" value="'.$block->option.'">
                          <input type="hidden" name="zubi_block_id['.$i.']" value="'.$block->key.'">
                          <div class="zubi-pro-page-block">
                              <div class="zubi-pro-block-action">
                              <button class="zubi-pro-block-save zubi-submit-legacy" type="button">Save</button>
                              <button class="zubi-pro-block-remove zubi-remove-legacy" type="button" style="margin: 0;">Remove</button>
                              </div>
                          </div>
                  </div>';
        } else {
          return '<div class="zubi-tab-contant '.$param['active'].'" id="'.$block->block_id.'">
                          <h3>'.$block->block_name.'</h3>
                          <div class="zubi-pro-page-block">
                              <h4>Placement</h4>
                              <p>Decide where to place the recommendation. Or use the shortcode below to manually place the recommendation.</p>
                              <div class="zubi-pro-page-form">
                                  <select class="select-field-zubi" name="zubi_placement_hook['.$i.']" data-id="'.$i.'">
                                      <option value="none">Do not display</option>
                                      '.$param['options'].'
                                  </select>
                                  '.$hidden.'
                              </div>
                          </div>
                          <div class="zubi-pro-page-block">
                              <h4>Shortcode</h4>
                              <p>Deploy this recommendation block anywhere using the shortcode</p>
                              <div class="zubi-pro-page-form zubi-pro-shortcode-form">
                                  <input type="text" name="zubi_shortcode['.$i.']" class="input-field-zubi shortcode-input-field" placeholder="'.$param['shortcode_placeholder'].'" value="'.$block_shortcode.'"/>
                                  <button class="shortcode-copy-zubi" type="button">Copy</button>
                              </div>
                          </div>
                          <input type="hidden" name="zubi_block_name['.$i.']" value="'.$block->block_name.'">
                          <input type="hidden" name="zubi_block_id['.$i.']" value="'.$block->block_id.'">
                          <div class="zubi-pro-page-block">
                              <div class="zubi-pro-block-action">
                                  <button class="zubi-pro-block-save zubi-submit" type="button">Save</button>
                                  <button class="zubi-pro-block-remove zubi-remove" type="button">Clear</button>
                              </div>
                          </div>
                  </div>';
        }

    }

     /**
     * Show relevant notices for the plugin
     */
    function dashboardNotices()
    {
        global $pagenow;
        if (!get_option($this
            ->plugin
            ->db_welcome_dismissed_key))
        {
            if (!($pagenow == 'options-general.php' && isset($_GET['page']) && $_GET['page'] == 'engage-by-zubi'))
            {
                $setting_page = admin_url('options-general.php?page=' . $this
                    ->plugin
                    ->name);
                // load the notices view
                include_once ($this
                    ->plugin->folder . '/views/dashboard-notices.php');
            }
        }
    }
    /**
     * Dismiss the welcome notice for the plugin
     */
    function dismissDashboardNotices()
    {
        check_ajax_referer($this
            ->plugin->name . '-nonce', 'nonce');
        // user has dismissed the welcome notice
        update_option($this
            ->plugin->db_welcome_dismissed_key, 1);
        exit;
    }
    /**
     * Register Settings
     */
    function registerSettings()
    {

        register_setting($this
            ->plugin->name, 'ebz_use_square_img', 'trim');
        if (get_option('ebz_use_square_img') != 0)
        {
            update_option('ebz_use_square_img', 1);
        }

        register_setting($this
            ->plugin->name, 'ebz_user_token', 'trim');
        register_setting($this
            ->plugin->name, 'ebz_tracker_key', 'trim');
        register_setting($this
            ->plugin->name, 'ebz_store_name', 'trim');
        register_setting($this
            ->plugin->name, 'ebz_is_disabled', 'trim');
        register_setting($this
            ->plugin->name, 'ebz_is_debug', 'trim');
        register_setting($this
            ->plugin->name, 'ebz_img_size', 'trim');
        register_setting($this
            ->plugin->name, 'euKey', 'trim');
        register_setting($this
            ->plugin->name, 'etKey', 'trim');

        if (empty(get_option('ebz_is_debug')))
        {
            update_option('ebz_is_debug', false);
        }
        if (empty(get_option('ebz_is_disabled')))
        {
            update_option('ebz_is_disabled', false);
        }
        if (empty(get_option('ebz_img_size')))
        {
            update_option('ebz_img_size', 'full');
        }


        register_setting($this
            ->plugin->name, 'ebz_prod_rec_position', 'trim');
        register_setting($this
            ->plugin->name, 'ebz_cat_rec_position', 'trim');
        register_setting($this
            ->plugin->name, 'ebz_start_rec_position', 'trim');
        register_setting($this
            ->plugin->name, 'ebz_checkout_rec_position', 'trim');
        register_setting($this
            ->plugin->name, 'ebz_search_rec_position', 'trim');
        register_setting($this
            ->plugin->name, 'ebz_cart_rec_position', 'trim');
        register_setting($this
            ->plugin->name, 'ebz_minicart_rec_position', 'trim');

        if (empty(get_option('ebz_prod_rec_position')))
        {
            update_option('ebz_prod_rec_position', 'none');
        }
        if (empty(get_option('ebz_cat_rec_position')))
        {
            update_option('ebz_cat_rec_position', 'none');
        }
        if (empty(get_option('ebz_start_rec_position')))
        {
            update_option('ebz_start_rec_position', 'none');
        }
        if (empty(get_option('ebz_checkout_rec_position')))
        {
            update_option('ebz_checkout_rec_position', 'none');
        }
        if (empty(get_option('ebz_search_rec_position')))
        {
            update_option('ebz_search_rec_position', 'none');
        }
        if (empty(get_option('ebz_cart_rec_position')))
        {
            update_option('ebz_cart_rec_position', 'none');
        }
        if (empty(get_option('ebz_minicart_rec_position')))
        {
            update_option('ebz_minicart_rec_position', 'none');
        }

        /**
         * Product page placements
         */
        global $positions;
        $defaults = array(
            'type' => 'array',
            'group' => $this
                ->plugin->name,
            'description' => '',
            'sanitize_callback' => null,
            'show_in_rest' => false,
        );

        foreach ($positions as $value)
        {
            register_setting($this
                ->plugin->name, 'ebz_' . $value, $defaults);
            register_setting($this
                ->plugin->name, 'ebz_' . $value . '_name', $defaults);
            register_setting($this
                ->plugin->name, 'ebz_' . $value . '_default', $defaults);
            if (empty(get_option('ebz_' . $value)))
            {
                update_option('ebz_' . $value . '_name', '');
            }
            if (empty(get_option('ebz_' . $value)))
            {
                update_option('ebz_' . $value, '');
            }
            if (empty(get_option('ebz_' . $value . '_default')))
            {
                update_option('ebz_' . $value . '_default', '');
            }
        }

        // Deprecated in v1.3.0
        register_setting($this
            ->plugin->name, 'ebz_css_prod_rec_display', 'trim');
        register_setting($this
            ->plugin->name, 'ebz_css_cat_rec_display', 'trim');
        register_setting($this
            ->plugin->name, 'ebz_css_start_rec_display', 'trim');
        register_setting($this
            ->plugin->name, 'ebz_css_checkout_rec_display', 'trim');
        register_setting($this
            ->plugin->name, 'ebz_css_search_rec_display', 'trim');
        register_setting($this
            ->plugin->name, 'ebz_css_cart_rec_display', 'trim');
        register_setting($this
            ->plugin->name, 'ebz_css_minicart_rec_display', 'trim');

        // Deprecated in v1.3.0
        if (empty(get_option('ebz_css_prod_rec_display')))
        {
            update_option('ebz_css_prod_rec_display', 'edt');
        }
        if (empty(get_option('ebz_css_cat_rec_display')))
        {
            update_option('ebz_css_cat_rec_display', 'edt');
        }
        if (empty(get_option('ebz_css_start_rec_display')))
        {
            update_option('ebz_css_start_rec_display', 'edt');
        }
        if (empty(get_option('ebz_css_checkout_rec_display')))
        {
            update_option('ebz_css_checkout_rec_display', 'edt');
        }
        if (empty(get_option('ebz_css_search_rec_display')))
        {
            update_option('ebz_css_search_rec_display', 'edt');
        }
        if (empty(get_option('ebz_css_cart_rec_display')))
        {
            update_option('ebz_css_cart_rec_display', 'edt');
        }
        if (empty(get_option('ebz_css_minicart_rec_display')))
        {
            update_option('ebz_css_minicart_rec_display', 'edt');
        }

        if (file_exists(ZUBI_HOME_DIR . 'keys.txt'))
        {
            $str = file_get_contents(ZUBI_HOME_DIR . 'keys.txt');
            $envarr = explode(PHP_EOL, $str);
            $envvar = implode('&', $envarr);
            $arr = array();
            $envv = array();
            parse_str($envvar, $arr);
            foreach ($arr as $k => $e)
            {
                $envv[strtolower($k) ] = $e;
            }

            if (empty(esc_html(wp_unslash(get_option('ebz_user_token')))))
            {
                update_option('ebz_user_token', esc_html(wp_unslash($envv['ebz_user_token'])));
            }
            if (empty(esc_html(wp_unslash(get_option('ebz_tracker_key')))))
            {
                update_option('ebz_tracker_key', esc_html(wp_unslash($envv['ebz_tracker_key'])));
            }
        }
    }


    function zl_get_cart(){
    /**
       * Zubi Cart Tracker
       */
        try{

            $cart = WC()->cart;

            if(!is_null($cart)){

                if( ! $cart->is_empty()  ) {
                    $all_in_cart = [];
                    $all_in_cart_arr = [];
                    $json_main = new stdClass();
                    $object_Mapper = new stdClass();

                    $cart = WC()->cart->get_cart();
                    $total = WC()->cart->total;
                    $total_tax = WC()->cart->get_taxes_total();
                    $shipping = WC()->cart->get_shipping_total();
                    $discounts = WC()->cart->get_discount_total();
                    $coupons = WC()->cart->get_coupons();
                    if(isset($coupons)){
                        if(isset($coupons[0])) {
                            $json_main->coupon  = $coupons[0];
                        }
                    }
                    $currency = get_option('woocommerce_currency');
                    $subtotal = WC()->cart->get_displayed_subtotal();

                    $json_main->total  = floatval($total);
                    $json_main->subtotal  = floatval($subtotal);
                    $json_main->shipping  = floatval($shipping);
                    $json_main->tax  = floatval($total_tax);
                    $json_main->discount  = floatval($discounts);

                    $json_main->currency  = $currency;


                    foreach( $cart as $cart_item ){

                      $id = $cart_item['product_id'];
                      $product = wc_get_product( $id );
                      $quant = $cart_item['quantity'];
                      $ttl = $product->get_title();
                      $price = floatval($product->get_price());
                      $sku = $product->get_sku();

                      if( $cart_item['variation_id'] ){
                         $variation_id = wc_get_product($cart_item['variation_id']);
                      }else{
                         $variation_id = wc_get_product($id);
                      }

                      $variation_id = strval($variation_id->get_id());
                      $onsale = false;

                      if( $product->is_on_sale() )
                        $onsale = true;

                      $url = get_permalink( $id );
                      $image_url = get_the_post_thumbnail_url($id);
                      $prod_data = new stdClass();
                      $prod_data->product_id  = $id;
                      $prod_data->quantity  = $quant;
                      $prod_data->name  = $ttl;
                      $prod_data->price  = floatval($price);
                      $prod_data->variation_id  = $variation_id;
                      $prod_data->currency  = $currency;
                      $prod_data->on_sale  = $onsale;
                      $prod_data->url  = $url;
                      $prod_data->image_url  = $image_url;
                      $object_Mapper->$id = $prod_data;
                      array_push($all_in_cart_arr, $prod_data );

                    }

                    echo  json_encode(array( 'zlcartProdsArray' => $all_in_cart_arr ,  'zlcartProdsMap' =>  $object_Mapper , 'zlCartDetails' => $json_main ));
                }else{
                    echo "no_els";
                }
            }
        }catch(Exception $e){
            wp_die();
        }

        wp_die();

    }


    function ebz_default_products($atts)
    {
        try
        {
            if (is_admin() || is_feed() || is_robots() || is_trackback())
            {
                return;
            }
            if (get_option('ebz_is_debug'))
            {
                $debug = True;
		            var_dump("before merge: ");
		            var_dump($atts);
            }
            else
            {
                $debug = False;
            }

            $zString = "";
            for ($i = 0;$i < sizeof($atts);$i++)
            {
                if (isset($atts[$i])) {
                	if (strpos($atts[$i], '=') !== false) {
	                	$zString .= "|".$atts[$i] . " ";
	                } else {
	                	$zString .= $atts[$i] . " ";
	                }
                }
            }

      			if (isset($zString)) {
      				$zString = str_replace("'", "", $zString);
      				$atts[0] = $zString;
      		  }

            $zString = explode("|",htmlentities($zString));
            $zString = array_filter($zString);
            $zString = array_values($zString);

    		    for ($i = 0;$i < sizeof($zString);$i++){
              if (strpos($zString[$i], '=') !== false) {
      			    list($k, $v) = explode('=', $zString[$i]);
      			    $attrs2[ $k ] = trim($v);
              }
    		    }

            for ($i = 0;$i < sizeof($atts);$i++){
              unset($atts[$i]);
            }

		        if(isset($attrs2)){
			        $atts = array_merge($atts,$attrs2);
		        }

    		    if(isset($atts[0])) {
              unset($atts[0]);
            }

            $atts = array_merge(array(
                //'limit' => "4", Managed backend
                //'columns' => "4",
                "data-mprods"=>"4",
                "data-prods"=>"4",
                "data-mslide"=>"-1",
                "data-slide"=>"-1",
		            "a_p_h_display"=>"none",
            ) , (array)$atts);

            $zString = "";
            for ($i = 0;$i < sizeof($atts);$i++)
            {
                if (isset($atts[$i])) $zString .= $atts[$i] . " ";
            }
            if (strstr($zString, "header=") != false)
            {
                $zString = str_replace('header=', ',,header=', $zString);
            }
            if (strstr($zString, "model=") != false)
            {
                $zString = str_replace('model=', ',,model=', $zString);
            }
            if (isset($zString))
            {
                $zString = str_replace("'", "", $zString);
                $atts[0] = $zString;
            }
            $zString = explode(",,",htmlentities($zString));
            $zString = array_filter($zString);
            $zString = array_values($zString);
            for ($i = 0;$i < sizeof($zString);$i++){
              if (strpos($zString[$i], '=') !== false) {
                list($k, $v) = explode('=', $zString[$i]);
                $attrs2[ $k ] = $v;
              }
            }
            for ($i = 0;$i < sizeof($atts);$i++){
                unset($atts[$i]);
            }
            if(isset($attrs2)){
                $atts = array_merge($atts,$attrs2);
            }
            if(isset($atts[0]))
                unset($atts[0]);

        		if ($debug) {
        			var_dump($atts);
        		}

            /**
             * Get the current product or cart content
             * If nothing exists, return empty
             */

            global $product;

            $product_id = '';
            if (isset($product))
            {
                $product_id = $product->get_id();
            }
            $cart = WC()->cart;

            if(!is_null($cart)){
                if ( ! $cart->is_empty() )
                {
                    $items = WC()->cart->get_cart();
                    $product_ids = [];
                    foreach ($items as $item => $values)
                    {
                        $_product = wc_get_product($values['data']->get_id());
                        if ($values['variation_id'] > 0)
                        {
                            $product_ids[] = $_product->get_parent_id();
                        }
                        else
                        {
                            $product_ids[] = $_product->get_id();
                        }
                    }
                    $product_id_string = implode(",", $product_ids);
                    if (sizeof($product_ids) > 0 && strlen($product_id) > 0)
                    {
                        $product_id .= ',' . $product_id_string;
                    }
                    elseif (sizeof($product_ids) > 0)
                    {
                        $product_id = $product_id_string;
                    }
                }
            }
            global $rcid;
            $zltid = uniqid('z');

      $zl_origin_url = '';
	    try {
				global $wp;
        $protocol = 'https://';
  			if (isset($_SERVER['HTTPS']) &&
  				($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||
  				isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
  				$_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
  			  $protocol = 'https://';
  			}
  			else {
  			  $protocol = 'http://';
  			}
				$zl_origin_url = $protocol . $_SERVER['SERVER_NAME'] . add_query_arg( home_url( $wp->request ), NULL );
			} catch(\Exception $e) {
				$zl_origin_url = '';
			}
            $url = 'https://realtime-dot-solutionsone-211314.appspot.com/v1/recommendations/product-ids';
            $url_token = esc_html(wp_unslash(get_option('ebz_user_token')));

            $model_override = isset($atts['model']) ? '"mid": "'.$atts['model'].'",' : '';
            $cnt_override = isset($atts['limit']) && $atts['limit'] != '' ? '"cnt": "'.$atts['limit'].'",' : '';
            $block_override = isset($atts['data-id']) ? '"tid": "'.$atts['data-id'].'",' : '';
            $device_check = wp_is_mobile() ? '"device": "mobile",' : '"device": "desktop",';

	    	$uid_cookie = '';
			try {
			  $uid_cookie = isset($_COOKIE['-zl_udi']) ? '"uid": "'.$_COOKIE['-zl_udi'].'",' : '';
			} catch(\Exception $e) {
			  $uid_cookie = '';
			}

            // Request parameters as string
            $zbody = '{
              '.$block_override.'
              '.$model_override.'
              '.$device_check.'
			        '.$uid_cookie.'
              "origin": "wc",
              '.$cnt_override.'
              "rec_key": "'.$rcid.'",
              "_token": "'.$url_token.'",
              "pid": "'.$product_id.'",
              "zltid": "'.$zltid.'",
			        "url": "'.$zl_origin_url.'"
            }';

            $zData = array(
                'headers' => array(
                    'Content-Type' => 'application/json; charset=utf-8',
                    'Cache-Control' => 'no-store, no-cache, must-revalidate, max-age=0'
                ) ,
                'method' => 'POST',
                'timeout' => 45,
                'redirection' => 5,
                'httpversion' => '1.0',
                'blocking' => true,
                'body' => $zbody,
                'cookies' => array()
            );


            // Make the request to Engage
            $response = wp_remote_post($url,$zData);
            $bodyArray = (json_decode($response["body"], true));
            if(!empty($bodyArray) && !array_key_exists('message', $bodyArray)){

              // Expose the recKey
              echo '<div class="recKey" data-rec="' . $rcid . '"></div><script>zlt.track("ZL Rec Key", {"rec_key" : "' . $rcid . '"});</script>';

              // Retrieve the products
              $products_received = $bodyArray['products'];

              // Get Settings
              $rec_settings = isset($bodyArray['settings']) ? $bodyArray['settings'] : array();
              // $rec_settings = array_key_exists('settings', $bodyArray) ? $bodyArray['settings'] : NULL;

              try {
        				if (isset($rec_settings['desktop']['title_settings']['title'])) {
        					$rec_settings['title'] = $rec_settings['desktop']['title_settings']['title'];
        				}
              } catch(\Exception $e) {}

              try {
        				if (isset($rec_settings['version']) && $rec_settings['version'] == 'v0' && $atts['data-mslide'] == '-1') {
        					$atts['data-mslide'] = "2";
        				}
              } catch(\Exception $e) {}

              try {
        				if (isset($rec_settings['version']) && $rec_settings['version'] == 'v0' && $atts['data-slide'] == '-1') {
        					$atts['data-slide'] = "0";
        				}
              } catch(\Exception $e) {}

              // var_dump($atts);
              // Create a new block instance
              $shortcode = new ebz_default_theme($atts, $zltid);

              // Deploy slider
              echo $shortcode->get_slider($atts, $rec_settings);

              // Return the recommendations
              return $shortcode->get_content($products_received, $rec_settings);

            }else{
                return;
            }

        }
        catch(\Exception $e)
        {
            return;
        }
    }


    function ebz_woocommerce_before_single_product()
    {
        $ebzp = get_option('ebz_woocommerce_before_single_product');
        try
        {
            if ( is_array($ebzp) || is_object($ebzp)  )
            {
                foreach ($ebzp as $value)
                {
                    //var_dump($value);
                    echo do_shortcode($value);
                }
            }
        }
        catch(\Exception $e)
        {
            return;
        }
    }
    function ebz_woocommerce_before_single_product_summary()
    {
        $ebzp = get_option('ebz_woocommerce_before_single_product_summary');
        try
        {
            if (is_array($ebzp) || is_object($ebzp))
            {
                foreach ($ebzp as $value)
                {
                    echo do_shortcode($value);
                }
            }
        }
        catch(\Exception $e)
        {
            return;
        }
    }
    function ebz_woocommerce_product_thumbnails()
    {
        $ebzp = get_option('ebz_woocommerce_product_thumbnails');
        try
        {

            if (is_array($ebzp) || is_object($ebzp))
            {
                foreach ($ebzp as $value)
                {
                    echo do_shortcode($value);
                }
            }
        }
        catch(\Exception $e)
        {
            return;
        }
    }
    function ebz_woocommerce_single_product_summary()
    {
        $ebzp = get_option('ebz_woocommerce_single_product_summary');
        try
        {
            if (is_array($ebzp) || is_object($ebzp) )
            {
                foreach ($ebzp as $value)
                {
                    echo do_shortcode($value);
                }
            }
        }
        catch(\Exception $e)
        {
            return;
        }
    }
    function ebz_woocommerce_before_add_to_cart_form()
    {
        $ebzp = get_option('ebz_woocommerce_before_add_to_cart_form');
        try
        {
            if (is_array($ebzp) || is_object($ebzp) )
            {
                foreach ($ebzp as $value)
                {
                    echo do_shortcode($value);
                }
            }
        }
        catch(\Exception $e)
        {
            return;
        }
    }
    function ebz_woocommerce_before_variations_form()
    {

        $ebzp = get_option('ebz_woocommerce_before_variations_form');
        try
        {
            if (is_array($ebzp) || is_object($ebzp))
            {
                foreach ($ebzp as $value)
                {
                    echo do_shortcode($value);
                }
            }
        }
        catch(\Exception $e)
        {
            return;
        }
    }
    function ebz_woocommerce_before_add_to_cart_button()
    {
        $ebzp = get_option('ebz_woocommerce_before_add_to_cart_button');
        try
        {
            if (is_array($ebzp) || is_object($ebzp))
            {
                foreach ($ebzp as $value)
                {
                    echo do_shortcode($value);
                }
            }
        }
        catch(\Exception $e)
        {
            return;
        }
    }
    function ebz_woocommerce_before_single_variation()
    {
        $ebzp = get_option('ebz_woocommerce_before_add_to_cart_button');
        try
        {
            if (is_array($ebzp) || is_object($ebzp))
            {
                foreach ($ebzp as $value)
                {
                    echo do_shortcode($value);
                }
            }
        }
        catch(\Exception $e)
        {
            return;
        }
    }
    function ebz_woocommerce_single_variation()
    {
        $ebzp = get_option('ebz_woocommerce_single_variation');
        try
        {
            if (is_array($ebzp) || is_object($ebzp))
            {
                foreach ($ebzp as $value)
                {
                    echo do_shortcode($value);
                }
            }
        }
        catch(\Exception $e)
        {
            return;
        }
    }
    function ebz_woocommerce_after_single_variation()
    {
        $ebzp = get_option('ebz_woocommerce_after_single_variation');
        try
        {
            if (is_array($ebzp) || is_object($ebzp))
            {
                foreach ($ebzp as $value)
                {
                    echo do_shortcode($value);
                }
            }
        }
        catch(\Exception $e)
        {
            return;
        }
    }
    function ebz_woocommerce_after_add_to_cart_button()
    {
        $ebzp = get_option('ebz_woocommerce_after_add_to_cart_button');
        try
        {
            if (is_array($ebzp) || is_object($ebzp))
            {
                foreach ($ebzp as $value)
                {
                    echo do_shortcode($value);
                }
            }
        }
        catch(\Exception $e)
        {
            return;
        }
    }
    function ebz_woocommerce_after_variations_form()
    {
        $ebzp = get_option('ebz_woocommerce_after_variations_form');
        try
        {
            if (is_array($ebzp) || is_object($ebzp))
            {
                foreach ($ebzp as $value)
                {
                    echo do_shortcode($value);
                }
            }
        }
        catch(\Exception $e)
        {
            return;
        }
    }
    function ebz_woocommerce_after_add_to_cart_form()
    {
        $ebzp = get_option('ebz_woocommerce_after_add_to_cart_form');
        try
        {
            if (is_array($ebzp) || is_object($ebzp))
            {
                foreach ($ebzp as $value)
                {
                    echo do_shortcode($value);
                }
            }
        }
        catch(\Exception $e)
        {
            return;
        }
    }
    function ebz_woocommerce_product_meta_start()
    {
        $ebzp = get_option('ebz_woocommerce_product_meta_start');
        try
        {
            if (is_array($ebzp) || is_object($ebzp))
            {
                foreach ($ebzp as $value)
                {
                    echo do_shortcode($value);
                }
            }
        }
        catch(\Exception $e)
        {
            return;
        }
    }
    function ebz_woocommerce_product_meta_end()
    {
        $ebzp = get_option('ebz_woocommerce_product_meta_end');
        try
        {
            if (is_array($ebzp) || is_object($ebzp))
            {
                foreach ($ebzp as $value)
                {
                    echo do_shortcode($value);
                }
            }
        }
        catch(\Exception $e)
        {
            return;
        }
    }
    function ebz_woocommerce_share()
    {
        $ebzp = get_option('ebz_woocommerce_share');
        try
        {
            if (is_array($ebzp) || is_object($ebzp))
            {
                foreach ($ebzp as $value)
                {
                    echo do_shortcode($value);
                }
            }
        }
        catch(\Exception $e)
        {
            return;
        }
    }
    function ebz_woocommerce_after_single_product_summary()
    {
        $ebzp = get_option('ebz_woocommerce_after_single_product_summary');
        try
        {
            if (is_array($ebzp) || is_object($ebzp))
            {
                foreach ($ebzp as $value)
                {
                    echo do_shortcode($value);
                }
            }
        }
        catch(\Exception $e)
        {
            return;
        }
    }
    function ebz_woocommerce_after_single_product()
    {
        $ebzp = get_option('ebz_woocommerce_after_single_product');
        try
        {
            if (is_array($ebzp) || is_object($ebzp))
            {
                foreach ($ebzp as $value)
                {
                    echo do_shortcode($value);
                }
            }
        }
        catch(\Exception $e)
        {
            return;
        }
    }

    function ebz_prod_rec_wasps()
    {
        try
        {
            if (is_admin() || is_feed() || is_robots() || is_trackback())
            {
                return;
            }
            $exploded = explode('_', esc_html(wp_unslash(get_option('ebz_prod_rec_position'))));
            $qty = end($exploded);
            if ($exploded[0] != 'wasps')
            {
                return;
            }
            $qty = ($qty > 0 ? $qty : 4);
            $prod_rec = '[zlt_rec per_row="' . $qty . '" qty="' . $qty . '" type="product"]';
            echo do_shortcode($prod_rec);
        }
        catch(\Exception $e)
        {
            return;
        }
    }

    function ebz_prod_rec_wasp()
    {
        try
        {
            if (is_admin() || is_feed() || is_robots() || is_trackback())
            {
                return;
            }
            $exploded = explode('_', esc_html(wp_unslash(get_option('ebz_prod_rec_position'))));
            $qty = end($exploded);
            if ($exploded[0] != 'wasp')
            {
                return;
            }
            $qty = ($qty > 0 ? $qty : 4);
            $prod_rec = '[zlt_rec per_row="' . $qty . '" qty="' . $qty . '" type="product"]';
            echo do_shortcode($prod_rec);
        }
        catch(\Exception $e)
        {
            return;
        }
    }

    # woocommerce_no_products_found
    function ebz_prod_rec_wnpf()
    {
        try
        {
            if (is_admin() || is_feed() || is_robots() || is_trackback())
            {
                return;
            }

            $exploded = explode('_', esc_html(wp_unslash(get_option('ebz_search_rec_position'))));
            $qty = end($exploded);
            if ($exploded[0] != 'wnpf')
            {
                return;
            }
            $qty = ($qty > 0 ? $qty : 4);
            $prod_rec = '[zlt_rec per_row="' . $qty . '" qty="' . $qty . '" type="search"]';
            echo do_shortcode($prod_rec);
        }
        catch(\Exception $e)
        {
            return;
        }
    }

    # woocommerce_before_checkout_form
    function ebz_prod_rec_wbcf()
    {
        try
        {

            if (is_admin() || is_feed() || is_robots() || is_trackback())
            {
                return;
            }
            $exploded = explode('_', esc_html(wp_unslash(get_option('ebz_checkout_rec_position'))));
            $qty = end($exploded);
            if ($exploded[0] != 'wbcf')
            {
                return;
            }
            $qty = ($qty > 0 ? $qty : 4);
            $prod_rec = '[zlt_rec per_row="' . $qty . '" qty="' . $qty . '" type="checkout"]';
            do_shortcode($prod_rec);
        }
        catch(\Exception $e)
        {
            return;
        }
    }

    # woocommerce_archive_description AND startpage
    function ebz_prod_rec_wad()
    {
        try
        {
            if (is_admin() || is_feed() || is_robots() || is_trackback())
            {
                return;
            }
            if (is_shop() && !is_search())
            {
                $exploded = explode('_', esc_html(wp_unslash(get_option('ebz_start_rec_position'))));
                $qty = end($exploded);
                if ($exploded[0] != 'wad')
                {
                    return;
                }
                $qty = ($qty > 0 ? $qty : 4);
                $prod_rec = '[zlt_rec per_row="' . $qty . '" qty="' . $qty . '" type="category"]';
                echo do_shortcode($prod_rec);
            }
            elseif (!is_search())
            {
                $exploded = explode('_', esc_html(wp_unslash(get_option('ebz_cat_rec_position'))));
                $qty = end($exploded);
                if ($exploded[0] != 'wad')
                {
                    return;
                }
                $qty = ($qty > 0 ? $qty : 4);
                $prod_rec = '[zlt_rec per_row="' . $qty . '" qty="' . $qty . '" type="category"]';
                echo do_shortcode($prod_rec);
            }
        }
        catch(\Exception $e)
        {
            return;
        }
    }

    # woocommerce_before_cart CHANGE OPTION
    function ebz_prod_rec_wbc()
    {
        try
        {
            if (is_admin() || is_feed() || is_robots() || is_trackback())
            {
                return;
            }

            $exploded = explode('_', esc_html(wp_unslash(get_option('ebz_cart_rec_position'))));
            $qty = end($exploded);
            if ($exploded[0] != 'wbc')
            {
                return;
            }
            $qty = ($qty > 0 ? $qty : 4);
            $prod_rec = '[zlt_rec per_row="' . $qty . '" qty="' . $qty . '" type="cart"]';
            echo do_shortcode($prod_rec);
        }
        catch(\Exception $e)
        {
            return;
        }
    }

    # woocommerce_after_mini_cart CHANGE OPTION
    function ebz_prod_rec_wamc()
    {
        try
        {

            if (is_admin() || is_feed() || is_robots() || is_trackback())
            {
                return;
            }
            $exploded = explode('_', esc_html(wp_unslash(get_option('ebz_minicart_rec_position'))));
            $qty = end($exploded);
            if ($exploded[0] != 'wamc')
            {
                return;
            }
            $qty = ($qty > 0 ? $qty : 4);
            $prod_rec = '[zlt_rec per_row="' . $qty . '" qty="' . $qty . '" type="minicart"]';
            echo do_shortcode($prod_rec);
        }
        catch(\Exception $e)
        {
            return;
        }
    }



    function ebz_recommendation($attributes)
    {
        try
        {
            if (is_admin() || is_feed() || is_robots() || is_trackback())
            {
                return;
            }
            if (get_option('ebz_is_debug'))
            {
                $debug = True;
            }
            else
            {
                $debug = False;
            }

            $args = shortcode_atts(array(
                'tid' => 0
            ) , $attributes);
            $tid = (int)$args['tid'];

            /**
             * Get the current product or cart content
             * If nothing exists, return empty
             */
            global $product;

            $product_id = '';
            if (isset($product))
            {
                $product_id = $product->get_id();
            }

            $cart = WC()->cart;

            if(!is_null($cart)){
                if ( ! $cart->is_empty() )
                {
                    $items = WC()->cart->get_cart();
                    $product_ids = [];
                    foreach ($items as $item => $values)
                    {
                        $_product = wc_get_product($values['data']->get_id());
                        if ($values['variation_id'] > 0)
                        {
                            $product_ids[] = $_product->get_parent_id();
                        }
                        else
                        {
                            $product_ids[] = $_product->get_id();
                        }
                    }
                    $product_id_string = implode(",", $product_ids);
                    if (sizeof($product_ids) > 0 && strlen($product_id) > 0)
                    {
                        $product_id .= ',' . $product_id_string;
                    }
                    elseif (sizeof($product_ids) > 0)
                    {
                        $product_id = $product_id_string;
                    }
                }
            }
            $atts = $attributes;
            $zString = "";
            for ($i = 0;$i < sizeof($atts);$i++)
            {
                if (isset($atts[$i])) $zString .= $atts[$i] . " ";
            }
            if (strstr($zString, "header=") != false)
            {
                $zString = str_replace('header=', ',,header=', $zString);
            }
            if (strstr($zString, "model=") != false)
            {
                $zString = str_replace('model=', ',,model=', $zString);
            }
            if (isset($zString))
            {
                $zString = str_replace("'", "", $zString);
                $atts[0] = $zString;
            }
            $zString = explode(",,",htmlentities($zString));
            $zString = array_filter($zString);
            $zString = array_values($zString);
            for ($i = 0;$i < sizeof($zString);$i++){
                list($k, $v) = explode('=', $zString[$i]);
                $attrs2[ $k ] = $v;
            }
            for ($i = 0;$i < sizeof($atts);$i++){
                    unset($atts[$i]);
            }
            if(isset($attrs2)){
                $atts = array_merge($atts,$attrs2);
            }
            if(isset($atts[0]))
                unset($atts[0]);

            $str = "";
            // Img size
            $img_size = esc_html(wp_unslash(get_option('ebz_img_size')));
            global $rcid;

      $zl_origin_url = '';
			try {
				global $wp;
        $protocol = 'https://';
  			if (isset($_SERVER['HTTPS']) &&
  				($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||
  				isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
  				$_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
  			  $protocol = 'https://';
  			}
  			else {
  			  $protocol = 'http://';
  			}
				$zl_origin_url = $protocol . $_SERVER['SERVER_NAME'] . add_query_arg( home_url( $wp->request ), NULL );
			} catch(\Exception $e) {
				$zl_origin_url = '';
			}

            $url = 'https://realtime-dot-solutionsone-211314.appspot.com/v1/recommendations/products';
            $url_token = esc_html(wp_unslash(get_option('ebz_user_token')));
            if(isset($atts['model']))
                 $zbody = '{"origin": "wc","model":"'.$atts['model'].'","tid":"' . $tid . '","_token":"' . $url_token . '","rec_key":"'. $rcid.'","pid":"' . $product_id . '","url":"' . $zl_origin_url . '"}';
            else
                 $zbody = '{"origin": "wc","tid":"' . $tid . '","_token":"' . $url_token . '","rec_key":"'. $rcid .'","pid":"' . $product_id . '","url":"' . $zl_origin_url . '"}';
            $response = wp_remote_post($url, array(
                'headers' => array(
                    'Content-Type' => 'application/json; charset=utf-8',
                    'Cache-Control' => 'no-store, no-cache, must-revalidate, max-age=0'
                ) ,
                'method' => 'POST',
                'timeout' => 45,
                'redirection' => 5,
                'httpversion' => '1.0',
                'blocking' => true,
                'body' => $zbody,
                'cookies' => array()
            ));
            $bodyArray = (json_decode($response["body"], true));
            if(!empty($bodyArray) && !array_key_exists('message',$bodyArray))  {
                $block_split = explode('<% |zl-pipe| %>', $bodyArray['html']);
                $products_received = $bodyArray['products'];
                $type = 'v1';
                $count = 0;
                $font = $bodyArray['font'];
                $str = '';
                if ($font != 'inherit')
                {
                    echo '<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js"></script>
                    <script>
                      WebFont.load({
                        google: {
                          families: ["' . $font . '", "' . $font . '"]
                        }
                      });
                    </script>';
                }

                $last_element = array_pop($block_split);
                if (isset($products_received) && is_array($products_received))
                {
                    foreach ($block_split as $block)
                    {
                        $_pid = (int)$products_received[$count];
                        $_product = wc_get_product($_pid);
                        if ($_product)
                        {
                            $image = wp_get_attachment_image_src($_product->get_image_id() , $img_size);
                            $image = $image[0];
                            if (empty($image))
                            {
                                $image = plugin_dir_url(__FILE__) . 'views/placeholder.png';
                            }
                            $zl_url = $_product->get_permalink();
                            if (strpos($zl_url, '?') !== false)
                            {
                                $zl_url = $zl_url . '&zlt_source=' . $type;
                            }
                            else
                            {
                                $zl_url = $zl_url . '?zlt_source=' . $type;
                            }
                            $zl_add_to_cart = $_product->add_to_cart_url();
                            if (strpos($zl_add_to_cart, '?') !== false)
                            {
                                $zl_add_to_cart = $zl_add_to_cart . '&zlt_source=' . $type;
                            }
                            else
                            {
                                $zl_add_to_cart = $zl_add_to_cart . '?zlt_source=' . $type;
                            }
                            if (strpos($zl_add_to_cart, '?wc-ajax=get_refreshed_fragments') !== false)
                            {
                                $zl_add_to_cart = $zl_url;
                            }
                            $block = str_replace("<% product_price %>", $_product->get_price_html() , $block);
                            $block = str_replace("<% add_to_cart_price %>", $_product->get_price_html() , $block);
                            $block = str_replace("<% product_name %>", $_product->get_name() , $block);
                            $block = str_replace("<% add_to_cart %>", $_product->add_to_cart_text() , $block);
                            $block = str_replace("<% product_img %>", $image, $block);
                            $block = str_replace("<% product_to_cart_url %>", $zl_add_to_cart, $block);
                            $block = str_replace("<% product_url %>", $zl_url, $block);
                            $block = str_replace("t_p_wrapper", "t_p_wrapper " . $tid, $block);
                        }
                        $count += 1;
                        $str .= $block;
                    }

                    $str .= $last_element;

                    echo '<div class="recKey" data-rec="'.$rcid.'" ></div>';

                    echo '<script type="text/javascript">
                            jQuery(document).ready(function(){
                              var img_wid = parseInt(jQuery(".product-wrapper .img").css("width"))  ;
                                  jQuery(".product-wrapper .zlt_text_block").css("max-width",img_wid+"px");
                                  jQuery(".product-wrapper  .zlt_text_block").css("overflow","hidden");
                              });
                          </script>';

                    return $str;

                }
                else
                {
                    if (current_user_can('manage_options'))
                    {
                        $redirect_to_temp = site_url() . '/wp-admin/admin.php?page=engage-by-zubi';
                        echo "<div id='warning_ebz' style='text-align: left;padding: 5px;color: #b77979;font-size: 16px;'>Please  <a href='" . $redirect_to_temp . "' style='text-decoration: underline;color: #e78145;'> Select a template </a> for Recommedations or make a <a href='" . $redirect_to_temp . "' style='text-decoration: underline;color: #e78145;'>New One</a></div> ";
                    }
                }
                return $str;
                }else{
                    return;
                }



        }
        catch(\Exception $e)
        {
            return;
        }

    }

    function trackingDisabled()
    {
        try
        {
            // Ignore admin, feed, robots or trackbacks
            if (empty(get_option('ebz_store_name')))
            {
                update_option('ebz_store_name', 'default_store');
            }
            if (is_admin() || is_feed() || is_robots() || is_trackback() || get_option('ebz_is_disabled') || empty(get_option('ebz_tracker_key')) || trim(get_option('ebz_tracker_key')) == '')
            {
                return true; // disabled

            }
            else
            {
                return false;
            }
        }
        catch(\Exception $e)
        {
            return;
        }
    }

    function zl_ajax_get_product()
    {
        try
        {
            $num = $_GET['pid'];
            $num = str_replace('"', "", $num);
            $num = stripslashes($num);
            $product = wc_get_product($num);
            echo $product;
            exit();
        }
        catch(\Exception $e)
        {
            echo "";
            exit();
        }
    }

    /**
     * Register the plugin settings panel
     */
    function adminPanelsAndMetaBoxes()
    {
        global $wp_admin_bar;
        add_menu_page('Settings', 'engage', 'manage_options', $this
            ->plugin->name, array(&$this,
            'adminPanel'
        ) , '', 30);
    }


    /**
     * Output the Administration Panel
     * Save POSTed data from the Administration Panel into a WordPress option
     */
    function adminPanel()
    {
        // only admin user can access this page
        if (!current_user_can('administrator'))
        {
            echo '<p>' . __('Sorry, you are not allowed to access this page.', $this
                ->plugin
                ->name) . '</p>';
            return;
        }

        /* No longer in use
        if (isset($_REQUEST['submit2']))
        {
            update_option('euKey', sanitize_text_field($_REQUEST['ebz_user_token']));
            update_option('etKey', sanitize_text_field($_REQUEST['ebz_tracker_key']));
            $store_url = site_url();
            $endpoint = '/wc-auth/v1/authorize';
            $params = ['app_name' => 'engage by zubi', 'scope' => 'read', 'user_id' => sanitize_text_field($_REQUEST['ebz_uid']) , 'return_url' => site_url() . '/wp-admin/admin.php?page=engage-by-zubi', 'callback_url' => "https://api-dot-solutionsone-211314.ew.r.appspot.com/callback/nsRPyZZGfrQWx5eAwVgG3d/wc"];
            $params = http_build_query($params);
            $redirect_to_auth = $store_url . $endpoint . '?' . $params;
            header("location:" . $redirect_to_auth);
        } */

        if (isset($_REQUEST['success']) && isset($_REQUEST['user_id']))
        {
            $connection_made = $_REQUEST['success'];
            if ($connection_made != 1)
            {
                update_option('ebz_user_token', ' ');
                update_option('ebz_tracker_key', ' ');
                $this->message = __('Settings Could not be saved.', $this
                    ->plugin
                    ->name);
            }
            /* NO LONGER IN USE
            else
            {
                $this->message = __('Connection Successfull.', $this
                    ->plugin
                    ->name);
                update_option('ebz_user_token', esc_html(wp_unslash(get_option('euKey'))));
                update_option('ebz_tracker_key', esc_html(wp_unslash(get_option('etKey'))));
            }*/
        }

        /* NO LONGER IN USE
        // Save Settings
        if (isset($_REQUEST['submit']))
        {

            // Check nonce
            if (!isset($_REQUEST[$this
                ->plugin->name . '_nonce']))
            {
                // Missing nonce
                $this->errorMessage = __('nonce field is missing. Settings NOT saved.', $this
                    ->plugin
                    ->name);
            }
            elseif (!wp_verify_nonce($_REQUEST[$this
                ->plugin->name . '_nonce'], $this
                ->plugin
                ->name))
            {
                // Invalid nonce
                $this->errorMessage = __('Invalid nonce specified. Settings NOT saved.', $this
                    ->plugin
                    ->name);
            }
            else
            {
                // Save
                if (!empty($_REQUEST['ebz_user_token']) && !empty($_REQUEST['ebz_user_token']))
                {
                    update_option('ebz_user_token', sanitize_text_field($_REQUEST['ebz_user_token']));
                    update_option('ebz_tracker_key', sanitize_text_field($_REQUEST['ebz_tracker_key']));
                    if (isset($_REQUEST['ebz_is_disabled'])) update_option('ebz_is_disabled', $_REQUEST['ebz_is_disabled']);
                    else update_option('ebz_is_disabled', 0);
                    if (isset($_REQUEST['ebz_use_square_img'])) update_option('ebz_use_square_img', sanitize_text_field($_REQUEST['ebz_use_square_img']));
                    update_option('ebz_img_size', sanitize_text_field($_REQUEST['ebz_img_size']));
                    if (isset($_REQUEST['ebz_is_debug'])) update_option('ebz_is_debug', $_REQUEST['ebz_is_debug']);
                    else update_option('ebz_is_debug', 0);
                    if (isset($_REQUEST['ebz_prod_rec_position'])) update_option('ebz_prod_rec_position', sanitize_text_field($_REQUEST['ebz_prod_rec_position']));
                    if (isset($_REQUEST['ebz_cat_rec_position'])) update_option('ebz_cat_rec_position', sanitize_text_field($_REQUEST['ebz_cat_rec_position']));
                    if (isset($_REQUEST['ebz_start_rec_position'])) update_option('ebz_start_rec_position', sanitize_text_field($_REQUEST['ebz_start_rec_position']));
                    if (isset($_REQUEST['ebz_checkout_rec_position'])) update_option('ebz_checkout_rec_position', sanitize_text_field($_REQUEST['ebz_checkout_rec_position']));
                    if (isset($_REQUEST['ebz_search_rec_position'])) update_option('ebz_search_rec_position', sanitize_text_field($_REQUEST['ebz_search_rec_position']));
                    if (isset($_REQUEST['ebz_cart_rec_position'])) update_option('ebz_cart_rec_position', sanitize_text_field($_REQUEST['ebz_cart_rec_position']));
                    if (isset($_REQUEST['ebz_minicart_rec_position'])) update_option('ebz_minicart_rec_position', sanitize_text_field($_REQUEST['ebz_minicart_rec_position']));


                    global $positions;
                    foreach ($positions as $value)
                    {
                        if (isset($_REQUEST['ebz_' . $value]))
                        {
                            update_option('ebz_' . $value, $_REQUEST['ebz_' . $value]);
                        }
                        if (isset($_REQUEST['ebz_' . $value . '_name']))
                        {
                            update_option('ebz_' . $value . '_name', $_REQUEST['ebz_' . $value . "_name"]);
                        }
                        if (isset($_REQUEST['ebz_' . $value . '_default']))
                        {
                            update_option('ebz_' . $value . '_default', $_REQUEST['ebz_' . $value . '_default']);
                        }
                    }

                }
                else
                {
                    $this->errorMessage = __('User Key and Token cannot be empty.', $this
                        ->plugin
                        ->name);
                }
                update_option($this
                    ->plugin->db_welcome_dismissed_key, 1);
                $this->message = __('Settings Saved.', $this
                    ->plugin
                    ->name);
            }

        }*/
        // Get latest settings
        $this->settings = array(
            'ebz_user_token' => esc_html(wp_unslash(get_option('ebz_user_token'))) ,
            'ebz_tracker_key' => esc_html(wp_unslash(get_option('ebz_tracker_key'))) ,
            'ebz_store_name' => esc_html(wp_unslash(get_option('ebz_store_name'))) ,
            'ebz_is_disabled' => esc_html(wp_unslash(get_option('ebz_is_disabled'))) ,
            'ebz_use_square_img' => esc_html(wp_unslash(get_option('ebz_use_square_img'))) ,
            'ebz_img_size' => esc_html(wp_unslash(get_option('ebz_img_size'))) ,
            'ebz_is_debug' => esc_html(wp_unslash(get_option('ebz_is_debug'))) ,

            'ebz_prod_rec_position' => esc_html(wp_unslash(get_option('ebz_prod_rec_position'))) ,
            'ebz_cat_rec_position' => esc_html(wp_unslash(get_option('ebz_cat_rec_position'))) ,
            'ebz_start_rec_position' => esc_html(wp_unslash(get_option('ebz_start_rec_position'))) ,
            'ebz_checkout_rec_position' => esc_html(wp_unslash(get_option('ebz_checkout_rec_position'))) ,
            'ebz_search_rec_position' => esc_html(wp_unslash(get_option('ebz_search_rec_position'))) ,
            'ebz_cart_rec_position' => esc_html(wp_unslash(get_option('ebz_cart_rec_position'))) ,
            'ebz_minicart_rec_position' => esc_html(wp_unslash(get_option('ebz_minicart_rec_position'))) ,

            'ebz_css_prod_rec_display' => esc_html(wp_unslash(get_option('ebz_css_prod_rec_display'))) ,
            'ebz_css_cat_rec_display' => esc_html(wp_unslash(get_option('ebz_css_cat_rec_display'))) ,
            'ebz_css_start_rec_display' => esc_html(wp_unslash(get_option('ebz_css_start_rec_display'))) ,
            'ebz_css_checkout_rec_display' => esc_html(wp_unslash(get_option('ebz_css_checkout_rec_display'))) ,
            'ebz_css_search_rec_display' => esc_html(wp_unslash(get_option('ebz_css_search_rec_display'))) ,
            'ebz_css_cart_rec_display' => esc_html(wp_unslash(get_option('ebz_css_cart_rec_display'))) ,
            'ebz_css_minicart_rec_display' => esc_html(wp_unslash(get_option('ebz_css_minicart_rec_display'))) ,
        );

        /**
         * Product page placements
         */
        global $positions;
        foreach ($positions as $value)
        {
            $this->settings['ebz_' . $value . '_name'] = get_option('ebz_' . $value . '_name');
            $this->settings['ebz_' . $value] = get_option('ebz_' . $value);
            $this->settings['ebz_' . $value . '_default'] = get_option('ebz_' . $value . '_default');
        }

        // Load Settings Form
        if (!include_once(WP_PLUGIN_DIR . '/' . $this->plugin->name . '/views/settings.php')) {
      		include_once(WP_PLUGIN_DIR . '/' . dirname( plugin_basename( __FILE__ ) ) . '/views/settings.php');
      	}
    }
    /**
     * Loads plugin textdomain
     */

    function loadLanguageFiles()
    {
        load_plugin_textdomain($this
            ->plugin->name, false, $this
            ->plugin->name . '/languages/');
    }

    function custom_products_displayed()
    {
        try {
            // Return if tracking is disabled
            // if ( $this->trackingDisabled() ) {return;}
            global $product;

            $terms = get_the_terms($product->get_id(), 'product_cat');
            if (!is_countable($terms)) {
                $cntx = 0;
            } else {
                $cntx = count($terms);
            }
            $product_cat_name = "";
            for ($i = 0; $i < $cntx; $i++) {
                if ($i + 1 == $cntx) {
                    $product_cat_name .= addslashes($terms[$i]->name);
                } else {
                    $product_cat_name .= addslashes($terms[$i]->name) . '>';
                }
            }

            if (empty($product_cat_name)) {
                $product_cat_name = "uncategorized";
            }
            $sale_price = $product->get_sale_price();
            if (empty($sale_price)) {
                $sale_price = $product->get_price();
            }

            wp_register_script('zl-handle-footer-3', '', [], '', true);
            wp_enqueue_script('zl-handle-footer-3');
            wp_add_inline_script('zl-handle-footer-3', "var prod_id = " . $product->get_id() . ";var x = {type:'product',product_id: prod_id.toString(), name: '" . addslashes($product->get_name()) . "',type : 'product', category: '" . $product_cat_name . "' , currency: '" . get_option('woocommerce_currency') . "', price : " . floatval($product->get_price()) . ", sale_price:" .  floatval($sale_price) . "  ,url: window.location.href};
              zlMappedProdsXRC178[prod_id] =  x;
              zlArrayProdsXRC178.push(x);
              zlt.track('Product Seen', x);");
        } catch (\Exception $e) {
            return;
        }
    }



    function productPages()
    {
        try
        {

            global $product;
            $currency = get_woocommerce_currency();

            $terms = get_the_terms($product->get_id() , 'product_cat');
            $product_cat_name = "";
            for ($i = 0;$i < count($terms);$i++)
            {
                if ($i + 1 == count($terms))
                {

                    $product_cat_name .= addslashes($terms[$i]->name);
                }
                else
                {
                    $product_cat_name .= addslashes($terms[$i]->name) . '>';
                }
            }

            if (empty($product_cat_name))
            {
                $product_cat_name = "uncategorized";
            }
            $sale_price = $product->get_sale_price();
            if (empty($sale_price))
            {
                $sale_price = $product->get_price();
            }

            wp_register_script('zl-handle-footer-1', '', [], '', true);
            wp_enqueue_script('zl-handle-footer-1');



            wp_add_inline_script('zl-handle-footer-1', "var prod_id = ".$product->get_id()."; var x = {type:'product' ,product_id: prod_id.toString(), name: '" . addslashes($product->get_name()) . "', category: '" . $product_cat_name . "' , currency: '" . get_option('woocommerce_currency') . "', price : " . floatval($product->get_price()) . ", sale_price:" . $sale_price . "  ,url: window.location.href}; zlMappedProdsXRC178[prod_id] =  x;  zlsingle_viewed_id = prod_id; zlArrayProdsXRC178.push(x);   zlt.track('Product Viewed', x);");

        }
        catch(\Exception $e)
        {
            return;
        }

    }
    /**
        Checkout Started
    */
    function zl_checkout_started($checkout){
        try{

            $all_in_cart = [];
            $all_in_cart_arr = [];
            $json_main = new stdClass();
            $object_Mapper = new stdClass();

            $cart = WC()->cart->get_cart();
            $total = WC()->cart->total;
            $total_tax = WC()->cart->get_taxes_total();
            $shipping = WC()->cart->get_shipping_total();
            $discounts = WC()->cart->get_discount_total();
            $coupons = WC()->cart->get_coupons();
            if(isset($coupons)){
                if(isset($coupons[0])) {
                    $json_main->coupon  = $coupons[0];
                }
            }
            $currency = get_option('woocommerce_currency');
            $subtotal = WC()->cart->get_displayed_subtotal();

            $json_main->total  = (float)$total;
            $json_main->subtotal  = (float)$subtotal;
            $json_main->shipping  = (float)$shipping;
            $json_main->tax  = (float)$total_tax;
            $json_main->discount  = (float)$discounts;
            $json_main->currency  = $currency;


            foreach( $cart as $cart_item ){

              $id = $cart_item['product_id'];
              $product = wc_get_product( $id );
              $quant = $cart_item['quantity'];
              $ttl = $product->get_title();
              $price = floatval($product->get_price());
              $sku = $product->get_sku();

              if( $cart_item['variation_id'] ){
                 $variation_id = wc_get_product($cart_item['variation_id']);
              }else{
                 $variation_id = wc_get_product($id);
              }

              $variation_id = strval($variation_id->get_id());
              $onsale = false;

              if( $product->is_on_sale() )
                $onsale = true;


              $url = get_permalink( $id );
              $image_url = get_the_post_thumbnail_url($id);
              $prod_data = new stdClass();
              $prod_data->product_id  = $id;
              $prod_data->quantity  = $quant;
              $prod_data->name  = $ttl;
              $prod_data->price  = $price;
              $prod_data->variation_id  = $variation_id;
              $prod_data->currency  = $currency;
              $prod_data->on_sale  = $onsale;
              $prod_data->url  = $url;
              $prod_data->image_url  = $image_url;
              array_push($all_in_cart_arr, $prod_data );

            }

            echo '<script>
                const zl_cart_deets = '.json_encode($json_main).';
                zlt.track("Checkout Started", { products : '.json_encode($all_in_cart_arr).' ,
                 ...zl_cart_deets });

            </script>';
        }catch(Exception $e){

        }
    }
    function customReadOrder($order_id = NULL)
    {
        try
        {
            // Return if tracking is disabled
            // if ( $this->trackingDisabled() ) {return;}
            if (is_null($order_id))
            {
                return;
            }

            $currency = get_woocommerce_currency();
            //getting order object
            $order = wc_get_order($order_id);
            $items = $order->get_items();
            $line_items = "[";
            foreach ($items as $item_id => $item_data)
            {
                // Get an instance of corresponding the WC_Product object
                $product = $item_data->get_product();
                $terms = get_the_terms($product->get_id() , 'product_cat');
                $product_cat_name = "";
		if ( $terms && ! is_wp_error( $terms ) ) {
                  for ($i = 0;$i < count($terms);$i++)
                  {
                      if ($i + 1 == count($terms))
                      {

                          $product_cat_name .= addslashes($terms[$i]->name);
                      }
                      else
                      {
                          $product_cat_name .= addslashes($terms[$i]->name) . '>';
                      }
                  }
		}

		if (empty($product_cat_name))
		{
			$product_cat_name = "uncategorized";
		}
		$sale_price = $product->get_sale_price();
		if (empty($sale_price))
		{
			$sale_price = $product->get_price();
		}

                $item_quantity = $item_data->get_quantity(); // Get the item quantity
                $unit_price = number_format(((float)$item_data->get_total() / (float)$item_quantity) , 2, '.', '');
                $line_items .= "{type:'product',product_id: ".$product->get_id() .", name: '" . addslashes($product->get_name()) . "',type : 'product', category: '" . $product_cat_name . "' , currency: '" . get_option('woocommerce_currency') . "', price : " . floatval($product->get_price()) . ", sale_price:" .  floatval($product->get_price())  . "  ,url: window.location.href},";
            }
            $line_items .= "]";
            $line_items = json_encode($line_items);
            wp_register_script('zl-handle-footer-2', '', [], '', true);
            wp_enqueue_script('zl-handle-footer-2');
            wp_add_inline_script('zl-handle-footer-2', "function IsJsonString(str) {try {JSON.stringify(str);} catch (e) {return false;}return true;}
            try{
            var zl_order_prodss = ". json_decode($line_items) .";
            if(IsJsonString(zl_order_prodss)){
                zlt.track('Order Completed', {
            email: '" . esc_html(wp_unslash($order->get_billing_email())) . "',
            billing_address_first_name: '" . esc_html(wp_unslash($order->get_billing_first_name())) . "',
            billing_address_last_name: '" . esc_html(wp_unslash($order->get_billing_last_name())) . "',
            billing_address_company: '" . esc_html(wp_unslash($order->get_billing_company())) . "',
            billing_address_zip: '" . esc_html(wp_unslash($order->get_billing_postcode())) . "',
            billing_address_phone: '" . esc_html(wp_unslash($order->get_billing_phone())) . "',
            billing_address_address1: '" . esc_html(wp_unslash($order->get_billing_address_1())) . "',
            billing_address_address2: '" . esc_html(wp_unslash($order->get_billing_address_2())) . "',
            billing_address_city: '" . esc_html(wp_unslash($order->get_billing_city())) . "',
            billing_address_country: '" . esc_html(wp_unslash($order->get_billing_country())) . "',
            shipping_address_first_name: '" . esc_html(wp_unslash($order->get_shipping_first_name())) . "',
            shipping_address_last_name: '" . esc_html(wp_unslash($order->get_shipping_last_name())) . "',
            shipping_address_company: '" . esc_html(wp_unslash($order->get_shipping_company())) . "',
            shipping_address_zip: '" . esc_html(wp_unslash($order->get_shipping_postcode())) . "',
            shipping_address_address1: '" . esc_html(wp_unslash($order->get_shipping_address_1())) . "',
            shipping_address_address2: '" . esc_html(wp_unslash($order->get_shipping_address_2())) . "',
            shipping_address_city: '" . esc_html(wp_unslash($order->get_shipping_city())) . "',
            shipping_address_country: '" . esc_html(wp_unslash($order->get_shipping_country())) . "',
            order_id: '" . $order->get_id() . "',
            total: '" . $order->get_total() . "',
            shipping: '" . $order->get_shipping_total() . "',
            tax: '" . $order->get_total_tax() . "',
            payment_method: '" . esc_html(wp_unslash($order->get_payment_method())) . "',
            currency: '" . $currency . "',
            products: zl_order_prodss,
            created_at: '" . esc_html(wp_unslash($order->get_date_paid())) . "',
            updated_at: '" . esc_html(wp_unslash($order->get_date_completed())) . "'
          }); }else{
            zlt.track('Order Completed', {
            email: '" . esc_html(wp_unslash($order->get_billing_email())) . "',order_id: '" . $order->get_id() . "', });
          } } catch(e) { zlt.track('Order Completed', {
            email: '" . esc_html(wp_unslash($order->get_billing_email())) . "',order_id: '" . $order->get_id() . "', }); };");

        }
        catch(\Exception $e)
        {
            $order = wc_get_order($order_id);
            wp_register_script('zl-handle-footer-2', '', [], '', true);
            wp_enqueue_script('zl-handle-footer-2');
            wp_add_inline_script('zl-handle-footer-2',
            "zlt.track('Order Completed', {
            email: '" . esc_html(wp_unslash($order->get_billing_email())) . "',order_id: '"
            . $order->get_id() . "', }); };" );
            return;
        }
    }


    function zubi_scripts()
    {
       try
        {

            wp_enqueue_script('zubitracker', 'https://assets.zubitracker.io/v1/tracker/track.js', '', '', false);

            $meta = 'var TRACKER_KEY="'.get_option('ebz_tracker_key').'";window.zlt_queue||(window.zlt_queue=[]),window.zlt_queue2||(window.zlt_queue2=[]),window.zlt=function(){},window.zlt.rec=function(p,k,d){var u={p,k,d};window.zlt_queue2.push(u)},zlt.track=function(w,n){var u={};u[w]=n,window.zlt_queue.push(u)};';
            $meta .= '  var zlsingle_viewed_id = ""; var zlMappedProdsXRC178 = {}; var zlcartProdsArray = []; var zlcartProdsMap = {};  var zlArrayProdsXRC178 = []; var zl_Front_callerXRC18 = "'.admin_url( 'admin-ajax.php' ).'"; ';


            if (is_user_logged_in())
            {
                $current_user = wp_get_current_user();
                $date = strtotime($current_user->user_registered) * 1000;
                $meta .= "zlt.track('User', {'user_id':'" . esc_html($current_user->user_email) . "', user_email :'" . esc_html($current_user->user_email) . "', user_fname: '" . esc_html($current_user->user_firstname) . "' ,  user_lname : '" . esc_html($current_user->user_lastname) . "' , user_signed_up :" . $date . "});";
            }

            if(is_cart()){
              $meta .= "setTimeout(function(){window.zlt.track=function(e,t){var n={};n[e]=t,zlSDTT(Object.assign(n,zlXmr))};zlt.track('Cart Viewed', { products: zlcartProdsArray } )},2000);";
            }

            wp_add_inline_script('zubitracker', $meta, 'before');


        }
        catch(\Exception $e)
        {
            return;
        }
    }
}
$ebz = new eCommerceByZubi();
