<?php

if (!defined('ABSPATH')) exit; // Exit if accessed direct;


/****************************************************************/

add_action('wp_loaded', 'ahachat_check_when_user_click_checkout');

if (!function_exists('ahachat_check_when_user_click_checkout')) {
    function ahachat_check_when_user_click_checkout()
    {

        if (isset($_GET["multi-product-add"]) && isset($_GET["quantity"])) {

            if (WC()->cart->is_empty()):

                // Fire before the WC_Form_Handler::add_to_cart_action callback.

                add_action('wp_loaded', 'ahachat_custom_product_link', 15);

            endif;


            global $wpdb;

            $reminder = $_GET["reminder"];

            $table_analystic_fb = AHACHAT_ANALYTICS_FB_TABLE;

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

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

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

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

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

            if (empty($list_analystic_fb))://

                $click_first = (isset($reminder) && $reminder == "first") ? 1 : 0;

                $click_second = (isset($reminder) && $reminder == "second") ? 1 : 0;

                $click_third = (isset($reminder) && $reminder == "third") ? 1 : 0;

                $first_reminder = array(

                    'click' => $click_first,

                    'purchases' => 0,

                    'revenue' => 0

                );

                $second_reminder = array(

                    'click' => $click_second,

                    'purchases' => 0,

                    'revenue' => 0

                );

                $third_reminder = array(

                    'click' => $click_third,

                    'purchases' => 0,

                    'revenue' => 0

                );

                $wpdb->insert($table_analystic_fb,

                    array(

                        'count_user_click' => 1,

                        'count_user_order' => 0,

                        'order_total_suc' => 0,

                        'first_reminder' => serialize($first_reminder),

                        'second_reminder' => serialize($second_reminder),

                        'third_reminder' => serialize($third_reminder),

                        'arr_order' => array(),

                        'day' => $day,

                        'month' => $month,

                        'year' => $year,

                        'date_statis' => $date_current

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

            else:

                $array_first_reminder = unserialize($list_analystic_fb->first_reminder);

                $array_second_reminder = unserialize($list_analystic_fb->second_reminder);

                $array_third_reminder = unserialize($list_analystic_fb->third_reminder);

                $click_first = (isset($reminder) && $reminder == "first") ? ((isset($array_first_reminder['click']) && !empty($array_first_reminder['click'])) ? (double)$array_first_reminder['click'] + 1 : 1) : ((isset($array_first_reminder['click']) && !empty($array_first_reminder['click'])) ? (double)$array_first_reminder['click'] : 0);

                $click_second = (isset($reminder) && $reminder == "second") ? ((isset($array_second_reminder['click']) && !empty($array_second_reminder['click'])) ? (double)$array_second_reminder['click'] + 1 : 1) : ((isset($array_second_reminder['click']) && !empty($array_second_reminder['click'])) ? (double)$array_second_reminder['click'] : 0);

                $click_third = (isset($reminder) && $reminder == "third") ? ((isset($array_third_reminder['click']) && !empty($array_third_reminder['click'])) ? (double)$array_third_reminder['click'] + 1 : 1) : ((isset($array_third_reminder['click']) && !empty($array_third_reminder['click'])) ? (double)$array_third_reminder['click'] : 0);

                $purchases_first = (isset($array_first_reminder['purchases'])) ? (double)$array_first_reminder['purchases'] : 0;

                $purchases_second = (isset($array_second_reminder['purchases'])) ? (double)$array_second_reminder['purchases'] : 0;

                $purchases_third = (isset($array_third_reminder['purchases'])) ? (double)$array_third_reminder['purchases'] : 0;

                $revenue_first = (isset($array_first_reminder['revenue'])) ? (double)$array_first_reminder['revenue'] : 0;

                $revenue_second = (isset($array_second_reminder['revenue'])) ? (double)$array_second_reminder['revenue'] : 0;

                $revenue_third = (isset($array_third_reminder['revenue'])) ? (double)$array_third_reminder['revenue'] : 0;

                $first_reminder = array(

                    'click' => $click_first,

                    'purchases' => $purchases_first,

                    'revenue' => $revenue_first

                );

                $second_reminder = array(

                    'click' => $click_second,

                    'purchases' => $purchases_second,

                    'revenue' => $revenue_second

                );

                $third_reminder = array(

                    'click' => $click_third,

                    'purchases' => $purchases_third,

                    'revenue' => $revenue_third

                );

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

                $wpdb->update(

                    $table_analystic_fb,

                    array(

                        'count_user_click' => $list_analystic_fb->count_user_click + 1,

                        'first_reminder' => serialize($first_reminder),

                        'second_reminder' => serialize($second_reminder),

                        'third_reminder' => serialize($third_reminder),

                    ),

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

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

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

                );

            endif;

            //  }


        }

    }
}

if (!function_exists('isSecure')) {
    function isSecure() {
        return
            (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
            || $_SERVER['SERVER_PORT'] == 443;
    }
}

if (!function_exists('ahachat_custom_product_link')) {
    function ahachat_custom_product_link()
    {

        if (empty($_REQUEST['multi-product-add'])) {

            return;

        }

        $product_ids = explode(',', $_REQUEST['multi-product-add']);

        $quantity = explode(',', $_REQUEST['quantity']);

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

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

            $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;

            }

        }

    }
}

if (!function_exists('ahachat_cartback_border_style')) {
    function ahachat_cartback_border_style()
    {
        $border_style = array(
            'none' => 'none',
            'hidden' => 'hidden',
            'dotted' => 'dotted',
            'dashed' => 'dashed',
            'solid' => 'solid',
            'double' => 'double',
            'groove' => 'groove',
            'ridge' => 'ridge',
            'inset' => 'inset',
            'outset' => 'outset',
            'dotted solid double dashed' => 'dotted solid double dashed',
            'dotted solid' => 'dotted solid',
            'initial' => 'initial'
        );

        return $border_style;

    }
}

if (!function_exists('Aha__Month_In_Year')) {
    function Aha__Month_In_Year($month)
    {

        switch ($month) {

            case 'Jan':

                echo "January";

                break;

            case 'Feb':

                echo "February";

                break;

            case 'Mar':

                echo "March";

                break;

            case 'Apr':

                echo "April";

                break;

            case 'May':

                echo "May";

                break;

            case 'Jun':

                echo "June";

                break;

            case 'Jul':

                echo "July";

                break;

            case 'Aug':

                echo "August";

                break;

            case 'Sep':

                echo "September";

                break;

            case 'Oct':

                echo "October";

                break;

            case 'Nov':

                echo "November";

                break;

            case 'Dec':

                echo "December";

                break;

            default:

                echo "Error";

                break;

        }

    }
}

add_action("woocommerce_checkout_after_customer_details", "ahachat_add_filed_check_when_user_click_btn_fb");

if (!function_exists('ahachat_add_filed_check_when_user_click_btn_fb')) {
    function ahachat_add_filed_check_when_user_click_btn_fb()
    {

        if (is_user_logged_in()) {

            $user_info = wp_get_current_user();

            $email_login = $user_info->user_email;

        } else {

            $email_login = "";

        }

        //

        ?>

        <input type="hidden" name="ahachat_click_order_" id="ahachat_click_order_" class=""
               value="<?php echo isset($_REQUEST['multi-product-add']) ? $_REQUEST['multi-product-add'] : ''; ?>">

        <input type="hidden" name="ahachat_reminder_" id="ahachat_reminder_" class=""
               value="<?php echo isset($_REQUEST['reminder']) ? $_REQUEST['reminder'] : ''; ?>">

        <input type="hidden" name="ahachat_user_checkout_" id="ahachat_user_checkout_" class=""
               value="<?php echo isset($_REQUEST['user']) ? $_REQUEST['user'] : ''; ?>">

        <!-- SAVE COOKIE TO CHECK WITH DATABASE-->

        <input type="hidden" name="ahachat_cookie_browser" id="ahachat_cookie_browser" value="">

        <!--UPDATE 19/10/2018: ADD USER_REF PAGE CHECKOUT -->

        <input type="hidden" name="ahachat_user_checked_checkout" id="ahachat_user_checked_checkout" value="">

        <!--UPDATE 23/10/2018: ADD USER_REF WHEN USER ADD TO CART -->

        <input type="hidden" name="user_addcart_" id="user_addcart_" value="">

        <!-- UPDATE EMAIL -->

        <input type="hidden" name="user_logged_" value="<?php echo $email_login; ?>">

        <input type="hidden" name="user_cookie_popup_" id="user_cookie_popup_" value="">

        <?php

    }
}

add_action('woocommerce_checkout_update_order_meta', 'ahachat_save_check_when_user_click_btn_fb');
if (!function_exists('ahachat_save_check_when_user_click_btn_fb')) {
    function ahachat_save_check_when_user_click_btn_fb($order_id)
    {

        if (!empty($_POST['ahachat_click_order_'])) {

            add_post_meta($order_id, '_ahachat_click_order_', $_POST['ahachat_click_order_']);

        }

        if (!empty($_POST['ahachat_reminder_'])) {

            add_post_meta($order_id, '_ahachat_reminder_', $_POST['ahachat_reminder_']);

        }

        if (!empty($_POST['ahachat_user_checkout_'])) {

            add_post_meta($order_id, '_ahachat_user_checkout_', $_POST['ahachat_user_checkout_']);

        }

        // SAVE COOKIE TO CHECK WITH DATABASE

        if (!empty($_POST['ahachat_cookie_browser'])) {

            add_post_meta($order_id, '_cookie_browser_', $_POST['ahachat_cookie_browser']);

        }

        //UPDATE 19/10/2018: ADD USER_REF PAGE CHECKOUT

        if (!empty($_POST['ahachat_user_checked_checkout'])) {

            add_post_meta($order_id, '_ahachat_click_cb_checkout', $_POST['ahachat_user_checked_checkout']);

        }

        //UPDATE 23/10/2018: ADD USER_REF WHEN USER ADD TO CART

        if (!empty($_POST['user_addcart_'])) {

            add_post_meta($order_id, '_user_addcart_', $_POST['user_addcart_']);

        }

        //UPDATE 25/10/2018: UPDATE EMAIL

        if (!empty($_POST['user_logged_'])) {

            add_post_meta($order_id, '_user_logged__', $_POST['user_logged_']);

        }

        if (!empty($_POST['user_cookie_popup_'])) {

            add_post_meta($order_id, '_user_cookie_popup_', $_POST['user_cookie_popup_']);

        }

    }
}

add_action('woocommerce_thankyou', 'ahachat_excute_when_order_success_with_click_order_btn_fb', 10, 1);
if (!function_exists('ahachat_excute_when_order_success_with_click_order_btn_fb')) {
    function ahachat_excute_when_order_success_with_click_order_btn_fb($order_id)
    {

        // excute

        if (!$order_id) return;

        global $wpdb;

        $cookie_name_order = "user_order_success";

        $cookie_value_order = "order";

        $table_user_ref = AHACHAT_USER_REF_TABLE;

        //

        $fb_api = new AHACHAT_WP_API();

        $page_id = get_option('ahachat_page_id');

        //=====UPDATE AUDIENCE,EMAIL

        $post_type_get_email = new AHA_POST_TYPE_USER_EMAIL;

        $post_type_user_add_cart = new AHA_POST_TYPE_USER_ADD_TO_CART();

        //

        $order = wc_get_order($order_id);

        $order_data = $order->get_data();

        //===ONLY ACTIVE USE THIS FEATURE

        $check_active = -1;

        if (get_option("license_cb_active")) {

            $license_cb_active = get_option("license_cb_active");

            $day_current = date('Y-m-d H:i:s', time());

            $supported_until = $license_cb_active["supported_until"];

            $check_active = strtotime($supported_until) - strtotime($day_current);

        }

        //

        //====COUPON EXCUTE====

        $flag_check_messenger_receipt = 0;

        if (get_option("cb_messenger_receipt")) {

            $messenger_receipt = get_option("cb_messenger_receipt");

            if (isset($messenger_receipt["on_off"]) && $check_active > 0) {

                //first message

                $recipient_name = (isset($order_data["shipping"]["first_name"]) && !empty($order_data["shipping"]["first_name"])) ? $order_data["shipping"]["first_name"] : $order_data["billing"]["first_name"];

                if (!empty($messenger_receipt["before_receipt"])) {

                    $before_message = $messenger_receipt["before_receipt"];

                    $before_message = str_replace("[firstName]", $recipient_name, $before_message);

                    $before_message = str_replace("[orderNumber]", "#" . $order_id, $before_message);

                } else {

                    $before_message = "Hi " . $recipient_name . ", thanks for shopping with us! If you have any questions, message us here.";

                }

                //product message

                $array_product = array();

                foreach ($order->get_items() as $item_key => $item_values):

                    $item_data = $item_values->get_data();

                    $image_url = str_replace('http://', 'https://', wp_get_attachment_image_src(get_post_thumbnail_id($item_data['product_id'], 'full', false))[0]);

                    $array_product[] = array(

                        "title" => $item_data['name'],

                        "subtitle" => !empty(_ahachat_substr(get_the_excerpt($item_data['product_id']), 50)) ? _ahachat_substr(get_the_excerpt($item_data['product_id']), 50) : $item_data['name'] . ' X ' . $item_data['quantity'],

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

                        "price" => $item_data['total'],

                        "currency" => $order_data["currency"],//"USD",

                        "image_url" => $image_url,

                    );

                endforeach;


                $order_number = "Order #" . $order_id;

                $currency_code = $order->get_currency();

                $currency = $order_data["currency"];//"USD";

                $payment_method = $order_data["payment_method_title"];

                $order_url = esc_url($order->get_view_order_url());


                $recipient_name = (isset($order_data["shipping"]["first_name"]) && isset($order_data["shipping"]["last_name"]) && !empty($order_data["shipping"]["first_name"]) && !empty($order_data["shipping"]["last_name"])) ? $order_data["shipping"]["first_name"] . " " . $order_data["shipping"]["last_name"] : $order_data["billing"]["first_name"] . " " . $order_data["billing"]["last_name"];


                $array_address_shipping = array(

                    "street_1" => (isset($order_data["shipping"]["address_1"]) && !empty($order_data["shipping"]["address_1"])) ? $order_data["shipping"]["address_1"] : $order_data["billing"]["address_1"],

                    "street_2" => (isset($order_data["shipping"]["address_2"]) && !empty($order_data["shipping"]["address_2"])) ? (!empty($order_data["shipping"]["address_2"]) ? $order_data["shipping"]["address_2"] : "") : (!empty($order_data["billing"]["address_2"]) ? $order_data["billing"]["address_2"] : ""),

                    "city" => (isset($order_data["shipping"]["city"]) && !empty($order_data["shipping"]["city"])) ? $order_data["shipping"]["city"] : $order_data["billing"]["city"],

                    "state" => (isset($order_data["shipping"]["state"]) && !empty($order_data["shipping"]["state"])) ? (!empty($order_data["shipping"]["state"]) ? $order_data["shipping"]["state"] : "State: none") : (!empty($order_data["billing"]["state"]) ? $order_data["billing"]["state"] : "State: none"),

                    "postal_code" => (isset($order_data["shipping"]["postcode"]) && !empty($order_data["shipping"]["postcode"])) ? (!empty($order_data["shipping"]["postcode"]) ? $order_data["shipping"]["postcode"] : "Postcode: none") : (!empty($order_data["billing"]["postcode"]) ? $order_data["billing"]["postcode"] : "Postcode: none"),

                    "country" => (isset($order_data["shipping"]["country"]) && !empty($order_data["shipping"]["country"])) ? (!empty($order_data["shipping"]["country"]) ? $order_data["shipping"]["country"] : "Country: none") : (!empty($order_data["billing"]["country"]) ? $order_data["billing"]["country"] : "Country: none"),

                );


                $array_sumary = array(

                    "subtotal" => $order->get_subtotal(),

                    "shipping_cost" => $order_data["shipping_total"],

                    "total_tax" => $order_data["total_tax"],

                    "total_cost" => $order_data["total"]

                );


                if (empty($order_data["coupon_lines"])) {

                    $array_coupon = array(

                        array(

                            "name" => "Customer Discount",

                            "amount" => 0

                        )

                    );

                } else {

                    $array_coupon = array(

                        array(

                            "name" => "Customer Discount With Code" . $order_data["coupon_lines"]["code"],

                            "amount" => !empty($messenger_receipt["amount"]) ? $messenger_receipt["amount"] : 10

                        )

                    );

                }


                $timestamp = time();

                //third message

                $allow_email = $order_data["billing"]["email"];

                $amount_coupon = !empty($messenger_receipt["amount"]) ? $messenger_receipt["amount"] : 10;

                $expiry_date = !empty($messenger_receipt["expiry_date"]) ? (int)$messenger_receipt["expiry_date"] : 14;

                if ($expiry_date > 0) {

                    $time_expiry_date = time() + $expiry_date * 24 * 60 * 60;

                } else {

                    $time_expiry_date = "";

                }

                $usage_limit = !empty($messenger_receipt["usage_limit"]) ? (int)$messenger_receipt["usage_limit"] : 10;

                $coupon_type = $messenger_receipt["coupon_type"];

                if ($coupon_type == "fixed_cart") {

                    $amount = "$" . $amount_coupon;

                } else if ($coupon_type == "percent_product") {

                    $amount = "$" . $amount_coupon . "/product";

                } else {

                    $amount = $amount_coupon . "%";

                }


                $coupon_code = !empty($messenger_receipt["coupon_code"]) ? $messenger_receipt["coupon_code"] . $order_id : "THANKYOU" . $order_id;

                //

                //

                $array_button = array();

                $array_button[] = array(

                    "type" => "web_url",

                    "url" => !empty($messenger_receipt["call_action_url"]) ? $messenger_receipt["call_action_url"] : home_url() . '/shop',

                    "title" => !empty($messenger_receipt["call_action"]) ? $messenger_receipt["call_action"] : "Shop Now"

                );

                //

                $sender_id = "";

                if (!empty($messenger_receipt["after_receipt"])) {

                    $after_message = $messenger_receipt["after_receipt"];

                    $after_message = str_replace("[amount_coupon]", $amount, $after_message);

                    if ($expiry_date > 0) {

                        $show_test_expiry_date = $expiry_date . " days";

                    } else {

                        $show_test_expiry_date = "days";

                    }

                    $after_message = str_replace("[expiry_date]", $show_test_expiry_date, $after_message);

                    $after_message = str_replace("[unique_coupon]", $coupon_code, $after_message);

                    $after_message = str_replace("[usage_limit]", $usage_limit, $after_message);

                } else {

                    $amount_t = !empty($amount) ? $amount : "10%";

                    $expiry_date_t = !empty($messenger_receipt["expiry_date"]) ? (int)$messenger_receipt["expiry_date"] : 14;

                    if ($expiry_date_t > 0) {

                        $show_test_expiry_date = $expiry_date_t . " days";

                    } else {

                        $show_test_expiry_date = "days";

                    }

                    $after_message = "Get " . $amount_t . " off your next purchase in the next " . $show_test_expiry_date . ": use THANKYOU" . $order_id . " at checkout.";

                }

                //

                $flag_check_messenger_receipt = 1;

            }

        }

        //

        if (!isset($_COOKIE[$cookie_name_order]) || isset($_COOKIE[$cookie_name_order])) {


            $table_analystic_fb = AHACHAT_ANALYTICS_FB_TABLE;

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

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

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

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

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

            //

            foreach ($order_data["meta_data"] as $key_reminder => $value_reminder) {

                if ($value_reminder->key == "_ahachat_user_checkout_") {

                    $user_ref_checkout = $value_reminder->value;

                    break;

                }

            }

            foreach ($order_data["meta_data"] as $key_reminder => $value_reminder) {

                if ($value_reminder->key == "_ahachat_reminder_") {

                    $reminder = $value_reminder->value;

                    break;

                }

            }


            if (isset($user_ref_checkout) && !empty($user_ref_checkout) && isset($reminder) && !empty($reminder)) {

                if (!isset($_COOKIE[$cookie_name_order])) {


                    setcookie($cookie_name_order, $cookie_value_order, time() + (86400 * 1), "/");


                    if (empty($list_analystic_fb)) {

                        $click_first = (isset($reminder) && $reminder == "first") ? 1 : 0;

                        $click_second = (isset($reminder) && $reminder == "second") ? 1 : 0;

                        $click_third = (isset($reminder) && $reminder == "third") ? 1 : 0;

                        $purchases_first = (isset($reminder) && $reminder == "first") ? 1 : 0;

                        $purchases_second = (isset($reminder) && $reminder == "second") ? 1 : 0;

                        $purchases_third = (isset($reminder) && $reminder == "third") ? 1 : 0;

                        $revenue_first = (isset($reminder) && $reminder == "first") ? $order_data['total'] : 0;

                        $revenue_second = (isset($reminder) && $reminder == "second") ? $order_data['total'] : 0;

                        $revenue_third = (isset($reminder) && $reminder == "third") ? $order_data['total'] : 0;

                        $first_reminder = array(

                            'click' => $click_first,

                            'purchases' => $purchases_first,

                            'revenue' => $revenue_first

                        );

                        $second_reminder = array(

                            'click' => $click_second,

                            'purchases' => $purchases_second,

                            'revenue' => $revenue_second

                        );

                        $third_reminder = array(

                            'click' => $click_third,

                            'purchases' => $purchases_third,

                            'revenue' => $revenue_third

                        );

                        $wpdb->insert($table_analystic_fb,

                            array(

                                'count_user_click' => 1,

                                'count_user_order' => 1,

                                'order_total_suc' => $order_data['total'],

                                'first_reminder' => serialize($first_reminder),

                                'second_reminder' => serialize($second_reminder),

                                'third_reminder' => serialize($third_reminder),

                                'arr_order' => serialize(array($order_id)),

                                'day' => $day,

                                'month' => $month,

                                'year' => $year,

                                'date_statis' => $date_current

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

                    } else {


                        // update :

                        $array_order = unserialize($list_analystic_fb->arr_order);

                        $first_reminder = unserialize($list_analystic_fb->first_reminder);

                        $second_reminder = unserialize($list_analystic_fb->second_reminder);

                        $third_reminder = unserialize($list_analystic_fb->third_reminder);

                        $click_first = (isset($first_reminder['click'])) ? (double)$first_reminder['click'] : 0;

                        $click_second = (isset($second_reminder['click'])) ? (double)$second_reminder['click'] : 0;

                        $click_third = (isset($third_reminder['click'])) ? (double)$third_reminder['click'] : 0;

                        $purchases_first = (isset($first_reminder['purchases']) && $reminder == "first") ? (double)$first_reminder['purchases'] + 1 : (double)$first_reminder['purchases'];

                        $purchases_second = (isset($second_reminder['purchases']) && $reminder == "second") ? (double)$second_reminder['purchases'] + 1 : (double)$second_reminder['purchases'];

                        $purchases_third = (isset($third_reminder['purchases']) && $reminder == "third") ? (double)$third_reminder['purchases'] + 1 : (double)$third_reminder['purchases'];

                        $revenue_first = (isset($first_reminder['revenue']) && $reminder == "first") ? (double)$first_reminder['revenue'] + $order_data['total'] : (double)$first_reminder['revenue'];

                        $revenue_second = (isset($second_reminder['revenue']) && $reminder == "second") ? (double)$second_reminder['revenue'] + $order_data['total'] : (double)$second_reminder['revenue'];

                        $revenue_third = (isset($third_reminder['revenue']) && $reminder == "third") ? (double)$third_reminder['revenue'] + $order_data['total'] : (double)$third_reminder['revenue'];

                        $first_reminder = array(

                            'click' => $click_first,

                            'purchases' => $purchases_first,

                            'revenue' => $revenue_first

                        );

                        $second_reminder = array(

                            'click' => $click_second,

                            'purchases' => $purchases_second,

                            'revenue' => $revenue_second

                        );

                        $third_reminder = array(

                            'click' => $click_third,

                            'purchases' => $purchases_third,

                            'revenue' => $revenue_third

                        );

                        if (empty($array_order)) {

                            $wpdb->update(

                                $table_analystic_fb,

                                array(

                                    'count_user_order' => $list_analystic_fb->count_user_order + 1,

                                    'order_total_suc' => $list_analystic_fb->order_total_suc + $order_data['total'],

                                    'first_reminder' => serialize($first_reminder),

                                    'second_reminder' => serialize($second_reminder),

                                    'third_reminder' => serialize($third_reminder),

                                    'arr_order' => serialize(array($order_id))

                                ),

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

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

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

                            );

                        } else {

                            if (!in_array($order_id, $array_order)) {

                                array_push($array_order, $order_id);

                                $wpdb->update(

                                    $table_analystic_fb,

                                    array(

                                        'count_user_order' => $list_analystic_fb->count_user_order + 1,

                                        'order_total_suc' => $list_analystic_fb->order_total_suc + $order_data['total'],

                                        'first_reminder' => serialize($first_reminder),

                                        'second_reminder' => serialize($second_reminder),

                                        'third_reminder' => serialize($third_reminder),

                                        'arr_order' => serialize($array_order)

                                    ),

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

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

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

                                );

                            }

                        }


                    }


                } else if (isset($_COOKIE[$cookie_name_order])) {


                    if (empty($list_analystic_fb)) {


                        $click_first = (isset($reminder) && $reminder == "first") ? 1 : 0;

                        $click_second = (isset($reminder) && $reminder == "second") ? 1 : 0;

                        $click_third = (isset($reminder) && $reminder == "third") ? 1 : 0;

                        $purchases_first = (isset($reminder) && $reminder == "first") ? 1 : 0;

                        $purchases_second = (isset($reminder) && $reminder == "second") ? 1 : 0;

                        $purchases_third = (isset($reminder) && $reminder == "third") ? 1 : 0;

                        $revenue_first = (isset($reminder) && $reminder == "first") ? $order_data['total'] : 0;

                        $revenue_second = (isset($reminder) && $reminder == "second") ? $order_data['total'] : 0;

                        $revenue_third = (isset($reminder) && $reminder == "third") ? $order_data['total'] : 0;

                        $first_reminder = array(

                            'click' => $click_first,

                            'purchases' => $purchases_first,

                            'revenue' => $revenue_first

                        );

                        $second_reminder = array(

                            'click' => $click_second,

                            'purchases' => $purchases_second,

                            'revenue' => $revenue_second

                        );

                        $third_reminder = array(

                            'click' => $click_third,

                            'purchases' => $purchases_third,

                            'revenue' => $revenue_third

                        );

                        $wpdb->insert($table_analystic_fb,

                            array(

                                'count_user_click' => 1,

                                'count_user_order' => 1,

                                'order_total_suc' => $order_data['total'],

                                'first_reminder' => serialize($first_reminder),

                                'second_reminder' => serialize($second_reminder),

                                'third_reminder' => serialize($third_reminder),

                                'arr_order' => serialize(array($order_id)),

                                'day' => $day,

                                'month' => $month,

                                'year' => $year,

                                'date_statis' => $date_current

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

                    } else {

                        // update :

                        $array_order = unserialize($list_analystic_fb->arr_order);

                        $first_reminder = unserialize($list_analystic_fb->first_reminder);

                        $second_reminder = unserialize($list_analystic_fb->second_reminder);

                        $third_reminder = unserialize($list_analystic_fb->third_reminder);

                        $click_first = (isset($first_reminder['click'])) ? (double)$first_reminder['click'] : 0;

                        $click_second = (isset($second_reminder['click'])) ? (double)$second_reminder['click'] : 0;

                        $click_third = (isset($third_reminder['click'])) ? (double)$third_reminder['click'] : 0;

                        $purchases_first = (isset($first_reminder['purchases']) && $reminder == "first") ? (double)$first_reminder['purchases'] + 1 : (double)$first_reminder['purchases'];

                        $purchases_second = (isset($second_reminder['purchases']) && $reminder == "second") ? (double)$second_reminder['purchases'] + 1 : (double)$second_reminder['purchases'];

                        $purchases_third = (isset($third_reminder['purchases']) && $reminder == "third") ? (double)$third_reminder['purchases'] + 1 : (double)$third_reminder['purchases'];

                        $revenue_first = (isset($first_reminder['revenue']) && $reminder == "first") ? (double)$first_reminder['revenue'] + $order_data['total'] : (double)$first_reminder['revenue'];

                        $revenue_second = (isset($second_reminder['revenue']) && $reminder == "second") ? (double)$second_reminder['revenue'] + $order_data['total'] : (double)$second_reminder['revenue'];

                        $revenue_third = (isset($third_reminder['revenue']) && $reminder == "third") ? (double)$third_reminder['revenue'] + $order_data['total'] : (double)$third_reminder['revenue'];

                        $first_reminder = array(

                            'click' => $click_first,

                            'purchases' => $purchases_first,

                            'revenue' => $revenue_first

                        );

                        $second_reminder = array(

                            'click' => $click_second,

                            'purchases' => $purchases_second,

                            'revenue' => $revenue_second

                        );

                        $third_reminder = array(

                            'click' => $click_third,

                            'purchases' => $purchases_third,

                            'revenue' => $revenue_third

                        );

                        if (empty($array_order)) {

                            $wpdb->update(

                                $table_analystic_fb,

                                array(

                                    'count_user_order' => $list_analystic_fb->count_user_order + 1,

                                    'order_total_suc' => $list_analystic_fb->order_total_suc,

                                    'first_reminder' => serialize($first_reminder),

                                    'second_reminder' => serialize($second_reminder),

                                    'third_reminder' => serialize($third_reminder),

                                    'arr_order' => array($order_id)

                                ),

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

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

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

                            );

                        } else {


                            if (!in_array($order_id, $array_order)) {

                                array_push($array_order, $order_id);

                                $wpdb->update(

                                    $table_analystic_fb,

                                    array(

                                        'count_user_order' => $list_analystic_fb->count_user_order + 1,

                                        'order_total_suc' => $list_analystic_fb->order_total_suc + $order_data['total'],

                                        'first_reminder' => serialize($first_reminder),

                                        'second_reminder' => serialize($second_reminder),

                                        'third_reminder' => serialize($third_reminder),

                                        'arr_order' => serialize($array_order)

                                    ),

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

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

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

                                );


                            }

                        }


                    }

                }

                // DELETE

                //===========SEND MESSEAGE

                if ($flag_check_messenger_receipt == 1) {

                    $page_access_token = $fb_api->AHA_Get_Access_Token_Page();

                    cb_send_message_order_info($page_access_token, $page_id, $before_message, $user_ref_checkout, $recipient_name, $order_number, $currency, $payment_method, $order_url, $array_address_shipping, $array_sumary, $array_coupon, $timestamp, $array_product, $order_id, $coupon_code, $amount, $coupon_type, $amount_coupon, $usage_limit, $allow_email, $time_expiry_date, $after_message, $sender_id, $array_button);

                }

                //

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

                if (!empty($row_user_ref)) {

                    $wpdb->delete($table_user_ref, array('user_ref' => $user_ref_checkout), array('%s'));

                }

            } else {


                foreach ($order_data["meta_data"] as $key => $value) {

                    if ($value->key == "_cookie_browser_") {

                        $session_user = $value->value;

                        break;

                    }

                }

                foreach ($order_data["meta_data"] as $key => $value) {

                    if ($value->key == "_user_logged__") {

                        $user_logged = $value->value;

                        break;

                    }

                }

                foreach ($order_data["meta_data"] as $key => $value) {

                    if ($value->key == "_user_cookie_popup_") {

                        $user_cookie_popup = $value->value;

                        break;

                    }

                }

                foreach ($order_data["meta_data"] as $key => $value) {

                    if ($value->key == "_ahachat_click_cb_checkout") {

                        $user_ref_checkout = $value->value;

                        break;

                    }

                }


                // get user_ref when user add to cart have checkbox

                foreach ($order_data["meta_data"] as $key => $value) {

                    if ($value->key == "_user_addcart_") {

                        $user_ref_addcart = $value->value;

                        break;

                    }

                }

                if (isset($session_user) && !empty($session_user)) {

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

                    if (!empty($row_user_ref)) {

                        $wpdb->delete($table_user_ref, array('session_key' => $session_user), array('%s'));

                    }

                    //

                    $agrs_add_cart = array(

                        'cookie_browser' => $session_user,

                        'page_id' => $page_id

                    );

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

                    if ($pid) {

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

                    }

                    //update email


                    if (isset($user_logged) && !empty($user_logged)) {

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

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

                            if (isset($user_cookie_popup) && !empty($user_cookie_popup)) {

                                $cookie_popup_br = $user_cookie_popup;

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

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

                                if ($postid) {

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

                                    update_post_meta($postid, 'ahachat_email_reminder', "no");

                                }

                            }


                        } else {

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

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

                            update_post_meta($postid, 'ahachat_email_reminder', "no");

                        }

                    } else { // not login

                        if (isset($user_cookie_popup) && !empty($user_cookie_popup)) {

                            $cookie_popup_br = $user_cookie_popup;

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

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

                            if ($postid) {

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

                                update_post_meta($postid, 'ahachat_email_reminder', "no");

                            }

                        }

                    }

                }


                if (isset($user_ref_checkout) && !empty($user_ref_checkout)) {


                    // send coupon

                    if ($flag_check_messenger_receipt == 1) {

                        $page_access_token = $fb_api->AHA_Get_Access_Token_Page();


                        cb_send_message_order_info($page_access_token, $page_id, $before_message, $user_ref_checkout, $recipient_name, $order_number, $currency, $payment_method, $order_url, $array_address_shipping, $array_sumary, $array_coupon, $timestamp, $array_product, $order_id, $coupon_code, $amount, $coupon_type, $amount_coupon, $usage_limit, $allow_email, $time_expiry_date, $after_message, $sender_id, $array_button);

                    }


                } else if (isset($user_ref_addcart) && !empty($user_ref_addcart)) {

                    $page_access_token = $fb_api->AHA_Get_Access_Token_Page();

                    cb_send_message_order_info($page_access_token, $page_id, $before_message, $user_ref_addcart, $recipient_name, $order_number, $currency, $payment_method, $order_url, $array_address_shipping, $array_sumary, $array_coupon, $timestamp, $array_product, $order_id, $coupon_code, $amount, $coupon_type, $amount_coupon, $usage_limit, $allow_email, $time_expiry_date, $after_message, $sender_id, $array_button);

                }

            }

        }


    }
}

if (!function_exists('cb_send_message_order_info')) {
    function cb_send_message_order_info($page_access_token, $page_id, $before_message, $user_ref_checkout, $recipient_name, $order_number, $currency, $payment_method, $order_url, $array_address_shipping, $array_sumary, $array_coupon, $timestamp, $array_product, $order_id, $coupon_code, $amount, $coupon_type, $amount_coupon, $usage_limit, $allow_email, $time_expiry_date, $after_message, $sender_id, $array_button)
    {


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

            $fb_api = new AHACHAT_WP_API();

            $page_token = $page_access_token["access_token"];

            $send_first = $fb_api->AHA_Send_message_text_user_ref($page_id, $page_token, $before_message, $user_ref_checkout);

            $send_second = $fb_api->AHA_Send_Order_Template_by_user_ref($page_id, $page_token, $user_ref_checkout, $recipient_name, $order_number, $currency, $payment_method, $order_url, $array_address_shipping, $array_sumary, $array_coupon, $timestamp, $array_product);


            //

            $flag_coupon = 0;

            if (!get_option('cb_list_orderid')) {

                update_option('cb_list_orderid', array($order_id));

                $flag_coupon = 1;

            } else {

                $list_orderid = get_option('cb_list_orderid');

                if (!in_array($order_id, $list_orderid)) {

                    array_push($list_orderid, $order_id);

                    $flag_coupon = 1;

                }

                update_option('cb_list_orderid', $list_orderid);

            }

            if ($flag_coupon == 1) {

                $coupon = array(

                    'post_title' => $coupon_code,

                    'post_content' => $amount . ' off coupon',

                    'post_excerpt' => $amount . ' off coupon',

                    'post_status' => 'publish',

                    //'post_author' => 1,

                    'post_type' => 'shop_coupon'

                );

                $new_coupon_id = wp_insert_post($coupon);

                update_post_meta($new_coupon_id, 'discount_type', $coupon_type);

                update_post_meta($new_coupon_id, 'coupon_amount', $amount_coupon);

                update_post_meta($new_coupon_id, 'individual_use', 'no');

                update_post_meta($new_coupon_id, 'product_ids', '');

                update_post_meta($new_coupon_id, 'exclude_product_ids', '');

                update_post_meta($new_coupon_id, 'usage_limit', $usage_limit);

                update_post_meta($new_coupon_id, 'customer_email', $allow_email);

                if (!empty($time_expiry_date)) {

                    update_post_meta($new_coupon_id, 'expiry_date', $time_expiry_date);

                }


                update_post_meta($new_coupon_id, 'apply_before_tax', 'yes');

                update_post_meta($new_coupon_id, 'free_shipping', 'no');

            }

            //

            $send_third = $fb_api->AHA_SEND_TEXT_BUTTON($page_id, $page_token, $after_message, $user_ref_checkout, $sender_id, $array_button);

        }


    }
}

if (!function_exists('_ahachat_substr')) {
    function _ahachat_substr($str, $length, $minword = 3)

    {

        $sub = '';

        $len = 0;

        foreach (explode(' ', $str) as $word) {

            $part = (($sub != '') ? ' ' : '') . $word;

            $sub .= $part;

            $len += strlen($part);

            if (strlen($word) > $minword && strlen($sub) >= $length) {

                break;

            }

        }

        return $sub . (($len < strlen($str)) ? '...' : '');

    }
}

if (!function_exists('cartback_show_table_list_user')) {
    function cartback_show_table_list_user($list_user)
    {

        ?>

        <style type="text/css">

            th#user_ref, th#sender_id, th#type {
                width: 15%
            }

        </style>

        <div class="wrap" style="margin-bottom: 50px;">


        </div>

        <div id='list-users' class="wrap list-slide">

            <form id="movies-filter" method="get">

                <input type="hidden" name="page" value="<?php echo $_REQUEST['page'] ?>"/>

                <?php

                $list_user->prepare_items();


                $list_user->display();

                ?>

            </form>

        </div>

        <?php

    }
}

if (!function_exists('cartback_show_table_list_user_audience')) {
    function cartback_show_table_list_user_audience($list_user)
    {

        ?>

        <style type="text/css">

            th#user_ref, th#sender_id, th#type {
                width: 15%
            }

        </style>

        <div class="wrap" style="margin-bottom: 50px;">


        </div>

        <div id='list-users' class="wrap list-slide">

            <form id="movies-filter" method="get">

                <input type="hidden" name="page" value="<?php echo $_REQUEST['page'] ?>"/>

                <input type="hidden" name="menu" value="send"/>

                <?php

                $list_user->prepare_items();

                $list_user->search_box(__('Search Subscribers', AHACHAT_WP), 'search_user_id');

                $list_user->display();

                ?>

            </form>

        </div>

        <?php

    }
}

if (!function_exists('ahachat_cartback_insert_show_messenger_checkbox')) {
    function ahachat_cartback_insert_show_messenger_checkbox($page_url, $user_ref)
    {
        $ahachat_app_id = get_option('ahachat_app_id');
        ?>

        <div class="ahachat_messenger_checkbox _14X7Pp8Px9j1Dgym9BVhk5 _3al24jDc_7bpmog69K5Q4Z _3XtmVWbgt6wWmymPR_xc5r _3ARoJwboeJ4Kxm1p_NNDSu _4UOJsfsxD-a1Kl-_h0eew _1o5_-XBfbQnxX0KJ-Dub9l">
            <button type="button" class="_14X7Pp8Px9j1Dgym9BVhk5 _3Mqz7u5-Me22KQVYtDF1t5" disabled=""
                    style="background-color: rgb(0, 132, 255) !important; color: rgba(0, 132, 255, 0.5) !important;">
                <div class="vHb-ynFjMBIIPShCGRneI">
                    <div style="color: rgb(255, 255, 255); display: inline-block;">
                        <style>input#undefined::-ms-clear {
                                display: none;
                            }</style>
                        <input id="ahachat_type_cb_send_me" type="text" value="Send me Coupon"
                               class="_29cC3dsRVx1tkpL6su198Y"
                               style="width: 200px; box-sizing: content-box;">
                        <div style="position: absolute; top: 0px; left: 0px; visibility: hidden; height: 0px; overflow: scroll; white-space: pre; font-size: 16px; font-family: Lato, &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif; font-weight: 700; font-style: normal; letter-spacing: normal; text-transform: none;">
                            Send me Coupon
                        </div>
                    </div>
                </div>
            </button>
            <div class="_284huAFDTpT-7nrtX3Y0tl _3akuPMQv9z8eFbgqdxDVvU _3dEG6gxnrooNv1al1pTbr0">
                <div class="_284huAFDTpT-7nrtX3Y0tl _1szswuGzrOfRCjj95aiEpT _1MKE7OpDJkgrjkGlMVAU0j _5G8On6NZ0O7k0bd9ziACm">
                    <!-- -->
                    <div class='fb-messenger-checkbox' origin="<?php echo $page_url; ?>"
                         page_id="<?php echo get_option('ahachat_page_id'); ?>"
                         messenger_app_id="<?php echo $ahachat_app_id; ?>" user_ref='<?php echo $user_ref; ?>'
                         prechecked='true' allow_login='true' size='large'></div>
                </div>
            </div>
        </div>

        <?php

    }
}

