<?php

if (!defined('ABSPATH')) exit; // Exit if accessed directlyhm;
require(plugin_dir_path(__FILE__) . '/facebook-api/' . AHACHAT_PREFIX .  'rule.php');

if (!class_exists('AHACHAT_WP_AJAX_CART')) {

    class AHACHAT_WP_AJAX_CART
    {

        public function __construct()
        {

            // ajax add

            add_action('wp_ajax_ahachat_add_user_ref', array($this, 'ahachat_add_user_ref'));

            add_action('wp_ajax_nopriv_ahachat_add_user_ref', array($this, 'ahachat_add_user_ref'));

            // ajax remove

            add_action('wp_ajax_ahachat_remove_product_cart', array($this, 'ahachat_remove_product_cart'));

            add_action('wp_ajax_nopriv_ahachat_remove_product_cart', array($this, 'ahachat_remove_product_cart'));

            // update

            add_action('wp_ajax_ahachat_update_product_cart', array($this, 'ahachat_update_product_cart'));

            add_action('wp_ajax_nopriv_ahachat_update_product_cart', array($this, 'ahachat_update_product_cart'));


            // Skip_it Ontime

            add_action('wp_ajax_ahachat_skip_it_ontime', array($this, 'ahachat_skip_it_ontime'));

            add_action('wp_ajax_nopriv_ahachat_skip_it_ontime', array($this, 'ahachat_skip_it_ontime'));

            // SUBMIT EMAIL

            add_action('wp_ajax_ahachat_submit_add_email', array($this, 'ahachat_submit_add_email'));

            add_action('wp_ajax_nopriv_ahachat_submit_add_email', array($this, 'ahachat_submit_add_email'));


            // CHECK USER ORDER

            //add_action( 'wp', array($this, 'ahachat_user_order_check' ) );

            // SEND MESSENGER LIST USER ADD TO CART

            add_action('wp_ajax_ahachat_send_list_user_add_cart', array($this, 'ahachat_send_list_user_add_cart'));

            add_action('wp_ajax_nopriv_ahachat_send_list_user_add_cart', array($this, 'ahachat_send_list_user_add_cart'));

            //

            add_action('wp_ajax_ahachat_get_all_user_add', array($this, 'ahachat_get_all_user_add'));

            add_action('wp_ajax_nopriv_ahachat_get_all_user_add', array($this, 'ahachat_get_all_user_add'));

            add_action('wp_ajax_ahachat_send_one_end', array($this, 'ahachat_send_one_end'));

            add_action('wp_ajax_nopriv_ahachat_send_one_end', array($this, 'ahachat_send_one_end'));


            // EXCUTE WITH SHORTCODE

            add_action('wp_ajax_ahachat_cartback_get_list_us_shortcode', array($this, 'ahachat_cartback_get_list_us_shortcode'));

            add_action('wp_ajax_nopriv_ahachat_cartback_get_list_us_shortcode', array($this, 'ahachat_cartback_get_list_us_shortcode'));

            // SHORTCODE

            add_action('wp_ajax_ahachat_action_save_change_shortcode', array($this, 'ahachat_action_save_change_shortcode'));

            add_action('wp_ajax_nopriv_ahachat_action_save_change_shortcode', array($this, 'ahachat_action_save_change_shortcode'));


            add_action('wp_ajax_ahachat_action_eidt_shortcode', array($this, 'ahachat_action_eidt_shortcode'));

            add_action('wp_ajax_nopriv_ahachat_action_eidt_shortcode', array($this, 'ahachat_action_eidt_shortcode'));


            add_action('wp_ajax_ahachat_action_delete_shortcode', array($this, 'ahachat_action_delete_shortcode'));

            add_action('wp_ajax_nopriv_ahachat_action_delete_shortcode', array($this, 'ahachat_action_delete_shortcode'));

            //

            add_action('wp_ajax_ahachat_popup_execute_live_search', array($this, 'ahachat_popup_execute_live_search'));

            add_action('wp_ajax_nopriv_ahachat_popup_execute_live_search', array($this, 'ahachat_popup_execute_live_search'));


            add_action('wp_ajax_ahachat_parse_edit_list_product', array($this, 'ahachat_parse_edit_list_product'));

            add_action('wp_ajax_nopriv_ahachat_parse_edit_list_product', array($this, 'ahachat_parse_edit_list_product'));

            //


            add_action('wp_ajax_ahachat_cartback_width_shortcode_custom_text', array($this, 'ahachat_cartback_width_shortcode_custom_text'));

            add_action('wp_ajax_nopriv_ahachat_cartback_width_shortcode_custom_text', array($this, 'ahachat_cartback_width_shortcode_custom_text'));


            add_action('wp_ajax_ahachat_cartback_width_shortcode_send_reminder', array($this, 'ahachat_cartback_width_shortcode_send_reminder'));

            add_action('wp_ajax_nopriv_ahachat_cartback_width_shortcode_send_reminder', array($this, 'ahachat_cartback_width_shortcode_send_reminder'));

            // ahachat callback
            add_action('wp_ajax_ahachat_callback_request', array($this, 'ahachat_callback_request'));
            add_action('wp_ajax_nopriv_ahachat_callback_request', array($this, 'ahachat_callback_request'));

            add_action('wp_ajax_ahachat_get_info_license', array($this, 'ahachat_get_info_license'));

            add_action('wp_ajax_nopriv_ahachat_get_info_license', array($this, 'ahachat_get_info_license'));

        }

        public function ahachat_callback_request()
        {
            $rule = new AHACHAT_WP_RULE;
            $rule->callback_request(json_decode(file_get_contents("php://input")));
            wp_die();
        }

        public function ahachat_add_user_ref()
        {
            if (isset($_POST['user_ref'])):

                global $woocommerce, $wpdb;

                $user_ref = $_POST["user_ref"];

                $product_id = $_POST["product_id"];

                $quantity_product = $_POST["quantity_product"];

                $session_user = $_POST["cookie_user"];  // cookie browser :)))

                $user_email = !empty($_POST["user_email"]) ? $_POST["user_email"] : "";

                $table_user_ref = AHACHAT_USER_REF_TABLE;

                $items = $woocommerce->cart->get_cart();

                $product_info = array();

                $product_quantity = array();

                if (count($items) > 0) {

                    foreach ($items as $item => $values) {

                        $product_info[] = array(

                            'product_id' => $values["product_id"],

                            'quantity' => $values["quantity"]

                        );

                    }

                }

                $count_product_quantity = 0;

                if (count($product_info) > 0) {

                    foreach ($product_info as $key => $cart) {

                        if ($cart["product_id"] == $_POST["product_id"]) {

                            $quantity = $cart["quantity"] + $_POST["quantity_product"];

                            $product_quantity[] = array(

                                'product_id' => $cart["product_id"],

                                'quantity' => $quantity

                            );

                            $count_product_quantity++;

                        } else {

                            $product_quantity[] = array(

                                'product_id' => $cart["product_id"],

                                'quantity' => $cart["quantity"]

                            );

                        }

                    }

                }

                if ($count_product_quantity == 0) {

                    $product_quantity[] = array(

                        'product_id' => $_POST["product_id"],

                        'quantity' => $_POST["quantity_product"]

                    );

                }

                $post_type_get_email = new AHA_POST_TYPE_USER_EMAIL;

                if (!empty($user_email)) {

                    $agrs_email = array('email' => $user_email);

                    if (count($product_quantity) > 0) {

                        $reminder_email = "yes";

                    } else {

                        $reminder_email = "no";

                    }

                    if (!$post_type_get_email->CheckUserExit($agrs_email)) {

                        $arr = array(

                            'mess' => "",

                            'post_date' => current_time('Y-m-d H:i:s'),

                            'post_type' => AHACHAT_LIST_EMAIL_POST_TYPE,

                            'post_status' => 'publish',

                            'cookie_popup_br' => 0,

                            'ahachat_email' => $user_email,

                            'ahachat_email_product' => serialize($product_quantity),

                            'ahachat_email_reminder' => $reminder_email

                        );

                        $add_email = $post_type_get_email->InsertEmail($arr);

                    } else {


                        $postid = $post_type_get_email->CheckMailPostID($agrs_email);


                        update_post_meta($postid, 'ahachat_email_product', serialize($product_quantity));

                        update_post_meta($postid, 'ahachat_email_reminder', $reminder_email);
                    }


                } else {
                    $cookie_popup_br = $_POST["cookie_popup"];

                    $agrs_email = array('cookie_popup' => $cookie_popup_br);

                    if (count($product_quantity) > 0) {

                        $reminder_email = "yes";

                    } else {

                        $reminder_email = "no";

                    }

                    $postid = $post_type_get_email->CheckCookiePostID($agrs_email);

                    if ($postid) {

                        update_post_meta($postid, 'ahachat_email_product', serialize($product_quantity));

                        update_post_meta($postid, 'ahachat_email_reminder', $reminder_email);

                    }


                }

                $row_user_ref = $wpdb->get_row("SELECT * FROM $table_user_ref WHERE session_key='" . $session_user . "' ");

                if (empty($row_user_ref) || $row_user_ref == NULL || $row_user_ref == ""):// add row into table
                    $cart = serialize($product_quantity);

                    $wpdb->insert($table_user_ref,

                        array(

                            'user_ref' => $user_ref,

                            'your_cart' => $cart,

                            'session_key' => $session_user,

                            'status_send_first' => 0,

                            'status_send_second' => 0,

                            'status_send_third' => 0,

                            'create_time' => date('Y-m-d H:i:s', time()),

                            'update_time' => date('Y-m-d H:i:s', time())

                        ),

                        array('%s', '%s', '%s', '%d', '%d', '%d', '%s', '%s')

                    );

                else:  // update row with session_key into table

                    $cart = serialize($product_quantity);

                    $wpdb->update(

                        $table_user_ref,

                        array(

                            'user_ref' => $user_ref,

                            'your_cart' => $cart,

                            'status_send_first' => 0,

                            'status_send_second' => 0,

                            'status_send_third' => 0,

                            'create_time' => date('Y-m-d H:i:s', time()),

                            'update_time' => date('Y-m-d H:i:s', time())

                        ),

                        array('session_key' => $session_user),

                        array('%s', '%s', '%d', '%d', '%d', '%s', '%s'), //'%s',

                        array('%s')

                    );

                    print_r("success");
                    // die;

                endif;


                $ahachat_table_statistical = AHACHAT_ANALYTICS_TABLE;

                $ahachat_date_statistical = date('Y-m-d', time());

                $day = date('d', time());

                $month = date('m', time());

                $year = date('Y', time());

                $fb_api = new AHACHAT_WP_API();

                $page_id = get_option('ahachat_page_id');

                $page_access_token = $fb_api->AHA_Get_Access_Token_Page();

                $ahachat_first_reminder = get_option('ahachat_first_reminder');


                if (isset($page_access_token["access_token"])) {

                    $page_token = $page_access_token["access_token"];

                    $array_product_mode = array();

                    $title = html_entity_decode(get_the_title($product_id));

                    $price = get_post_meta($product_id, '_regular_price', true);

                    $price_sale = get_post_meta($product_id, '_sale_price', true);

                    if (!empty($price_sale))

                        $subtitle_before = html_entity_decode(get_option('ahachat_currency')) . $price_sale;

                    else

                        $subtitle_before = html_entity_decode(get_option('ahachat_currency')) . $price;


                    $subtitle = html_entity_decode($subtitle_before . " - " . get_the_title($product_id));

                    $image_url = wp_get_attachment_image_src(get_post_thumbnail_id($product_id), 'full', false)[0];

                    $image_url = str_replace("http://", "https://", $image_url);

                    $button_view_url_product = get_the_permalink($product_id);

                    $button_view_url_product = str_replace("http://", "https://", $button_view_url_product);

                    $url_proudct_id_quantiy = $product_id . "&quantity=" . $quantity_product;

                    $url_button_generic = esc_url_raw(add_query_arg('multi-product-add', $url_proudct_id_quantiy, wc_get_checkout_url()));

                    $url_button_generic = str_replace("http://", "https://", $url_button_generic);

                    if (!isset($ahachat_first_reminder['checkout']))

                        $title_button_generic = "Checkout";

                    else

                        $title_button_generic = $ahachat_first_reminder['checkout'];//

                    $array_product_mode[] = array(

                        "title" => $title . ' X ' . $quantity_product,

                        "subtitle" => $subtitle,

                        "image_url" => $image_url,

                        "default_action" => array("type" => "web_url", "url" => $button_view_url_product,

                            "messenger_extensions" => true,

                            "webview_height_ratio" => "tall",

                            "fallback_url" => $button_view_url_product),

                        "buttons" => array(array("type" => "web_url",

                            "url" => $url_button_generic, "title" => $title_button_generic))

                    );

                    if (!isset($ahachat_first_reminder['something']) && empty($ahachat_first_reminder['something'])) {
                        $content_message = "You forgot your shopping cart";
                    } else {
                        $content_message = $ahachat_first_reminder['something'];
                    }

                    $ahachat_app_test_mode = get_option('ahachat_is_test_mode');

                    if ($ahachat_app_test_mode) {
                        $recipient = $fb_api->AHA_Send_message_text_user_ref($page_id, $page_token, $content_message, $user_ref);
                        if ($recipient == "(#100) No matching user found" || $recipient == "(#230) Requires pages_messaging_subscriptions permission to manage the object") {
                            echo "error";
                            die;
                        }

                        $fb_api->AHA_Send_message_one_product_user_ref($page_id, $page_token, $user_ref, $array_product_mode);

                        $list_statistical = $wpdb->get_row("SELECT * FROM $ahachat_table_statistical WHERE day='" . $day . "' AND month='" . $month . "' AND year='" . $year . "' ");

                        if (empty($list_statistical) || $list_statistical == NULL || $list_statistical == "")://

                            $user_test = 1;

                            $send_user = 1;

                            $list_user_test[] = array(

                                'cookie_browser' => $session_user,

                                'page_id' => $page_id

                            );

                            $arr_list_user = serialize($list_user_test);

                            $wpdb->insert($ahachat_table_statistical,

                                array(

                                    'user_test' => $user_test,

                                    'send_user' => $send_user,

                                    'first_reminder_sent' => 0,

                                    'second_reminder_sent' => 0,

                                    'third_reminder_sent' => 0,

                                    'list_user' => $arr_list_user,

                                    'day' => $day,

                                    'month' => $month,

                                    'year' => $year,

                                    'date_statis' => $ahachat_date_statistical

                                ), array('%d', '%d', '%s', '%s', '%s', '%s', '%d', '%d', '%d', '%s'));

                        else:

                            $array_list_user = unserialize($list_statistical->list_user);

                            $user_test = $list_statistical->user_test;

                            $send_user = $list_statistical->send_user + 1;

                            $arr_recipient_id = array();

                            foreach ($array_list_user as $key => $value) {

                                array_push($arr_recipient_id, $value["cookie_browser"]);

                                $list_user_test[] = array(

                                    'cookie_browser' => $value["cookie_browser"],

                                    'page_id' => $value["page_id"]

                                );

                            }

                            if (!in_array($session_user, $arr_recipient_id)) {

                                $list_user_test[] = array(

                                    'cookie_browser' => $session_user,

                                    'page_id' => $page_id,

                                );

                                $user_test = $user_test + 1;

                            }

                            $arr_list_user = serialize($list_user_test);

                            // update : number user test, send number user test

                            $wpdb->update(

                                $ahachat_table_statistical,

                                array(

                                    'user_test' => $user_test,

                                    'send_user' => $send_user,

                                    'list_user' => $arr_list_user

                                ),

                                array('date_statis' => $ahachat_date_statistical),

                                array('%d', '%d', '%s'),

                                array('%s')

                            );

                        endif;
                    }

                    // list user add to cart --- use custom post type

                    $post_type_user_add_cart = new AHA_POST_TYPE_USER_ADD_TO_CART();

                    $agrs = array(

                        'cookie_browser' => $session_user,

                        'page_id' => $page_id

                    );

                    if (!$post_type_user_add_cart->CheckUserExit($agrs)) {
                        $common_data = "-";

                        $product_quantity_js = serialize($product_quantity);

                        $arr = array(

                            'mess' => "",

                            'post_date' => current_time('Y-m-d H:i:s'),

                            'post_type' => AHACHAT_USER_ADD_TO_CART_POST_TYPE,

                            'post_status' => 'publish',

                            'ahachat_avatar_user' => $common_data,

                            'ahachat_first_name_user' => $common_data,

                            'ahachat_last_name_user' => $common_data,

                            'ahachat_gender_user' => $common_data,

                            'ahachat_locale_user' => $common_data,

                            'ahachat_cookie_browser' => $session_user,

                            'ahachat_user_ref' => $user_ref,

                            'ahachat_sender_id' => $common_data,

                            'ahachat_user_blacklist' => 'no',

                            'ahachat_page_id' => $page_id,

                            'ahachat_product_user' => $product_quantity_js,

                            'ahachat_type' => 'Add-to-cart'

                        );

                        $User_Add_Cart = $post_type_user_add_cart->Insert($arr);

                    } else {

                        $pid = $post_type_user_add_cart->Aha_Post_ID($agrs);

                        $product_quantity_js = serialize($product_quantity);

                        update_post_meta($pid, 'ahachat_product_user', $product_quantity_js);

                        $ahachat_type = "Add-to-cart";

                        $list_type = get_post_meta($pid, 'ahachat_type', true);

                        $array_type = explode(",", $list_type);

                        if (!in_array($ahachat_type, $array_type)) {

                            array_push($array_type, $ahachat_type);

                        }

                        $ahachat_type = implode(",", $array_type);

                        update_post_meta($pid, 'ahachat_type', $ahachat_type);

                        update_post_meta($pid, 'ahachat_user_ref', $user_ref);

                    }

                }


                die("success");

            endif;

        }

        // AJAX // Remove

        public function ahachat_remove_product_cart()
        {

            if (isset($_POST['product_id'])) {

                global $woocommerce, $wpdb;

                $session_user = $_POST["cookie_browser"];

                $product_id = $_POST['product_id'];

                //

                $items = $woocommerce->cart->get_cart();

                $product_info = array();

                $product_quantity = array();

                foreach ($items as $item => $values) {

                    $product_info[] = array(

                        'product_id' => $values["product_id"],

                        'quantity' => $values["quantity"]

                    );

                }

                if (count($product_info) > 0) {

                    foreach ($product_info as $key => $cart) {

                        if ($cart["product_id"] == $product_id) {

                            unset($product_info[$key]);

                        } else {

                            $product_quantity[] = array(

                                'product_id' => $cart["product_id"],

                                'quantity' => $cart["quantity"]

                            );

                        }

                    }

                }


                //

                $table_user_ref = AHACHAT_USER_REF_TABLE;

                $row_user_ref = $wpdb->get_row("SELECT * FROM $table_user_ref WHERE session_key='" . $session_user . "' ");

                if (!empty($row_user_ref)) {


                    $cart = serialize($product_quantity);

                    $wpdb->update(

                        $table_user_ref,

                        array(

                            'your_cart' => $cart,

                            'update_time' => date('Y-m-d H:i:s')

                        ),

                        array('session_key' => $session_user),

                        array('%s', '%s'),

                        array('%s')

                    );

                }

                /********PRODUCT IN ADD TO CART USER*******/

                $page_id = get_option('ahachat_page_id');

                $post_type_user_add_cart = new AHA_POST_TYPE_USER_ADD_TO_CART();

                $agrs = array(

                    'cookie_browser' => $session_user,

                    'page_id' => $page_id

                );

                if ($post_type_user_add_cart->CheckUserExit($agrs)) {

                    $pid = $post_type_user_add_cart->Aha_Post_ID($agrs);

                    $arr_cart = serialize($product_quantity);


                    update_post_meta($pid, 'ahachat_product_user', $arr_cart);

                }

                //====excute mail

                $post_type_get_email = new AHA_POST_TYPE_USER_EMAIL;

                $user_email = !empty($_POST["user_email"]) ? $_POST["user_email"] : "";

                if (!empty($user_email)) {

                    $agrs_email = array('email' => $user_email);

                    if (count($product_quantity) > 0) {

                        $reminder_email = "yes";

                    } else {

                        $reminder_email = "no";

                    }

                    if (!$post_type_get_email->CheckUserExit($agrs_email)) {

                        $arr = array(

                            'mess' => "",

                            'post_date' => current_time('Y-m-d H:i:s'),

                            'post_type' => AHACHAT_LIST_EMAIL_POST_TYPE,

                            'post_status' => 'publish',

                            'cookie_popup_br' => 0,

                            'ahachat_email' => $user_email,

                            'ahachat_email_product' => serialize($product_quantity),

                            'ahachat_email_reminder' => $reminder_email

                        );

                        $add_email = $post_type_get_email->InsertEmail($arr);

                    } else {


                        $postid = $post_type_get_email->CheckMailPostID($agrs_email);


                        update_post_meta($postid, 'ahachat_email_product', serialize($product_quantity));

                        update_post_meta($postid, 'ahachat_email_reminder', $reminder_email);

                    }


                } else {

                    //not login

                    $cookie_popup_br = $_POST["cookie_popup"];

                    $agrs_email = array('cookie_popup' => $cookie_popup_br);

                    if (count($product_quantity) > 0) {

                        $reminder_email = "yes";

                    } else {

                        $reminder_email = "no";

                    }

                    $postid = $post_type_get_email->CheckCookiePostID($agrs_email);

                    if ($postid) {

                        update_post_meta($postid, 'ahachat_email_product', serialize($product_quantity));

                        update_post_meta($postid, 'ahachat_email_reminder', $reminder_email);

                    }


                }

                //

                die("success");

            }

        }

        // AJAX // UPDATE

        public function ahachat_update_product_cart()
        {


            if (isset($_POST["arr_your_cart"])) {

                global $wpdb;

                $data_cart = $_POST['arr_your_cart'];

                $table_user_ref = AHACHAT_USER_REF_TABLE;

                $session_user = $_POST["cookie_browser"];

                $page_id = get_option('ahachat_page_id');

                $cart = serialize($data_cart);

                $wpdb->update(

                    $table_user_ref,

                    array(

                        'your_cart' => $cart,

                        'status_send_first' => 0,

                        'status_send_second' => 0,

                        'status_send_third' => 0,

                        'update_time' => date('Y-m-d H:i:s', time())

                    ),

                    array('session_key' => $session_user),

                    array('%s', '%d', '%d', '%s'),

                    array('%s')

                );

                $post_type_user_add_cart = new AHA_POST_TYPE_USER_ADD_TO_CART();

                $agrs = array(

                    'cookie_browser' => $session_user,

                    'page_id' => $page_id

                );

                if ($post_type_user_add_cart->CheckUserExit($agrs)) {

                    $pid = $post_type_user_add_cart->Aha_Post_ID($agrs);

                    update_post_meta($pid, 'ahachat_product_user', $cart);

                }

                //====excute mail

                $post_type_get_email = new AHA_POST_TYPE_USER_EMAIL;

                $user_email = !empty($_POST["user_email"]) ? $_POST["user_email"] : "";

                if (!empty($user_email)) {

                    $agrs_email = array('email' => $user_email);

                    if (count($data_cart) > 0) {

                        $reminder_email = "yes";

                    } else {

                        $reminder_email = "no";

                    }

                    if (!$post_type_get_email->CheckUserExit($agrs_email)) {

                        $arr = array(

                            'mess' => "",

                            'post_date' => current_time('Y-m-d H:i:s'),

                            'post_type' => AHACHAT_LIST_EMAIL_POST_TYPE,

                            'post_status' => 'publish',

                            'cookie_popup_br' => 0,

                            'ahachat_email' => $user_email,

                            'ahachat_email_product' => serialize($data_cart),

                            'ahachat_email_reminder' => $reminder_email

                        );

                        $add_email = $post_type_get_email->InsertEmail($arr);

                    } else {


                        $postid = $post_type_get_email->CheckMailPostID($agrs_email);


                        update_post_meta($postid, 'ahachat_email_product', serialize($data_cart));

                        update_post_meta($postid, 'ahachat_email_reminder', $reminder_email);

                    }


                } else {

                    //not login

                    $cookie_popup_br = $_POST["cookie_popup"];

                    $agrs_email = array('cookie_popup' => $cookie_popup_br);

                    if (count($data_cart) > 0) {

                        $reminder_email = "yes";

                    } else {

                        $reminder_email = "no";

                    }

                    $postid = $post_type_get_email->CheckCookiePostID($agrs_email);

                    if ($postid) {

                        update_post_meta($postid, 'ahachat_email_product', serialize($data_cart));

                        update_post_meta($postid, 'ahachat_email_reminder', $reminder_email);

                    }


                }

                die("success");

            }

        }


        // AJAX // SKIP IT ONETIME

        public function ahachat_skip_it_ontime()
        {

            if (isset($_POST['ahachat_skip_it'])) {

                if (get_option('ahachat_is_skip_ontime')) {

                    $cookie_browser = $_POST["cookie_browser"];

                    $ahachat_session_id = $cookie_browser;


                    if (get_option("ahachat_list_user_skip_it")) {

                        $array_list_user_skip_it = get_option("ahachat_list_user_skip_it");

                        if (!in_array($ahachat_session_id, $array_list_user_skip_it)) {

                            array_push($array_list_user_skip_it, $ahachat_session_id);

                            update_option("ahachat_list_user_skip_it", $array_list_user_skip_it);

                        }

                    } else {

                        $array_list_user_skip_it = array($ahachat_session_id);

                        update_option("ahachat_list_user_skip_it", $array_list_user_skip_it);

                    }


                }

                die("success");

            }

        }

        // SUBMIT EMAIL

        public function ahachat_submit_add_email()
        {

            if (isset($_POST["email"])) {

                //

                global $woocommerce;

                $email = $_POST['email'];

                $product_id = $_POST["product_id"];

                $quantity = $_POST["quantity"];

                $cookie_pop_br = $_POST['cookie_popup'];

                $post_type_get_email = new AHA_POST_TYPE_USER_EMAIL;

                //

                $items = $woocommerce->cart->get_cart();

                $product_info = array();

                $product_quantity = array();

                foreach ($items as $item => $values) {

                    $product_info[] = array(

                        'product_id' => $values["product_id"],

                        'quantity' => $values["quantity"]

                    );

                }

                $count_product_quantity = 0;

                if (count($product_info) > 0) {

                    foreach ($product_info as $key => $cart) {

                        if ($cart["product_id"] == $_POST["product_id"]) {

                            $quantity = $cart["quantity"] + $_POST["quantity"];

                            $product_quantity[] = array(

                                'product_id' => $cart["product_id"],

                                'quantity' => $quantity

                            );

                            $count_product_quantity++;

                        } else {

                            $product_quantity[] = array(

                                'product_id' => $cart["product_id"],

                                'quantity' => $cart["quantity"]

                            );

                        }

                    }

                }

                if ($count_product_quantity == 0) {

                    $product_quantity[] = array(

                        'product_id' => $_POST["product_id"],

                        'quantity' => $_POST["quantity"]

                    );

                }

                //

                $agrs_email = array('email' => $email);


                if (!$post_type_get_email->CheckUserExit($agrs_email)) {

                    $arr = array(

                        'mess' => "",

                        'post_date' => current_time('Y-m-d H:i:s'),

                        'post_type' => AHACHAT_LIST_EMAIL_POST_TYPE,

                        'post_status' => 'publish',

                        'cookie_popup_br' => $cookie_pop_br,

                        'ahachat_email' => $email,

                        'ahachat_email_product' => serialize($product_quantity),

                        'ahachat_email_reminder' => 'yes'

                    );

                    $add_email = $post_type_get_email->InsertEmail($arr);

                } else {


                    $postid = $post_type_get_email->CheckMailPostID($agrs_email);


                    update_post_meta($postid, 'ahachat_email_product', serialize($product_quantity));

                    update_post_meta($postid, 'cookie_popup_br', $cookie_pop_br);

                }

                die("success");

            }

        }

        public function ahachat_get_all_user_add()
        {

            if (isset($_POST['id_user_send'])) {
                $args = array(

                    'posts_per_page' => -1,

                    'post_type' => AHACHAT_USER_ADD_TO_CART_POST_TYPE,

                    'meta_query' => array(

                        'relation' => 'AND',

                        array(

                            'key' => 'ahachat_sender_id',

                            'value' => '-',

                            'compare' => '!='

                        )

                    ),

                );

                $post_send = get_posts($args);

                if (count($post_send) > 0) {

                    $arr_list_user = array();

                    foreach ($post_send as $key => $user_id) {

                        array_push($arr_list_user, $user_id->ID);

                    }

                    $str_list_user = implode(',', $arr_list_user);

                    die($str_list_user);

                } else {

                    die("error");

                }

            }

        }

        public function ahachat_send_one_end()
        {

            if (isset($_POST['id_user_send'])) {

                //echo $_POST['id_user_send'];die;

                global $wpdb;

                $fb_api = new AHACHAT_WP_API();

                $user_send = $_POST['id_user_send'];

                $content_message = $_POST['mesage_messenger'];

                $message_tag = $_POST['message_tag'];

                $array_result = array();
                $error_fail = "";

                $count_send = 0;

                $count_fail = 0;

                $sender_id = get_post_meta($user_send, 'ahachat_sender_id', true);

                $page_id_send = get_post_meta($user_send, 'ahachat_page_id', true);

                $page_access_token = $fb_api->AHA_Get_Access_Token_Page();

                if (isset($page_access_token["access_token"])) {

                    $page_token = $page_access_token["access_token"];


                    $recipient = $fb_api->AHA_Send_message_user_add_cart_WITH_TAG($page_id_send, $page_token, $content_message, $sender_id, $message_tag);

                    if ($recipient == "(#100) No matching user found" || $recipient == "(#230) Requires pages_messaging_subscriptions permission to manage the object") {

                        $error_fail = $sender_id . ": " . $recipient;

                        die($error_fail);

                    } else {

                        die("done");

                    }

                } else {

                    die("error");

                }

            }

        }


        public function ahachat_cartback_get_list_us_shortcode()
        {

            if (isset($_POST['ahachat_user_ref'])) {

                $user_ref = $_POST['ahachat_user_ref'];

                $fb_api = new AHACHAT_WP_API();

                $page_id = get_option('ahachat_page_id');

                $abd_shortcode = get_option('ahachat_shortcode');

                if (!empty($abd_shortcode)) {

                    if (isset($abd_shortcode['value'])) {

                        if (!empty($abd_shortcode['value'])) {

                            $content_message = $abd_shortcode['value'];

                        } else {

                            $content_message = "Coupon for the special product";

                        }

                    }

                } else {

                    $content_message = "Coupon for the special product";

                }

                $page_access_token = $fb_api->AHA_Get_Access_Token_Page();

                if (gettype($page_access_token) == "array") {

                    $page_token = $page_access_token["access_token"];

                    $recipient = $fb_api->AHA_Send_message_text_user_ref($page_id, $page_token, $content_message, $user_ref);

                    if ($recipient == "(#100) No matching user found" || $recipient == "(#230) Requires pages_messaging_subscriptions permission to manage the object") {

                        die("error");

                    } else {

                        // list user add to cart --- use custom post type

                        $recipient = substr($recipient, 0, 18);

                        $post_type_user_add_cart = new AHA_POST_TYPE_USER_ADD_TO_CART();

                        $agrs = array(

                            'recipient_id' => $recipient,

                            'page_id' => $page_id

                        );

                        if (!$post_type_user_add_cart->CheckUserExit($agrs)) {

                            $avatar = "-";

                            $first_name = "-";

                            $last_name = "-";

                            $gender = "-";

                            $language = "-";

                            $product_quantity[] = array(

                                'product_id' => 0,

                                'quantity' => 1

                            );

                            $product_quantity_js = serialize($product_quantity);

                            $arr = array(

                                'mess' => "",

                                'post_date' => current_time('Y-m-d H:i:s'),

                                'post_type' => AHACHAT_USER_ADD_TO_CART_POST_TYPE,

                                'post_status' => 'publish',

                                'ahachat_avatar_user' => $avatar,

                                'ahachat_first_name_user' => $first_name,

                                'ahachat_last_name_user' => $last_name,

                                'ahachat_gender_user' => $gender,

                                'ahachat_locale_user' => $language,

                                'ahachat_recipient_id_user' => $recipient,

                                'ahachat_user_ref' => $user_ref,

                                'ahachat_page_id' => $page_id,

                                'ahachat_product_user' => $product_quantity_js,

                            );

                            $User_Add_Cart = $post_type_user_add_cart->Insert($arr);

                        } else {

                            $pid = $post_type_user_add_cart->Aha_Post_ID($agrs);

                            $arr_product_quantity = unserialize(get_post_meta($pid, 'ahachat_product_user', true));

                            $count_product_quantity = 0;

                            if (count($arr_product_quantity) > 0 && !empty(get_post_meta($pid, 'ahachat_product_user', true))) {

                                foreach ($arr_product_quantity as $key => $cart) {

                                    if ($cart["product_id"] != 0) {

                                        $product_quantity[] = array(

                                            'product_id' => $cart["product_id"],

                                            'quantity' => $cart["quantity"]

                                        );

                                    }

                                }

                            }

                            if ($count_product_quantity == 0) {

                                $product_quantity[] = array(

                                    'product_id' => 0,

                                    'quantity' => 1

                                );

                            }

                            $product_quantity_js = serialize($product_quantity);

                            update_post_meta($pid, 'ahachat_product_user', $product_quantity_js);

                        }

                        die($recipient);

                    }

                } else {

                    die("error");

                }

            }

        }


        // SHORTCODE

        public function ahachat_action_save_change_shortcode()
        {

            if (isset($_POST['title']) && isset($_POST["sub_title"])) {

                global $wpdb; // use query table

                $table_shortcode = AHACHAT_SHORTCODES_TABLE;

                $title = (isset($_POST["title"]) && !empty($_POST["title"])) ? $_POST["title"] : "15% discount";

                $sub_title = (isset($_POST["sub_title"]) && !empty($_POST["sub_title"])) ? $_POST["sub_title"] : "Get your 15% discount now by subscribing to our newsletter in facebook messenger. Just click the blue button below.";

                $message = (isset($_POST["message"]) && !empty($_POST["message"])) ? $_POST["message"] : "Congratulations! You’ve successfully got the coupon! Please check your inbox!";

                $message_sendto = (isset($_POST["message_sendto"]) && !empty($_POST["message_sendto"])) ? $_POST["message_sendto"] : "Congratulations! You’ve successfully got the coupon! Please check your inbox!";


                $action_shortcode = isset($_POST["action_shortcode"]) ? $_POST["action_shortcode"] : "create";

                $button_type = isset($_POST["button_type"]) ? $_POST["button_type"] : "send_to";

                $message_type = isset($_POST["message_type"]) ? $_POST["message_type"] : "custom_text";

                $text_send_me = isset($_POST["text_send_me"]) ? $_POST["text_send_me"] : "Send me Coupon";

                $list_product = isset($_POST["list_product"]) ? $_POST["list_product"] : "";

                if ($action_shortcode == "create") {

                    $insert = $wpdb->insert($table_shortcode,

                        array(

                            'title' => $title,

                            'sub_title' => $sub_title,

                            'button_type' => $button_type,

                            'message_type' => $message_type,

                            'text_type_cb' => $text_send_me,

                            'list_product' => $list_product,

                            'message' => $message_sendto,

                            'message_cb' => $message,

                        ), array('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s'));

                    if ($insert) {

                        $shortcode_create = $wpdb->insert_id;

                        //print_r($shortcode_create);die;

                        $html = "<li class='ahachat_popup_dashboard_optins_item ahachat_popup_dashboard_parent_item ahachat_shortcode_show_" . $shortcode_create . "' data-shortcode='" . $shortcode_create . "'>

										<div class='ahachat_popup_dashboard_table_name ahachat_popup_dashboard_table_column'><img style='float: left;margin-right: 5px;' src=''>Shortcode " . $shortcode_create . "

										</div>

										<div class='ahachat_popup_dashboard_table_impressions ahachat_popup_dashboard_table_column ahachat_popup_dashboard_refreshed'>

										</div>

										<div class='ahachat_popup_dashboard_table_conversions ahachat_popup_dashboard_table_column ahachat_popup_dashboard_refreshed'>

												<input readonly='readonly' onclick='select();' id='ahachat_popup_shortcode_" . $shortcode_create . "' style='width: 300px;background: transparent;' type='text' value='[cartback id=" . $shortcode_create . "]'/>

										</div>

										<div class='ahachat_popup_dashboard_table_rate ahachat_popup_dashboard_table_column ahachat_popup_dashboard_refreshed'>

										</div>

										<div class='ahachat_popup_dashboard_table_actions ahachat_popup_dashboard_table_column'>

										<span class='ahachat_tool_action' tooltip='Delete' flow='up'>

											<span style='position: relative;top: 2px' class='et_optin_button icon-trash ahachat_shortcode_delete' title='Delete Shortcode'>	

												<span class='ahachat_popup_dashboard_confirmation'>Delete this optin?

													<span class='ahachat_popup_dashboard_confirm_delete' data-shortcdoe_delete=" . $shortcode_create . ">Yes

													</span>

													<span class='ahachat_popup_dashboard_cancel_delete'>No

													</span>

												</span>

											</span>

										</span>

										

										<span class='ahachat_tool_action' tooltip='Edit' flow='up'>

											<span style='position: relative;top: 2px' class='et_optin_button icon-settings ahachat_edit_shortcode' title='Edit Shortcode' data-shortcode_edit=" . $shortcode_create . "></span>

											<span class='spinner'></span>

										</span>



										<span class='ahachat_tool_action' tooltip='Copy' flow='up'>

											<span style='position: relative;top: 2px' class='et_optin_button ahachat_copy_shortcode ahachat_popup_dashboard_form_optin_duplicate icon-doc' title='Duplicate' data-shortcode_id=" . $shortcode_create . ">

												<span class='spinner'></span>

											</span>

										</span>

															

										</div>

										<div style='clear: both;'></div>

									</li>";

                        die($html);

                    }

                } else {


                    $id_shortcode = (int)$_POST["id_shortcode"];

                    $message = (isset($_POST["message"]) && !empty($_POST["message"])) ? $_POST["message"] : "";

                    $message_sendto = (isset($_POST["message_sendto"]) && !empty($_POST["message_sendto"])) ? $_POST["message_sendto"] : "";

                    if ($message != "" && $message_sendto != "") {

                        $edit = $wpdb->update($table_shortcode,

                            array(

                                'title' => $title,

                                'sub_title' => $sub_title,

                                'button_type' => $button_type,

                                'message_type' => $message_type,

                                'text_type_cb' => $text_send_me,

                                'list_product' => $list_product,

                                'message' => $message_sendto,

                                'message_cb' => $message,

                            ),

                            array('id' => $id_shortcode),

                            array('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s'),

                            array('%d'));

                    } else if ($message != "" && $message_sendto == "") {

                        $edit = $wpdb->update($table_shortcode,

                            array(

                                'title' => $title,

                                'sub_title' => $sub_title,

                                'button_type' => $button_type,

                                'message_type' => $message_type,

                                'text_type_cb' => $text_send_me,

                                'list_product' => $list_product,

                                'message_cb' => $message,


                            ),

                            array('id' => $id_shortcode),

                            array('%s', '%s', '%s', '%s', '%s', '%s', '%s'),

                            array('%d'));

                    } else if ($message == "" && $message_sendto != "") {

                        $edit = $wpdb->update($table_shortcode,

                            array(

                                'title' => $title,

                                'sub_title' => $sub_title,

                                'button_type' => $button_type,

                                'message_type' => $message_type,

                                'text_type_cb' => $text_send_me,

                                'list_product' => $list_product,

                                'message' => $message_sendto,

                            ),

                            array('id' => $id_shortcode),

                            array('%s', '%s', '%s', '%s', '%s', '%s', '%s'),

                            array('%d'));

                    } else if ($message == "" && $message_sendto == "") {

                        $edit = $wpdb->update($table_shortcode,

                            array(

                                'title' => $title,

                                'sub_title' => $sub_title,

                                'button_type' => $button_type,

                                'message_type' => $message_type,

                                'text_type_cb' => $text_send_me,

                                'list_product' => $list_product,


                            ),

                            array('id' => $id_shortcode),

                            array('%s', '%s', '%s', '%s', '%s', '%s'),

                            array('%d'));

                    }


                    if ($edit) {

                        die("edit");

                    }

                }


            }

        }


        public function ahachat_action_eidt_shortcode()
        {

            if (isset($_POST["id_shortcode"])) {

                global $wpdb; // use query table

                $table_shortcode = AHACHAT_SHORTCODES_TABLE;

                $id_shortcode = (int)$_POST["id_shortcode"];

                $shortcode_selected = $wpdb->get_row("SELECT * FROM $table_shortcode WHERE id='" . $id_shortcode . "'");

                print_r(json_encode($shortcode_selected));
                die;

            }

        }


        public function ahachat_action_delete_shortcode()
        {

            if (isset($_POST["id_shortcode"])) {

                global $wpdb; // use query table

                $table_shortcode = AHACHAT_SHORTCODES_TABLE;

                $id_shortcode = (int)$_POST["id_shortcode"];

                //die($_POST["id_shortcode"]);

                $delete = $wpdb->delete($table_shortcode, array('id' => $id_shortcode), array('%d'));

                if ($delete) {

                    die("delete");

                }

            }

        }


        //

        function posts_query($args = array(), $include_post_type = '')
        {


            $query = array(

                'post_type' => 'product',

                'suppress_filters' => true,

                'update_post_term_cache' => false,

                'update_post_meta_cache' => false,

                'post_status' => 'publish',

                'posts_per_page' => 20,

            );

            $args['pagenum'] = isset($args['pagenum']) ? absint($args['pagenum']) : 1;

            if (isset($args['s']) && '' !== $args['s']) {

                $query['s'] = $args['s'];

            }

            $query['offset'] = $args['pagenum'] > 1 ? $query['posts_per_page'] * ($args['pagenum'] - 1) : 0;

            $get_posts = new WP_Query;

            $posts = $get_posts->query($query);

            if (!$get_posts->post_count) {

                return false;

            }

            $results = array();

            foreach ($posts as $post) {

                $results[] = array(

                    'id' => (int)$post->ID,

                    'title' => trim(esc_html(strip_tags(get_the_title($post)))),

                    'post_type' => $post->post_type,

                );

            }

            wp_reset_postdata();

            return $results;

        }

        public function ahachat_popup_execute_live_search()
        {

            if (!current_user_can('manage_options')) {

                die(-1);

            }

            $search_string = !empty($_POST['dashboard_live_search']) ? sanitize_text_field($_POST['dashboard_live_search']) : '';

            $page = !empty($_POST['dashboard_page']) ? sanitize_text_field($_POST['dashboard_page']) : 1;

            $post_type = !empty($_POST['dashboard_post_type']) ? sanitize_text_field($_POST['dashboard_post_type']) : 'any';

            $full_content = !empty($_POST['dashboard_full_content']) ? sanitize_text_field($_POST['dashboard_full_content']) : 'true';

            $args['s'] = $search_string;

            $args['pagenum'] = $page;

            $results = $this->posts_query($args, $post_type);

            if ('true' === $full_content) {

                $output = '<ul class="ahachat_popup_dashboard_search_results">';

            } else {

                $output = '';

            }

            if (empty($results)) {

                if ('true' === $full_content) {

                    $output .= sprintf(

                        '<li class="ahachat_popup_dashboard_no_res">%1$s</li>',

                        esc_html__('No results found', AHACHAT_WP)

                    );

                }

            } else {

                foreach ($results as $single_post) {

                    $output .= sprintf(

                        '<li data-post_id="%2$s">[%3$s] - %1$s</li>',

                        esc_html($single_post['title']),

                        esc_attr($single_post['id']),

                        esc_html($single_post['post_type'])

                    );

                }

            }

            if ('true' === $full_content) {

                $output .= '</ul>';

            }

            die($output);

        }


        public function ahachat_parse_edit_list_product()
        {

            if (isset($_POST["list_product"])) {

                $show_these_pages = explode(',', $_POST["list_product"]);

                foreach ($show_these_pages as $key => $display_page) { ?>

                    <span data-post_id="<?php echo $display_page; ?>">[product] - <?php echo get_the_title($display_page); ?><span
                                class="ahachat_popup_dashboard_menu_remove"><img class="remove_list_product"
                                                                             style="position: absolute;"
                                                                             src="<?php echo AHACHAT_WP_PLUGIN_PATH . 'assets/images/'.AHACHAT_PREFIX.'remove.png'; ?>"></span></span>

                <?php }

                die();

            }

        }


        public function ahachat_cartback_width_shortcode_custom_text()
        {

            if (isset($_POST["user_ref"])) {

                global $wpdb;

                $ahachat_table_statistical = AHACHAT_ANALYTICS_TABLE;

                $ahachat_date_statistical = date('Y-m-d', time());

                $day = date('d', time());

                $month = date('m', time());

                $year = date('Y', time());

                $fb_api = new AHACHAT_WP_API();

                $page_id = get_option('ahachat_page_id');

                $admin_token = get_option('ahachat_broadcast_token');

                $user_ref = $_POST["user_ref"];

                $content_message = $_POST["message_cb"];

                $cookie_browser = $_POST["cookie_browser"];

                $page_access_token = $fb_api->AHA_Get_Access_Token_Page();

                if (isset($page_access_token["access_token"])) {

                    $page_token = $page_access_token["access_token"];

                    $message_id = $fb_api->AHA_Send_message_text_user_ref($page_id, $page_token, $content_message, $user_ref);

                    //count shortcode user and shortcode sent

                    $list_statistical = $wpdb->get_row("SELECT * FROM $ahachat_table_statistical WHERE day='" . $day . "' AND month='" . $month . "' AND year='" . $year . "' ");

                    $recipient = substr($message_id, 0, 18);

                    if (empty($list_statistical)) {

                        $list_user_shortcode = array($recipient);

                        $arr_list_user = serialize($list_user_shortcode);

                        $wpdb->insert($ahachat_table_statistical,

                            array(

                                'send_user' => 1,

                                'shortcode_user' => 1,

                                'shortcode_sent' => 1,

                                'list_shortcode_user' => $arr_list_user,

                                'day' => $day,

                                'month' => $month,

                                'year' => $year,

                                'date_statis' => $ahachat_date_statistical

                            ), array('%d', '%d', '%d', '%s', '%d', '%d', '%d', '%s'));

                    } else {

                        $shortcode_user = $list_statistical->shortcode_user;

                        $shortcode_sent = $list_statistical->shortcode_sent + 1;

                        $user_sent = $list_statistical->send_user + 1;

                        if ($list_statistical->list_shortcode_user == null) {

                            $array_list_user = array($recipient);

                            $shortcode_user = $shortcode_user + 1;

                        } else {

                            $array_list_user = unserialize($list_statistical->list_shortcode_user);

                            if (!in_array($recipient, $array_list_user)) {

                                array_push($array_list_user, $recipient);

                                $shortcode_user = $shortcode_user + 1;

                            }

                        }


                        $list_user_update = serialize($array_list_user);

                        $wpdb->update(

                            $ahachat_table_statistical,

                            array(

                                'send_user' => $user_sent,

                                'shortcode_user' => $shortcode_user,

                                'shortcode_sent' => $shortcode_sent,

                                'list_shortcode_user' => $list_user_update

                            ),

                            array('day' => $day, 'month' => $month, 'year' => $year),

                            array('%d', '%d', '%d', '%s'),

                            array('%d', '%d', '%d')

                        );

                    }

                    $post_type_user_shortcode = new AHA_POST_TYPE_USER_ADD_TO_CART();

                    /**/

                    $agrs = array(

                        'cookie_browser' => $cookie_browser,

                        'page_id' => $page_id

                    );

                    if (!$post_type_user_shortcode->CheckUserExit($agrs)) {

                        $common = "-";

                        $product_quantity[] = array(

                            'product_id' => -1,

                            'quantity' => -1

                        );

                        $product_quantity_js = serialize($product_quantity);

                        $arr = array(

                            'mess' => "",

                            'post_date' => current_time('Y-m-d H:i:s'),

                            'post_type' => AHACHAT_USER_ADD_TO_CART_POST_TYPE,

                            'post_status' => 'publish',

                            'ahachat_avatar_user' => $common,

                            'ahachat_first_name_user' => $common,

                            'ahachat_last_name_user' => $common,

                            'ahachat_gender_user' => $common,

                            'ahachat_locale_user' => $common,

                            'ahachat_recipient_id_user' => $recipient,

                            'ahachat_user_ref' => $user_ref,

                            'ahachat_cookie_browser' => $cookie_browser,

                            'ahachat_sender_id' => '-',

                            'ahachat_user_blacklist' => 'no',

                            'ahachat_page_id' => $page_id,

                            'ahachat_product_user' => $product_quantity_js,

                            'ahachat_type' => 'Shortcode'

                        );

                        $User_Shortcode = $post_type_user_shortcode->Insert($arr);

                    } else {

                        $pid = $post_type_user_shortcode->Aha_Post_ID($agrs);

                        $arr_product_quantity = unserialize(get_post_meta($pid, 'ahachat_product_user', true));

                        $ahachat_type = 'Shortcode';

                        $product_quantity = array();

                        if (count($arr_product_quantity) > 0) {

                            $flag = 0;
                            $array_product_flag = array();

                            foreach ($arr_product_quantity as $key => $cart) {

                                array_push($array_product_flag, $cart["product_id"]);

                                $product_quantity[] = array(

                                    'product_id' => $cart["product_id"],

                                    'quantity' => $cart["quantity"]

                                );

                            }

                            if (!in_array(-1, $array_product_flag)) {

                                $product_quantity[] = array(

                                    'product_id' => -1,

                                    'quantity' => -1

                                );

                            }


                        } else {

                            $product_quantity[] = array(

                                'product_id' => -1,

                                'quantity' => -1

                            );

                        }


                        $list_type = get_post_meta($pid, 'ahachat_type', true);


                        $array_type = explode(",", $list_type);

                        if (!in_array($ahachat_type, $array_type)) {

                            array_push($array_type, $ahachat_type);

                        }


                        update_post_meta($pid, 'ahachat_product_user', serialize($product_quantity));

                        $ahachat_type = implode(",", $array_type);

                        update_post_meta($pid, 'ahachat_type', $ahachat_type);

                    }

                    /**/

                    die;

                } else {

                    die("error send message");

                }


            }

        }


        public function ahachat_cartback_width_shortcode_send_reminder()
        {

            if (isset($_POST["list_product"])) {

                $list_product = $_POST["list_product"];

                $user_ref = $_POST["user_ref"];

                if (!empty($list_product)) {


                    global $wpdb;

                    $table_user_ref = AHACHAT_USER_REF_TABLE;

                    $session_user = $_POST["cookie_browser"];

                    $product_ids = explode(',', $list_product);

                    $quantity = array();


                    // ADD MULTIPE PRODUCT WITH MULTIPE QUANTITY (HERE: ALL QUANTITY 1)


                    foreach ($product_ids as $key => $product) {

                        array_push($quantity, 1);

                    }

                    foreach ($product_ids as $key => $product_id) {

                        $product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($product_id));

                        $was_added_to_cart = false;

                        $adding_to_cart = wc_get_product($product_id);

                        if (!$adding_to_cart) {

                            continue;

                        }

                        // For now, quantity applies to all products.. This could be changed easily enough, but I didn't need this feature.

                        $quantity_number = wc_stock_amount($quantity[$key]);

                        $passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);

                        if ($passed_validation && false !== WC()->cart->add_to_cart($product_id, $quantity_number)) {

                            wc_add_to_cart_message(array($product_id => $quantity_number), true);

                        }

                    }

                    if (wc_notice_count('error') === 0) {

                        // If has custom URL redirect there

                        if ($url = apply_filters('woocommerce_add_to_cart_redirect', false)) {

                            wp_safe_redirect($url);

                            exit;

                        } elseif (get_option('woocommerce_cart_redirect_after_add') === 'yes') {

                            wp_safe_redirect(wc_get_cart_url());

                            exit;

                        }

                    }


                    $row_user_ref = $wpdb->get_row("SELECT * FROM $table_user_ref WHERE session_key='" . $session_user . "' ");

                    if (empty($row_user_ref) || $row_user_ref == NULL || $row_user_ref == ""):// add row into table


                        foreach ($product_ids as $key => $product_id) {

                            $your_cart[] = array(

                                'product_id' => $product_id,

                                'quantity' => 1,

                            );

                        }

                        $cart = serialize($your_cart);

                        $wpdb->insert($table_user_ref,

                            array(

                                'user_ref' => $user_ref,

                                'your_cart' => $cart,

                                'session_key' => $session_user,

                                'status_send_first' => 0,

                                'status_send_second' => 0,

                                'status_send_third' => 0,

                                'is_shortcode' => 1,

                                'create_time' => date('Y-m-d H:i:s', time()),

                                'update_time' => date('Y-m-d H:i:s', time())

                            ), array('%s', '%s', '%s', '%d', '%d', '%s', '%s'));

                    else:  // update row with session_key into table

                        $array_cart_1 = unserialize($row_user_ref->your_cart);

                        foreach ($product_ids as $key => $product_id) {

                            $your_cart_2[] = array(

                                'product_id' => $product_id,

                                'quantity' => 1,

                            );

                        }

                        $total_yourcart = array_merge($array_cart_1, $your_cart_2);

                        $arr = array();

                        foreach ($total_yourcart as $key => $value) {


                            if (count($arr) > 0) {

                                $count = 0;

                                foreach ($arr as $key_1 => $cart) {

                                    if ($cart["product_id"] == $value["product_id"]) {

                                        $quantity = $cart["quantity"] + $value["quantity"];

                                        $arr[$key_1]["product_id"] = $value["product_id"];

                                        $arr[$key_1]["quantity"] = $quantity;

                                        $count++;

                                    }

                                }

                                if ($count == 0) {

                                    $arr[] = array(

                                        'product_id' => $value["product_id"],

                                        'quantity' => $value["quantity"]

                                    );

                                }


                            } else {

                                $arr[] = array(

                                    'product_id' => $value['product_id'],

                                    'quantity' => $value['quantity'],

                                );


                            }


                        }

                        $cart = serialize($arr);

                        $wpdb->update(

                            $table_user_ref,

                            array(

                                'user_ref' => $user_ref,

                                'your_cart' => $cart,

                                'status_send_first' => 0,

                                'status_send_second' => 0,

                                'status_send_third' => 0,

                                'is_shortcode' => 1,

                                'create_time' => date('Y-m-d H:i:s', time()),

                                'update_time' => date('Y-m-d H:i:s', time())

                            ),

                            array('session_key' => $session_user),

                            array('%s', '%s', '%d', '%d', '%s', '%s'),

                            array('%s')

                        );

                    endif;

                    // ADD MULTIPE PRODUCT WITH MULTIPE QUANTITY (HERE: ALL QUANTITY 1)


                    die();

                } else {

                    die("error");

                }


            }

        }

        public function ahachat_message_with_text($fanpage_id, $fanpage_token, $content_message, $user_ref, $sender_id, $button = "")
        {

            $fb_api = new AHACHAT_WP_API();

            if (!empty($button)) {


                $message = $fb_api->AHA_SEND_TEXT_BUTTON($fanpage_id, $fanpage_token, $content_message, $user_ref, $sender_id, $button);


            } else {

                if (empty($user_ref)) {

                    $message = $fb_api->AHA_Send_message_user_add_cart($fanpage_id, $fanpage_token, $content_message, $sender_id);

                } else {

                    $message = $fb_api->AHA_Send_message_text_user_ref($fanpage_id, $fanpage_token, $content_message, $user_ref);

                }


            }


            return $message;

        }

        public function ahachat_get_info_license()
        {

            if (isset($_POST["data_return"])) {

                $data_return = $_POST["data_return"];

                $personal_token = $_POST["personal_token"];

                update_option("cartback_personal_token", $personal_token);

                update_option("license_cb_active", $data_return);

                die("success");

            }

        }

    }

}

new AHACHAT_WP_AJAX_CART();