<?php

if (!class_exists('AHACHAT_WP_RULE')): /****/
    class AHACHAT_WP_RULE
    {

        function __construct()
        {

            add_action('init', array(
                $this,
                'custom_rewrite_rule'
            ), 10, 0);

            add_filter('query_vars', array(
                $this,
                'callback_query_vars'
            ));

            add_action('parse_request', array(
                $this,
                'callback_request'
            ));
        }

        public function custom_rewrite_rule()
        {

            add_rewrite_rule('^facebook/callback', 'index.php?callback_abd_cart=$matches[1]', 'top');

        }

        function callback_query_vars($query_vars)
        {

            $query_vars[] = 'callback_abd_cart';

            return $query_vars;

        }

        function callback_request($data)
        {
            $fb_api = new AHACHAT_WP_API();

            $post_type_user_add = new AHA_POST_TYPE_USER_ADD_TO_CART();


            // USE WHEN CLICK SEND MESSENGER

            $sender_id = $data->entry[0]->messaging[0]->sender->id;

            $optin_ref = $data->entry[0]->messaging[0]->optin->ref;

            $page_id = $data->entry[0]->id;

            if (isset($sender_id) && isset($optin_ref)) {

                $fanpage_id = $data->entry[0]->id;

                $post_type_user_coupon = new AHA_POST_TYPE_USER_ADD_TO_CART();

                $agrs_coupon = array(

                    'sender_id' => $sender_id,

                    'page_id' => $fanpage_id

                );

                $arr_product_coupon = explode("_", $optin_ref);

                $product_coupon = $arr_product_coupon[3];

                //wp_mail('phptestfree@gmail.com','sdsd',json_encode($product_coupon));

                $page_access_token = $fb_api->AHA_Get_Access_Token_Page();

                if (isset($page_access_token["access_token"])) {
                    $page_token = $page_access_token["access_token"];

                    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());

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

                    //wp_mail('phptestfree@gmail.com','sdsd',json_encode($product_coupon));


                    if ($product_coupon == "shortcode") {

                        $id_shortcode = (int) $arr_product_coupon[4];

                        $table_shortcode = AHACHAT_SHORTCODES_TABLE;

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

                        $content_message = (!empty($shortcode_selected->message)) ? $shortcode_selected->message : "Congratulations! You’ve successfully got the coupon! Please check your inbox!";

                        $product_quantity[] = array(

                            'product_id' => -1,

                            'quantity' => -1

                        );

                        $ahachat_type = "Shortcode";

                        if (empty($list_statistical)) {

                            $list_user_shortcode = array(
                                $sender_id
                            );

                            $arr_list_user_shortcode = 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_shortcode,

                                '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(
                                    $sender_id
                                );

                            } else {

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

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

                                    array_push($array_list_user, $sender_id);

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

                        }

                    } else {

                        $content_message = (get_option('ahachat_text_send')) ? get_option('ahachat_text_send') : "You got the coupon successfully!";

                        $product_quantity[] = array(

                            'product_id' => 0,

                            'quantity' => 0

                        );

                        $ahachat_type = "Coupon";


                        if (empty($list_statistical)) {

                            $list_user_coupon = array(
                                $sender_id
                            );

                            $arr_list_user_coupon = serialize($list_user_coupon);

                            $wpdb->insert($ahachat_table_statistical, array(

                                'send_user' => 1,

                                'coupon_user' => 1,

                                'coupon_sent' => 1,

                                'list_coupon_user' => $arr_list_user_coupon,

                                'day' => $day,

                                'month' => $month,

                                'year' => $year,

                                'date_statis' => $ahachat_date_statistical

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

                        } else {

                            $coupon_user = $list_statistical->coupon_user;

                            $coupon_sent = $list_statistical->coupon_sent + 1;

                            $user_sent = $list_statistical->send_user + 1;

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

                                $array_list_user_coupon = array(
                                    $sender_id
                                );

                                $coupon_user = $coupon_user + 1;

                            } else {

                                $array_list_user_coupon = unserialize($list_statistical->list_coupon_user);

                                if (!in_array($sender_id, $array_list_user_coupon)) {

                                    array_push($array_list_user_coupon, $sender_id);

                                    $coupon_user = $coupon_user + 1;

                                }

                            }

                            $list_user_update = serialize($array_list_user_coupon);

                            $wpdb->update($ahachat_table_statistical, array(

                                'send_user' => $user_sent,

                                'coupon_user' => $coupon_user,

                                'coupon_sent' => $coupon_sent,

                                'list_coupon_user' => $list_user_update

                            ), array(
                                'day' => $day,
                                'month' => $month,
                                'year' => $year
                            ), array(
                                '%d',
                                '%d',
                                '%d',
                                '%s'
                            ), array(
                                '%d',
                                '%d',
                                '%d'
                            ));

                        }

                    }

                    $fb_api->AHA_Send_message_user_add_cart($fanpage_id, $page_token, $content_message, $sender_id);

                }

                /**/

                if (!$post_type_user_coupon->Check_Sender_ID_User_Exit($agrs_coupon)) {

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

                        $page_token = $page_access_token["access_token"];

                        $array_info = $fb_api->AHA_Get_Info_User_With_Recepit_ID($page_token, $sender_id);


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

                            $profile_pic = $array_info["profile_pic"]; // avatar

                            $arr_profile = explode('_', $profile_pic);

                            $avatar = $arr_profile[1];

                            $first_name = $array_info["first_name"];

                            $last_name = $array_info["last_name"];

                            $gender = $array_info["gender"];

                            $language = $array_info["locale"];

                            $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' => $profile_pic,

                                'ahachat_id_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' => '-',

                                'ahachat_user_ref' => '-',

                                'ahachat_page_id' => $fanpage_id,

                                'ahachat_product_user' => serialize($product_quantity),

                                'ahachat_sender_id' => $sender_id,

                                'ahachat_type' => $ahachat_type


                            );

                            $User_Coupon = $post_type_user_coupon->Insert($arr);

                            update_post_meta($User_Coupon, 'ahachat_check_delete_post', 'yes');

                        } else {

                            $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' => '-',

                                'ahachat_id_user' => '-',

                                'ahachat_first_name_user' => '-',

                                'ahachat_last_name_user' => '-',

                                'ahachat_gender_user' => '-',

                                'ahachat_locale_user' => '-',

                                'ahachat_recipient_id_user' => '-',

                                'ahachat_user_ref' => '-',

                                'ahachat_page_id' => $fanpage_id,

                                'ahachat_product_user' => serialize($product_quantity),

                                'ahachat_sender_id' => $sender_id,

                                'ahachat_type' => $ahachat_type

                            );

                            $User_Coupon = $post_type_user_coupon->Insert($arr);

                            update_post_meta($User_Coupon, 'ahachat_check_delete_post', 'yes');
                        }

                    }

                } else {

                    $user_coupon_id = $post_type_user_coupon->Check_Sender_ID_Post($agrs_coupon);

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

                    $product_quantity = array();

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

                        $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(0, $array_product_flag)) {

                            $product_quantity[] = array(

                                'product_id' => 0,

                                'quantity' => 0

                            );

                        }


                    } else {

                        $product_quantity[] = array(

                            'product_id' => 0,

                            'quantity' => 0

                        );

                    }


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

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

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

                        array_push($array_type, $ahachat_type);

                    }

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

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

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

                }


            }

            // USE WHEN CHECKBOX PLUGIN

            //wp_mail('phptestfree@gmail.com','sfsdf',json_encode($data));

            $user_comment = $data->entry[0]->messaging[0]->message->mid;

            if ($user_comment) {


                $page_access_token = $fb_api->AHA_Get_Access_Token_Page();

                /**/

                $source_reply = $data->entry[0]->messaging[0]->prior_message->source;

                $user_ref_reply = $data->entry[0]->messaging[0]->prior_message->identifier;

                /**/

                // GET INFO


                if (isset($source_reply) && isset($user_ref_reply) && $source_reply == "checkbox_plugin") {

                    $agrs_user_ref = array(

                        'user_ref' => $user_ref_reply,

                        'page_id' => $page_id

                    );


                    $pid = $post_type_user_add->Aha_Post_User_Ref_ID($agrs_user_ref);

                    if ($pid) {

                        if (get_post_meta($pid, 'ahachat_avatar_user', true) == "-") {

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

                                $page_token = $page_access_token["access_token"];

                                $array_info = $fb_api->AHA_Get_Info_User_With_Recepit_ID($page_token, $sender_id);

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

                                    $profile_pic = $array_info["profile_pic"]; // avatar

                                    $arr_profile = explode('_', $profile_pic);

                                    $href_avatar_user = $arr_profile[1];

                                    $first_name_user = $array_info["first_name"];

                                    $last_name_user = $array_info["last_name"];

                                    $gender_user = $array_info["gender"];

                                    $locale_user = $array_info["locale"];


                                    update_post_meta($pid, 'ahachat_id_user', $href_avatar_user);

                                    update_post_meta($pid, 'ahachat_avatar_user', $profile_pic);

                                    update_post_meta($pid, 'ahachat_first_name_user', $first_name_user);

                                    update_post_meta($pid, 'ahachat_last_name_user', $last_name_user);

                                    update_post_meta($pid, 'ahachat_gender_user', $gender_user);

                                    update_post_meta($pid, 'ahachat_locale_user', $locale_user);

                                    update_post_meta($pid, 'ahachat_sender_id', $sender_id);

                                    //

                                    $type_reply = "Reply";

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

                                    $array_type_cart = explode(",", $array_type_add_cart);

                                    if (!in_array($type_reply, $array_type_cart)) {

                                        array_push($array_type_cart, $type_reply);

                                    }

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

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

                                    //

                                }

                            }

                        }

                    }

                }


            }

            // EXCUTE WHEN TABLE HAVE 2 ROW REPEAT

            $agrs_sender_id = array(

                'sender_id' => $sender_id,

                'page_id' => $page_id

            );

            $count_row_found = $post_type_user_add->Count_Found_Post_Sender_ID($agrs_sender_id);


            if (count($count_row_found) > 1) {

                $list_post_id_found = array();

                foreach ($count_row_found as $key_found => $value_found) {

                    array_push($list_post_id_found, $value_found->ID);

                }

                $products = array();

                $list_type = array();

                //

                $postid_update = $list_post_id_found[0];

                foreach ($list_post_id_found as $key1 => $postid) {

                    $array_product_add_cart = unserialize(get_post_meta($postid, 'ahachat_product_user', true));

                    $type = get_post_meta($postid, 'ahachat_type', true);

                    $type = explode(',', $type);

                    foreach ($type as $key3 => $value3) {

                        array_push($list_type, $value3);

                    }

                    foreach ($array_product_add_cart as $key_list => $list) {

                        if (!empty($products)) {

                            $flag = 0;

                            foreach ($products as $key_pr => $value_pr) {

                                if ($value_pr["product_id"] == $list["product_id"]) {

                                    if ($value_pr["product_id"] == -1) {

                                        $products[$key_pr]["quantity"] = -1;

                                        $flag = 1;

                                        break;

                                    } else {

                                        $products[$key_pr]["quantity"] = $value_pr["quantity"] + $list["quantity"];

                                        $flag = 1;

                                        break;

                                    }

                                }

                            }

                            if ($flag == 0) {

                                $products[] = array(

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

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

                                );

                            }

                        } else {

                            $products[] = array(

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

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

                            );

                        }

                    }

                    // delete

                    if ($key1 != 0) {

                        wp_delete_post($postid);

                    }

                }

                //update

                if (!empty($products) && !empty($list_type)) {

                    update_post_meta($postid_update, 'ahachat_product_user', serialize($products));

                    $ahachat_type_update = implode(',', array_unique($list_type));

                    update_post_meta($postid_update, 'ahachat_type', $ahachat_type_update);

                }

                //update

            }

            if (count($count_row_found) == 1) {

                foreach ($count_row_found as $key_found => $value_found) {

                    $postid_update = $value_found->ID;

                }

                $type = get_post_meta($postid_update, 'ahachat_type', true);

                $type = explode(',', $type);

                if (!in_array("Reply", $type)) {

                    array_push($type, "Reply");

                }

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

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

            }

        }

        static function activate()
        {

            global $wp_rewrite;

            flush_rewrite_rules();

            $wp_rewrite->flush_rules(true);

        }

    }
endif;

new AHACHAT_WP_RULE();

register_deactivation_hook(__FILE__, 'flush_rewrite_rules');

register_activation_hook(__FILE__, 'AHACHAT_WP_RULE::activate');