if (!function_exists('ahachat_cartback_insert_send_to_messenger')) {
    function ahachat_cartback_insert_send_to_messenger($page_url, $user_ref)
    {
        $ahachat_app_id = get_option('ahachat_app_id');
        ?>

        <div style='width:350px;'
             class='ahachat_send_messenger ahachat-cartback-widget__box ahachat-cartback-widget-box'>

            <div class='ahachat-cartback-widget-box__icon-container'>

                <div class='ahachat-cartback-widget-box__icon ahachat-cartback-widget-box__discount-icon'>

                    <svg class='ahachat-cartback-widget-box__discount-icon-bg' xmlns='http://www.w3.org/2000/svg'
                         xmlns:xlink='http://www.w3.org/1999/xlink' width='46px' height='46px'>

                        <path fill-rule='evenodd'
                              d='M23.000,-0.000 L27.203,5.040 L33.234,2.278 L34.779,8.597 L41.439,8.660 L40.020,15.007 L45.993,17.882 L41.890,23.000 L45.993,28.118 L40.020,30.993 L41.439,37.340 L34.779,37.403 L33.234,43.722 L27.203,40.960 L23.000,46.000 L18.797,40.960 L12.766,43.722 L11.221,37.403 L4.561,37.340 L5.980,30.993 L0.007,28.118 L4.110,23.000 L0.007,17.882 L5.980,15.007 L4.561,8.660 L11.221,8.597 L12.766,2.278 L18.797,5.040 L23.000,-0.000 Z'></path>

                    </svg>

                    <span>%</span>

                </div>


                <div class='ahachat-cartback-widget-box__icon ahachat-cartback-widget-box__loading-icon cartback-loading-icon cartback-loading-circle'></div>

            </div>

            <div class='ahachat-cartback-widget-box__content'>

                <div id='ahachat-cartback-widget'>

                    <!--Stay up to date with order notifications!-->

                    <div class="fb-send-to-messenger" origin="<?php echo $page_url; ?>"
                         page_id="<?php echo get_option('ahachat_page_id'); ?>"
                         messenger_app_id="<?php echo $ahachat_app_id; ?>" data-ref="wp_cart_<?php echo $user_ref; ?>"
                         color="blue"
                         size='xlarge'></div>

                </div>

            </div>

        </div>

        <?php

    }
}

if (!function_exists('ahachat_cartback_insert_send_custom_text_with_sendto')) {
    function ahachat_cartback_insert_send_custom_text_with_sendto()
    {

        ?>

        <div class="ahachat-cartback-widget ahachat_with_button_type_sendto">

            <b id="ahachat_send_custom_message_option">Send custom message:</b><br/><br/>


            <span class="send_custom_text_width_sendto">

                    <textarea placeholder="Please enter a text message" id="message_custom_send"
                              style="width: 50%"></textarea>

                </span>


        </div>

        <?php

    }
}

if (!function_exists('ahachat_cartback_insert_message_type_with_checkbox')) {
    function ahachat_cartback_insert_message_type_with_checkbox()
    {

        ?>

        <input type="hidden" id="ahachat_img_remove_list_product"
               value="<?php echo AHACHAT_WP_PLUGIN_PATH . 'assets/images/' . AHACHAT_PREFIX . 'remove.png'; ?>">

        <div class="ahachat-cartback-widget ahachat_with_button_type_checkbox">

            <b id="ahachat_message_type_option">Message Type:</b><br/>


            <input id="ahachat_message_type_custom_text" checked="checked" class="ahachat_message_type" type="radio"
                   name="message_type" value="custom_text"> Send Custom Text

            <input id="ahachat_message_type_product_reminder" class="ahachat_message_type" type="radio"
                   name="message_type"
                   value="product_reminder"> Send Product Reminder<br><br/>

            <span class="send_custom_text">

                    <textarea placeholder="Please enter a text message" id="message_shortcode"
                              style="width: 50%"></textarea>

                </span>

            <ul class="ahachat_root_popup">

                <li class="ahachat_popup_dashboard_selected"></li>

                <li class="ahachat_popup_dashboard_live_fields">

                    <input style="background-color: #F3F5F8;border: none;-webkit-box-shadow: none;box-shadow: none;"
                           type="text" class="ahachat_popup_dashboard_search_posts"
                           placeholder="start typing product page name..." data-post_type="only_pages">

                    <span class="spinner"></span>

                    <input class="ahachat_product_page_list_results" type="hidden"
                           id="ahachat_popup_dashboard[pages_include]"
                           name="ahachat_popup_dashboard[pages_include]" value="">

                </li>


                <li class="ahachat_popup_dashboard_live_search_res">

                    <ul class="ahachat_popup_dashboard_search_results"></ul>

                </li>

            </ul>

        </div>

        <?php

    }
}

if (!function_exists('ahachat_cartback_insert_showphone')) {
    function ahachat_cartback_insert_showphone($fanpage_name)
    {

        ?>

        <style type="text/css">img.emojioneemoji {
                width: 20px;
            }</style>

        <div class="col-xs-12 col-md-6">

            <div class="text-center ahachat_phone_container col-auto">
                <div>
                    <div class="ahachat_phone_content_1 ahachat_phone_content_2 ahachat_phone_content_3">
                        <div class="ahachat_phone_content_div_1"></div>
                        <div class="ahachat_phone_content_div_2"></div>
                        <div class="ahachat_phone_content_div_3">
                            <div class="ahachat_phone_content_div_4_1 ahachat_phone_content_div_4_2">
                                <div class="ahachat_phone_content_div_5">
                                    <div><span class="ahachat_phone_content_span_1"><i
                                                    class="ahachat_phone_content_i_1 ahachat_phone_content_i_2"></i><span
                                                    class="ahachat_phone_content_span_2">Back</span></span></div>
                                    <div class="ahachat_phone_content_div_6">
                                        <div class="ahachat_phone_content_div_7">
                                            <div class="ahachat_phone_content_div_8"><span
                                                        class="ahachat_phone_content_div_9"><?php echo $fanpage_name; ?></span><i
                                                        class="i-keyboard_arrow_right ahachat_phone_content_i_3"></i>
                                            </div>
                                        </div>
                                        <div class="ahachat_phone_content_div_10_1 ahachat_phone_content_div_10_2">
                                            <span>Typically replies instantly</span>
                                        </div>
                                    </div>
                                    <div><span class="ahachat_phone_content_span_1"><span>Manage</span></span></div>
                                </div>
                            </div>
                            <div class="ahachat_phone_content_div_11">
                                <div class="ahachat_phone_content_div_12">
                                    <div class="_2Bgr6QI5K3O4b4IRhU71-m"
                                         style="position: relative; overflow: hidden; width: 100%; height: 100%;">
                                        <div style="position: absolute; top: 0px; left: 0px; right: 0px; bottom: 0px; overflow: scroll; margin-right: -17px; margin-bottom: -17px;">
                                            <div class="p-a-sm">
                                                <div>
                                                    <div><?php ahachat_show_txt_preview_custom_text_sendto_checkbox(); ?><?php ahachat_show_txt_preview_custom_text_list_product(); ?></div>
                                                </div>
                                            </div>
                                        </div>
                                        <div style="position: absolute; height: 6px; transition: opacity 200ms; opacity: 0; right: 2px; bottom: 2px; left: 2px; border-radius: 3px;">
                                            <div style="position: relative; display: block; height: 100%; cursor: pointer; border-radius: inherit; background-color: rgba(0, 0, 0, 0.2); width: 0px;"></div>
                                        </div>
                                        <div style="position: absolute; width: 6px; transition: opacity 200ms; opacity: 0; right: 2px; bottom: 2px; top: 2px; border-radius: 3px;">
                                            <div style="position: relative; display: block; width: 100%; cursor: pointer; border-radius: inherit; background-color: rgba(0, 0, 0, 0.2); height: 0px;"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="ahachat_phone_content_div_19"></div>
                    </div>
                </div>
            </div>

        </div>


        <?php

    }
}

if (!function_exists('cartback_show_phone_messenger_receipt')) {
    function cartback_show_phone_messenger_receipt($fanpage_name)
    {

        $messenger_receipt = get_option("cb_messenger_receipt");

        if (!empty($messenger_receipt) && !empty($messenger_receipt["after_receipt"])) {

            $after_message = $messenger_receipt["after_receipt"];

            $amount_coupon = $messenger_receipt["amount"];

            $coupon_code = $messenger_receipt["coupon_code"];

            $coupon_type = $messenger_receipt["coupon_type"];

            if ($coupon_type == "fixed_cart") {

                $amount_coupon = "$" . $amount_coupon;

            } else if ($coupon_type == "percent_product") {

                $amount_coupon = "$" . $amount_coupon . "/product";

            } else {

                $amount_coupon = $amount_coupon . "%";

            }

            $usage_limit = !empty($messenger_receipt["usage_limit"]) ? (int)$messenger_receipt["usage_limit"] : 10;


            $expiry_date = $messenger_receipt["expiry_date"];

            $after_message = str_replace("[amount_coupon]", $amount_coupon, $after_message);

            $after_message = str_replace("[expiry_date]", $expiry_date . " days", $after_message);

            $after_message = str_replace("[unique_coupon]", $coupon_code . "234", $after_message);

            $after_message = str_replace("[usage_limit]", $usage_limit, $after_message);

        } else {

            $after_message = 'Get 10% off your next purchase in the next 14 days: use THANKYOU234 at checkout.';

        }

        ?>

        <style type="text/css">img.emojioneemoji {
                width: 20px;
            }</style>

        <div class="col-xs-12 col-md-6">

            <div class="text-center ahachat_phone_container col-auto">
                <div>
                    <div class="ahachat_phone_content_1 ahachat_phone_content_2 ahachat_phone_content_3">
                        <div class="ahachat_phone_content_div_1"></div>
                        <div class="ahachat_phone_content_div_2"></div>
                        <div class="ahachat_phone_content_div_3">
                            <div class="ahachat_phone_content_div_4_1 ahachat_phone_content_div_4_2">
                                <div class="ahachat_phone_content_div_5">
                                    <div><span class="ahachat_phone_content_span_1"><i
                                                    class="ahachat_phone_content_i_1 ahachat_phone_content_i_2"></i><span
                                                    class="ahachat_phone_content_span_2">Back</span></span></div>
                                    <div class="ahachat_phone_content_div_6">
                                        <div class="ahachat_phone_content_div_7">
                                            <div class="ahachat_phone_content_div_8"><span
                                                        class="ahachat_phone_content_div_9"><?php echo $fanpage_name; ?></span><i
                                                        class="i-keyboard_arrow_right ahachat_phone_content_i_3"></i>
                                            </div>
                                        </div>
                                        <div class="ahachat_phone_content_div_10_1 ahachat_phone_content_div_10_2">
                                            <span>Typically replies instantly</span>
                                        </div>
                                    </div>
                                    <div><span class="ahachat_phone_content_span_1"><span>Manage</span></span></div>
                                </div>
                            </div>
                            <div class="ahachat_phone_content_div_11">
                                <div class="ahachat_phone_content_div_12">
                                    <div class="_2Bgr6QI5K3O4b4IRhU71-m"
                                         style="position: relative; overflow: hidden; width: 100%; height: 100%;">
                                        <div style="position: absolute; top: 0px; left: 0px; right: 0px; bottom: 0px; overflow: scroll; margin-right: -17px; margin-bottom: -17px;">
                                            <div class="p-a-sm">
                                                <div>
                                                    <div><?php ahachat_show_txt_preview_messenger_receipt(); ?><img
                                                                src="<?php echo AHACHAT_WP_PLUGIN_PATH . 'assets/images/' . AHACHAT_PREFIX . 'preview_payment.png'; ?>"
                                                                alt="" class="fbmessage-preview__image">
                                                        <div class="fb-text fb-text--buttons">
                                                            <div>
                                                                <div class="fb-text__text"><?php echo $after_message; ?></div>
                                                                <div>
                                                                    <div class="fb-text__buttons">
                                                                        <div class="fb-button"><?php if (!empty($messenger_receipt) && !empty($messenger_receipt["call_action"])) echo $messenger_receipt["call_action"]; else echo 'Shop Now'; ?></div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div><!----></div>
                                                </div>
                                            </div>
                                        </div>
                                        <div style="position: absolute; height: 6px; transition: opacity 200ms; opacity: 0; right: 2px; bottom: 2px; left: 2px; border-radius: 3px;">
                                            <div style="position: relative; display: block; height: 100%; cursor: pointer; border-radius: inherit; background-color: rgba(0, 0, 0, 0.2); width: 0px;"></div>
                                        </div>
                                        <div style="position: absolute; width: 6px; transition: opacity 200ms; opacity: 0; right: 2px; bottom: 2px; top: 2px; border-radius: 3px;">
                                            <div style="position: relative; display: block; width: 100%; cursor: pointer; border-radius: inherit; background-color: rgba(0, 0, 0, 0.2); height: 0px;"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="ahachat_phone_content_div_19"></div>
                    </div>
                </div>
            </div>

        </div>


        <?php


    }
}

if (!function_exists('ahachat_show_txt_preview_custom_text_sendto_checkbox')) {
    function ahachat_show_txt_preview_custom_text_sendto_checkbox()
    {

        ?>

        <div class="ahachat_phone_content_div_13 ahachat_show_custom_text_not_list_product">
            <div class="clearfix">
                <div class="ahachat_phone_content_div_14_1 ahachat_phone_content_div_14_2">
                    <div class="_1hbKwGBfQZcGesLiE9VSN8 clearfix _2hCUWe1ICZtOnr4162RbNv qkGQ6r7HU9GM1IGycvLCk"><span
                                style="" id="tooltip_show_empty" tooltip="Please enter a text." flow="right"><div
                                    class="ahachat_phone_content_div_15_1 ahachat_phone_content_div_15_2 ahachat_text_preiew"><div
                                        class="ahachat_phone_content_div_16"><div class="ahachat_phone_content_div_17"
                                                                                  style="outline: none; white-space: pre-wrap; word-wrap: break-word;"><p><span><span><span>&#8203;<span
                                                                id="txt_preview"></span></span></span></span></p></div></div></div><div
                                    class="ahachat_phone_content_div_15_1 ahachat_phone_content_div_15_2 ahachat_text_preiew_width_cb"><div
                                        class="ahachat_phone_content_div_16"><div class="ahachat_phone_content_div_17"
                                                                                  style="outline: none; white-space: pre-wrap; word-wrap: break-word;"><p><span><span><span>&#8203;<span
                                                                id="txt_preview_width_cb"></span></span></span></span></p></div></div></div></span>
                    </div>
                </div>
                <div class="ahachat_phone_content_div_17_1 ahachat_phone_content_div_17_2 ahachat_phone_content_div_17_3"
                     style="width: 32px; height: 32px;"><img
                            src="https://i.imgur.com/1Dfpchn.png"></div>
            </div>
            <div>
                <div class="ahachat_phone_content_div_14_1 ahachat_phone_content_div_14_2">
                    <div class="ahachat_phone_content_div_18"></div>
                </div>
            </div>
        </div>

        <?php

    }
}

if (!function_exists('ahachat_show_txt_preview_custom_text_list_product')) {
    function ahachat_show_txt_preview_custom_text_list_product()
    {

        $ahachat_first_reminder = get_option('ahachat_first_reminder');

        $custom_text = isset($ahachat_first_reminder['something']) ? $ahachat_first_reminder['something'] : "You forgot your shopping cart";

        $args = array('posts_per_page' => 1, 'post_type' => 'product', 'orderby' => 'date', 'order' => 'DESC', 'post_status' => 'publish');

        $product_lasted = new WP_Query($args);

        foreach ($product_lasted->posts as $key => $product) {

            $_product = wc_get_product($product->ID);

            $product_img = get_the_post_thumbnail_url($product->ID, "medium");

            $product_title = get_the_title($product->ID);

            $product_link = get_the_permalink($product->ID);

            $product_price = $_product->get_price_html();

        }

        ?>

        <style type="text/css">

            .add_box_reminder {

                background-color: #fff;

                padding-top: 0;

                border-radius: 16px;

                vertical-align: bottom;

                box-shadow: none;

                border: 1px solid #e0e6ed;
            }

            .add_box_reminder div.info {

                padding: 5px;

            }

            .add_box_reminder div.info span.title {

                font-weight: bold;
                font-size: 12px;

            }

            span.body.ahachat_ad_price {
                font-size: 12px;
            }


            .add_box_reminder div.actions {

                color: #0084ff;

                text-align: center;

                padding: 8px;

                border-top: 1px solid #e0e6ed;

            }

        </style>

        <div class="ahachat_show_custom_text_list_product ahachat_phone_content_div_13">
            <div class="clearfix">
                <div class="ahachat_phone_content_div_14_1 ahachat_phone_content_div_14_2">
                    <div class="_1hbKwGBfQZcGesLiE9VSN8 clearfix _2hCUWe1ICZtOnr4162RbNv qkGQ6r7HU9GM1IGycvLCk">
                        <div class="ahachat_phone_content_div_15_1 ahachat_phone_content_div_15_2 ahachat_text_preiew_list_product">
                            <div class="ahachat_phone_content_div_16">
                                <div class="ahachat_phone_content_div_17"
                                     style="outline: none; white-space: pre-wrap; word-wrap: break-word;"><p>
                                    <span><span><span>&#8203;<span
                                                        id="txt_preview_list_product"><?php echo $custom_text; ?></span></span></span></span>
                                    </p></div>
                            </div>
                        </div><!---->
                        <div class="add_box_reminder"><img style="width: 198px" src="<?php echo $product_img; ?>">
                            <div class="info"><span class="title"><?php echo $product_title; ?></span><br/><span
                                        class="body ahachat_ad_price"><?php echo $product_price; ?> - <?php echo $product_title; ?></span><br/><span
                                        class="body subdued"><a class="ahachat_product_link" target="_blank"
                                                                href="<?php echo $product_link; ?>"><?php echo $_SERVER['HTTP_HOST']; ?></a></span>
                            </div>
                            <div class="actions"><?php if (isset($ahachat_first_reminder['checkout'])) echo $ahachat_first_reminder['checkout']; else echo 'Checkout Now'; ?></div>
                        </div><!----></div>
                </div>
                <div class="ahachat_phone_content_div_17_1 ahachat_phone_content_div_17_2 ahachat_phone_content_div_17_3"
                     style="width: 32px; height: 32px;"><img
                            src="https://i.imgur.com/1Dfpchn.png"></div>
            </div>
            <div>
                <div class="ahachat_phone_content_div_14_1 ahachat_phone_content_div_14_2">
                    <div class="ahachat_phone_content_div_18"></div>
                </div>
            </div>
        </div>

        <?php

    }
}

if (!function_exists('ahachat_show_txt_preview_messenger_receipt')) {
    function ahachat_show_txt_preview_messenger_receipt()
    {

        $messenger_receipt = get_option("cb_messenger_receipt");

        if (!empty($messenger_receipt)) {

            if (!empty($messenger_receipt["before_receipt"])) {

                $show_before_receipt = $messenger_receipt["before_receipt"];

                $show_before_receipt = str_replace("[firstName]", "John", $show_before_receipt);

                $show_before_receipt = str_replace("[orderNumber]", "#1234", $show_before_receipt);

            } else {

                $show_before_receipt = "Hi John, thanks for shopping with us! If you have any questions, message us here.";

            }

        } else {

            $show_before_receipt = "Hi John, thanks for shopping with us! If you have any questions, message us here.";

        }

        ?>

        <div class="ahachat_phone_content_div_13 ahachat_show_custom_text_not_list_product">
            <div class="clearfix">
                <div class="ahachat_phone_content_div_14_1 ahachat_phone_content_div_14_2">
                    <div class="_1hbKwGBfQZcGesLiE9VSN8 clearfix _2hCUWe1ICZtOnr4162RbNv qkGQ6r7HU9GM1IGycvLCk">
                        <div class="ahachat_phone_content_div_15_1 ahachat_phone_content_div_15_2 ahachat_text_preiew_width_cb"><?php echo $show_before_receipt; ?>
                            <div class="ahachat_phone_content_div_16">
                                <div class="ahachat_phone_content_div_17"
                                     style="outline: none; white-space: pre-wrap; word-wrap: break-word;"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div>
                <div class="ahachat_phone_content_div_14_1 ahachat_phone_content_div_14_2">
                    <div class="ahachat_phone_content_div_18"></div>
                </div>
            </div>
        </div>

        <?php

    }
}