<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit ; // Exit if accessed directly.
}
if ( ! class_exists( 'FPRewardSystem_Free_Product' ) ) {

    class FPRewardSystem_Free_Product {

        public static function init() {

            add_action( 'wp_head' , array( __CLASS__ , 'fp_main_function_add_to_cart' ) ) ;

            add_action( 'woocommerce_checkout_update_order_meta' , array( __CLASS__ , 'save_data_to_order' ) ) ;

            add_filter( 'woocommerce_order_item_name' , array( __CLASS__ , 'show_item_id_after_checkout' ) , 10 , 2 ) ;

            add_filter( 'woocommerce_cart_item_name' , array( __CLASS__ , 'show_message_next_to_free_product' ) , 10 , 3 ) ;

            add_action( 'woocommerce_after_cart_table' , array( __CLASS__ , 'display_free_product_after_cart_table' ) ) ;

            add_action( 'wp_ajax_delete_meta_current_key' , array( 'RSMemberFunction' , 'delete_saved_product_key_callback' ) ) ;

            add_action( 'woocommerce_cart_loaded_from_session' , array( __CLASS__ , 'alter_free_product_price' ) ) ;

            add_filter( 'woocommerce_cart_item_price' , array( __CLASS__ , 'woocommerce_cart_item_price_custom' ) , 10 , 3 ) ;

            if ( get_option( 'rs_free_product_add_quantity' ) == '1' ) {

                add_filter( 'woocommerce_cart_item_quantity' , array( __CLASS__ , 'alter_quantity_in_free_product' ) , 10 , 2 ) ;

                add_filter( 'woocommerce_is_sold_individually' , array( __CLASS__ , 'rs_free_product_direct_add_to_cart_quantity_restrict' ) , 10 , 2 ) ;
            }

            add_filter( 'woocommerce_add_to_cart_validation' , array( __CLASS__ , 'validate_add_to_cart' ) , 10 , 5 ) ;

            $order_status_control = array( 'cancelled' , 'failed' , 'refunded' ) ;
            foreach ( $order_status_control as $order_status ) {
                $orderstatuslist = array( 'pending ' , 'processing' , 'on-hold' , 'completed' ) ;
                if ( is_array( $orderstatuslist ) ) {
                    foreach ( $orderstatuslist as $value ) {
                        add_action( 'woocommerce_order_status_' . $value . '_to_' . $order_status , array( __CLASS__ , 'free_product_add_once' ) ) ;
                    }
                }
            }
            $order_status_control = array( 'pending ' , 'processing' , 'on-hold' , 'completed' ) ;
            foreach ( $order_status_control as $order_status ) {
                $orderstatuslist = array( 'cancelled' , 'failed' , 'refunded' ) ;
                if ( is_array( $orderstatuslist ) ) {
                    foreach ( $orderstatuslist as $value ) {
                        add_action( 'woocommerce_order_status_' . $value . '_to_' . $order_status , array( __CLASS__ , 'free_product_add_once_complete_order' ) ) ;
                    }
                }
            }
        }

        public static function validate_add_to_cart( $passed , $product_id , $quantity , $variation_id = '' , $variations = array() ) {
            $UserId              = get_current_user_id() ;
            $AllowedProductToAdd = check_if_free_product_already_exists_in_cart( $UserId ) ;
            $ProductId           = ($variation_id != 0 || $variation_id != '') ? $variation_id : $product_id ;
            if ( isset( $AllowedProductToAdd[ $ProductId ] ) && $AllowedProductToAdd[ $ProductId ] ) {
                if ( get_option( 'rs_free_product_add_quantity' ) == '1' ) {
                    wc_add_notice( __( 'This product already is in the cart.' , 'rewardsystem' ) , 'error' ) ;
                    return false ;
                }
            } else {
                $UnsetRemovedList = check_if_product_exists_in_free_product_list( $product_id , $UserId ) ;
                if ( $UnsetRemovedList ) {
                    delete_user_meta( $UserId , 'listsetofids' ) ;
                }
            }

            return $passed ;
        }

        public static function free_product_add_once_complete_order( $order_id ) {
            $order         = new WC_Order( $order_id ) ;
            $order_user_id = rs_get_order_obj( $order ) ;
            $order_user_id = $order_user_id[ 'order_userid' ] ;
            $get_datas     = get_option( 'rewards_dynamic_rule' ) ;
            foreach ( $get_datas as $value ) {
                foreach ( $order->get_items() as $item_id => $eachitem ) {
                    $productid    = $eachitem[ 'variation_id' ] != '0' ? $eachitem[ 'variation_id' ] : $eachitem[ 'product_id' ] ;
                    $getproductid = get_post_meta( $order_user_id , 'product_id_for_free_prduct' ) ;
                    if ( in_array( $productid , ( array ) $value[ 'product_list' ] ) ) {
                        $getproductid = get_post_meta( $order_user_id , 'product_id_for_free_prduct' , true ) ;
                        if ( ($key          = array_search( $productid , $getproductid )) !== false ) {
                            update_post_meta( $order_user_id , 'product_id_for_free_prduct' , $getproductid ) ;
                        } else {
                            $arraymerge = array_merge( $getproductid , ( array ) $productid ) ;
                            update_post_meta( $order_user_id , 'product_id_for_free_prduct' , $arraymerge ) ;
                        }
                    }
                }
            }
        }

        public static function rs_free_product_direct_add_to_cart_quantity_restrict( $quantity , $object ) {
            $userid              = get_current_user_id() ;
            $total_earned_points = get_option( 'rs_select_earn_points_based_on' ) == '1' ? RSPointExpiry::total_points_earned_in_site( $userid ) : RSPointExpiry::total_available_points_in_site( $userid ) ;
            $dynamicruleid       = FPRewardSystem_Free_Product::fp_get_free_product_level_id( $total_earned_points ) ;
            $getproductlists     = FPRewardSystem_Free_Product::fp_get_corresponding_product( $dynamicruleid ) ;
            $cart_pdt_id         = rs_get_id( $object ) ;
            if ( get_option( 'rs_enable_earned_level_based_reward_points' ) == 'yes' && $total_earned_points > 0 ) {
                if ( in_array( $cart_pdt_id , ( array ) $getproductlists ) ) {
                    $quantity = true ;
                }
            }
            return $quantity ;
        }

        public static function free_product_add_once( $order_id ) {
            $order         = new WC_Order( $order_id ) ;
            $order_user_id = rs_get_order_obj( $order ) ;
            $order_user_id = $order_user_id[ 'order_userid' ] ;
            $get_datas     = get_option( 'rewards_dynamic_rule' ) ;
            foreach ( $get_datas as $value ) {
                foreach ( $order->get_items() as $item_id => $eachitem ) {
                    $productid    = $eachitem[ 'variation_id' ] != '0' ? $eachitem[ 'variation_id' ] : $eachitem[ 'product_id' ] ;
                    $getproductid = get_post_meta( $order_user_id , 'product_id_for_free_prduct' ) ;
                    if ( is_array( $getproductid ) ) {
                        if ( in_array( $productid , ( array ) $value[ 'product_list' ] ) ) {
                            $getproductid = get_post_meta( $order_user_id , 'product_id_for_free_prduct' , true ) ;
                            if ( $getproductid != '' ) {
                                if ( ($key = array_search( $productid , $getproductid )) !== false ) {
                                    unset( $getproductid[ $key ] ) ;
                                    update_post_meta( $order_user_id , 'product_id_for_free_prduct' , $getproductid ) ;
                                }
                            }
                        }
                    }
                }
            }
        }

        public static function fp_get_free_product_level_id( $total_earned_points ) {
            if ( is_admin() )
                return 0 ;

            if ( ! is_user_logged_in() )
                return 0 ;

            $each_member_level = RSMemberFunction::multi_dimensional_sort( get_option( 'rewards_dynamic_rule' ) , 'rewardpoints' ) ;
            if ( $each_member_level == "" )
                return 0 ;

            $array = array() ;
            foreach ( $each_member_level as $key => $value ) {
                if ( get_option( 'rs_free_product_range' ) == '2' ) {
                    $current_level_earning_points_limit = $value[ "rewardpoints" ] ;
                    if ( $current_level_earning_points_limit <= $total_earned_points ) {
                        $array[ $current_level_earning_points_limit ] = $key ;
                    }
                } else {
                    $current_level_earning_points_limit = $value[ "rewardpoints" ] ;
                    if ( $current_level_earning_points_limit >= $total_earned_points ) {
                        $array[ $current_level_earning_points_limit ] = $key ;
                    }
                }
            }

            if ( empty( $array ) )
                return 0 ;

            if ( get_option( 'rs_free_product_range' ) == '2' ) {
                $MaxValue = max( array_keys( $array ) ) ;
                return $array[ $MaxValue ] ;
            } else {
                $MinValue = min( array_keys( $array ) ) ;
                return $array[ $MinValue ] ;
            }
        }

        public static function fp_get_corresponding_product( $dynamicruleid ) {
            global $woocommerce ;
            $get_datas = get_option( 'rewards_dynamic_rule' ) ;
            if ( isset( $dynamicruleid ) ) {
                $free_products_list = isset( $get_datas[ $dynamicruleid ][ 'product_list' ] ) ? $get_datas[ $dynamicruleid ][ 'product_list' ] : array() ;
                return $free_products_list ;
            }
        }

        public static function fp_check_if_free_product_is_in_cart( $productid , $dynamicruleid , $total_earned_points ) {
            global $woocommerce ;
            $productids     = array() ;
            $soloproductids = array() ;
            foreach ( $woocommerce->cart->cart_contents as $key => $values ) {
                $getids = $values[ 'variation_id' ] != '' ? $values[ 'variation_id' ] : $values[ 'product_id' ] ;

                $productids[]      = $getids ;
                $getfreeproductids = self::fp_get_corresponding_product( $dynamicruleid ) ;

                if ( ! in_array( $getids , ( array ) $getfreeproductids ) ) {
                    $soloproductids[] = $getids ;
                }
            }
            if ( in_array( $productid , ( array ) $productids ) ) {
                if ( count( $soloproductids ) > 1 ) {
                    return "true" ; //Found
                } else {
                    return "true" ;
                }
            } else {
                return "false" ; //Not Found
            }
        }

        public static function fp_add_free_product_to_cart( $product_id , $quantity , $variation_id = '' , $variation = '' ) {
            global $woocommerce ;
            WC()->cart->add_to_cart( $product_id , $quantity , $variation_id , $variation , $cart_item_data = array() ) ;
            rs_set_intial_price_for_free_product() ;
        }

        public static function fp_main_function_add_to_cart() {
            if ( ! is_user_logged_in() )
                return ;

            if ( ! is_cart() )
                return ;

            if ( get_option( 'rs_enable_earned_level_based_reward_points' ) != 'yes' )
                return ;

            $UserId                          = get_current_user_id() ;
            $ListofProductWithPrice          = array() ;
            $ListofProductWithoutPrice       = array() ;
            $MainVariations                  = array() ;
            $ListofCartItemKeyForFreeProduct = array() ;
            $CartItemKey                     = array() ;
            $TotalEarnedPoints               = get_option( 'rs_select_earn_points_based_on' ) == '1' ? RSPointExpiry::total_points_earned_in_site( $UserId ) : RSPointExpiry::total_available_points_in_site( $UserId ) ;
            if ( $TotalEarnedPoints == 0 )
                return ;

            $LevelId         = self::fp_get_free_product_level_id( $TotalEarnedPoints ) ;
            $FreeProductList = self::fp_get_corresponding_product( $LevelId ) ;
            if ( ! is_array( $FreeProductList ) && empty( $FreeProductList ) )
                return ;

            global $woocommerce ;
            foreach ( $FreeProductList as $ProductId ) {
                if ( $ProductId == '' )
                    continue ;

                $PurchasedFreeProductList = get_post_meta( $UserId , 'product_id_for_free_prduct' , true ) ;
                if ( in_array( $ProductId , ( array ) $PurchasedFreeProductList ) )
                    continue ;

                $cartremovedlist = ( array ) get_user_meta( $UserId , 'listsetofids' , true ) ;
                $ProductObj      = rs_get_product_object( $ProductId ) ;
                $VariationId     = (is_object( $ProductObj ) && $ProductObj->is_type( 'simple' )) ? 0 : ( int ) $ProductId ;
                $ParentId        = rs_get_post_parent( $ProductObj ) ;
                if ( $ParentId > 0 ) {
                    $parent_productid = $ParentId ;
                    $VariationObj     = new WC_Product_Variation( $ProductId ) ;
                    $Variations       = wc_get_formatted_variation( $VariationObj->get_variation_attributes() , true ) ;
                    $ExplodeVariation = explode( ',' , $Variations ) ;
                    foreach ( $ExplodeVariation as $EachVariation ) {
                        $ExplodeEachVariation                                        = explode( ': ' , $EachVariation ) ;
                        $MainVariations[ 'attribute_' . $ExplodeEachVariation[ 0 ] ] = $ExplodeEachVariation[ 1 ] ;
                    }
                    $getcurrentcartids                 = $woocommerce->cart->generate_cart_id( $parent_productid , $VariationId , $MainVariations ) ;
                    $ListofCartItemKeyForFreeProduct[] = $getcurrentcartids ;
                } else {
                    $parent_productid                  = $ProductId ;
                    $getcurrentcartids                 = $woocommerce->cart->generate_cart_id( $parent_productid , $VariationId , $MainVariations ) ;
                    $ListofCartItemKeyForFreeProduct[] = $getcurrentcartids ;
                }
                $getcartcount = $woocommerce->cart->cart_contents_count ;
                $cartcontent  = $woocommerce->cart->cart_contents ;
                foreach ( $cartcontent as $key => $val ) {
                    $productprice = $val[ 'line_subtotal' ] ;
                    if ( $productprice > 0 ) {
                        $ListofProductWithPrice[] = count( $productprice ) ;
                    } else {
                        $ListofProductWithoutPrice[] = count( $productprice ) ;
                    }
                }
                $ProductCountWithPrice    = array_sum( $ListofProductWithPrice ) ;
                $ProductCountWithoutPrice = array_sum( $ListofProductWithoutPrice ) ;
                $found_or_not             = self::fp_check_if_free_product_is_in_cart( $ProductId , $LevelId , $TotalEarnedPoints ) ;
                if ( ! in_array( $getcurrentcartids , $cartremovedlist ) ) {
                    if ( ($ProductCountWithPrice > 0 ) ) {
                        if ( $found_or_not == 'false' ) {
                            if ( ($getcartcount > 0 ) ) {
                                if ( get_option( 'rs_free_product_add_by_user_or_admin' ) == '1' ) {
                                    self::fp_add_free_product_to_cart( $parent_productid , 1 , $VariationId , $MainVariations ) ;
                                }
                            }
                            WC()->session->set( 'setruleids' , $LevelId ) ;
                            WC()->session->set( 'excludedummyids' , $LevelId ) ;
                            WC()->session->set( 'dynamicruleproducts' , $FreeProductList ) ;
                        }
                    } else {
                        if ( $ProductCountWithoutPrice == 1 ) {
                            $woocommerce->cart->remove_cart_item( $getcurrentcartids ) ;
                        } else {
                            foreach ( $ListofCartItemKeyForFreeProduct as $listofcartitemkey ) {
                                if ( ! in_array( $listofcartitemkey , $cartremovedlist ) ) {
                                    $woocommerce->cart->remove_cart_item( $listofcartitemkey ) ;
                                }
                            }
                        }
                    }
                }
                WC()->session->set( 'freeproductcartitemkeys' , $ListofCartItemKeyForFreeProduct ) ;
                if ( get_option( 'rs_free_product_add_by_user_or_admin' ) == '2' ) {
                    self::rs_function_to_create_order_for_free_product( $ProductId , $UserId , $TotalEarnedPoints ) ;
                }
            }
        }

        public static function rs_function_to_create_order_for_free_product( $eachproduct , $userid , $total_earned_points ) {
            $value = 'userid_' . $userid . $eachproduct ;
            if ( get_user_meta( $userid , $value , true ) != 'yes' ) {
                global $woocommerce ;
                $order                 = wc_create_order() ;
                $order->add_product( rs_get_product_object( $eachproduct ) , 1 ) ;
                $order->update_status( get_option( 'rs_order_status_control_to_automatic_order' ) , 'Imported order' , TRUE ) ;
                $orderid               = $order->get_order_number() ;
                $shipping              = $order->get_address() ;
                $order->set_address( $shipping ) ;
                update_post_meta( $orderid , '_customer_user' , $userid ) ;
                $address               = array(
                    'first_name' => get_user_meta( $userid , 'shipping_first_name' , true ) ,
                    'last_name'  => get_user_meta( $userid , 'shipping_last_name' , true ) ,
                    'company'    => get_user_meta( $userid , 'shipping_company' , true ) ,
                    'address_1'  => get_user_meta( $userid , 'shipping_address_1' , true ) ,
                    'address_2'  => get_user_meta( $userid , 'shipping_address_2' , true ) ,
                    'city'       => get_user_meta( $userid , 'shipping_city' , true ) ,
                    'state'      => get_user_meta( $userid , 'shipping_state' , true ) ,
                    'postcode'   => get_user_meta( $userid , 'shipping_postcode' , true ) ,
                    'country'    => get_user_meta( $userid , 'shipping_country' , true ) ,
                        ) ;
                $bill_email            = get_user_meta( $userid , 'billing_email' , true ) ;
                update_post_meta( $orderid , '_billing_email' , $bill_email ) ;
                $order->set_address( $address , $type                  = 'shipping' ) ;
                $order->set_address( $address ) ;
                $emailsubject          = get_option( 'rs_subject_for_free_product_mail' ) ;
                $findemailsubject      = str_replace( '[sitename]' , get_option( 'blogname' ) , $emailsubject ) ;
                $emailmessage          = get_option( 'rs_content_for_free_product_mail' ) ;
                $findemailmessage      = str_replace( '[current_level_points]' , $total_earned_points , $emailmessage ) ;
                $post_url              = admin_url( 'post.php?post=' . $orderid ) . '&action=edit' ;
                $myaccountlink         = get_permalink( get_option( 'woocommerce_myaccount_page_id' ) ) ;
                $vieworderlink         = esc_url_raw( add_query_arg( 'view-order' , $orderid , $myaccountlink ) ) ;
                $vieworderlinkforfront = '<a target="_blank" href="' . $vieworderlink . '">#' . $orderid . '</a>' ;
                $replace               = str_replace( '[rsorderlink]' , $vieworderlinkforfront , $findemailmessage ) ;
                $user                  = get_userdata( $userid ) ;
                $to                    = $user->user_email ;
                $subject               = $findemailsubject ;
                $firstname             = $user->user_firstname ;
                $lastname              = $user->user_lastname ;
                ob_start() ;
                wc_get_template( 'emails/email-header.php' , array( 'email_heading' => $subject ) ) ;
                echo $replace ;
                wc_get_template( 'emails/email-footer.php' ) ;
                $woo_temp_msg          = ob_get_clean() ;
                $headers               = "MIME-Version: 1.0\r\n" ;
                $headers               .= "Content-Type: text/html; charset=UTF-8\r\n" ;
                $headers               .= "From: " . get_option( 'woocommerce_email_from_name' ) . " <" . get_option( 'woocommerce_email_from_address' ) . ">\r\n" ;
                if ( '2' == get_option( 'rs_select_mail_function' ) ) {
                    if ( ( float ) $woocommerce->version <= ( float ) ('2.2.0') ) {
                        if ( wp_mail( $to , $subject , $woo_temp_msg , $headers = '' ) ) {
                            
                        }
                    } else {
                        $mailer = WC()->mailer() ;
                        $mailer->send( $to , $subject , $woo_temp_msg , $headers ) ;
                    }
                } elseif ( '1' == get_option( 'rs_select_mail_function' ) ) {
                    if ( mail( $to , $subject , $woo_temp_msg , $headers ) ) {
                        
                    }
                } else {
                    if ( ( float ) $woocommerce->version <= ( float ) ('2.2.0') ) {
                        if ( wp_mail( $to , $subject , $woo_temp_msg , $headers = '' ) ) {
                            
                        }
                    } else {
                        $mailer = WC()->mailer() ;
                        $mailer->send( $to , $subject , $woo_temp_msg , $headers ) ;
                    }
                }
                update_user_meta( $userid , $value , 'yes' ) ;
            }
        }

        public static function save_data_to_order( $orderid ) {
            global $woocommerce ;
            $order               = new WC_Order( $orderid ) ;
            $order_user_id       = rs_get_order_obj( $order ) ;
            $order_user_id       = $order_user_id[ 'order_userid' ] ;
            $total_earned_points = get_option( 'rs_select_earn_points_based_on' ) == '1' ? RSPointExpiry::total_points_earned_in_site( $order_user_id ) : RSPointExpiry::total_available_points_in_site( $order_user_id ) ;
            $getsavedsession     = self::fp_get_free_product_level_id( $total_earned_points ) ;
            $listofcartitemkeys  = WC()->session->get( "freeproductcartitemkeys" ) ;
            $getfreeproductmsg   = WC()->session->get( 'freeproductmsg' ) ;
            update_post_meta( $orderid , 'listruleids' , $getsavedsession ) ;
            $getalldatas         = get_option( 'rewards_dynamic_rule' ) ;
            if ( ! empty( $getalldatas ) && ($getsavedsession != NULL || $getsavedsession != '') ) {
                update_post_meta( $orderid , 'ruleidsdata' , $getalldatas[ $getsavedsession ] ) ;
                $order = new WC_Order( $orderid ) ;
                foreach ( $order->get_items() as $item_id => $eachitem ) {
                    $productid         = $eachitem[ 'variation_id' ] != '0' ? $eachitem[ 'variation_id' ] : $eachitem[ 'product_id' ] ;
                    $getlistofproducts = self::fp_get_corresponding_product( $getsavedsession ) ;
                    if ( in_array( $productid , ( array ) $getlistofproducts ) ) {

                        $getproductid = ( array ) get_post_meta( $order_user_id , 'product_id_for_free_prduct' , true ) ;
                        if ( $getproductid == '' ) {
                            update_post_meta( $order_user_id , 'product_id_for_free_prduct' , $productid ) ;
                        } else {
                            $arraymerge = array_merge( $getproductid , ( array ) $productid ) ;
                            update_post_meta( $order_user_id , 'product_id_for_free_prduct' , $arraymerge ) ;
                        }
                        if ( get_option( 'rs_enable_earned_level_based_reward_points' ) == 'yes' ) {
                            wc_add_order_item_meta( $item_id , '_ruleidsdata' , $getalldatas[ $getsavedsession ] ) ;
                            wc_add_order_item_meta( $item_id , '_rsfreeproductmsg' , $getfreeproductmsg ) ;
                        }
                    }
                }
                WC()->session->__unset( 'setruleids' ) ;
                WC()->session->__unset( 'freeproductcartitemkeys' ) ;
                WC()->session->__unset( 'freeproductmsg' ) ;
            }
        }

        public static function alter_free_product_price( $cart_object ) {
            if ( get_option( 'rs_enable_earned_level_based_reward_points' ) == 'yes' ) {
                $order_user_id            = get_current_user_id() ;
                $total_earned_points      = get_option( 'rs_select_earn_points_based_on' ) == '1' ? RSPointExpiry::total_points_earned_in_site( $order_user_id ) : RSPointExpiry::total_available_points_in_site( $order_user_id ) ;
                $getsessiondata           = self::fp_get_free_product_level_id( $total_earned_points ) ;
                ( array ) $getcorrespondingproducts = self::fp_get_corresponding_product( $getsessiondata ) ;
                $get_quantity             = get_option( 'rs_free_product_quantity' ) ;
                if ( get_option( 'rs_free_product_add_quantity' ) == '1' ) {
                    rs_set_intial_price_for_free_product() ;
                } else {
                    foreach ( $cart_object->cart_contents as $key => $value ) {
                        $productid = $value[ 'variation_id' ] != '' ? $value[ 'variation_id' ] : $value[ 'product_id' ] ;
                        if ( in_array( $productid , ( array ) $getcorrespondingproducts ) ) {
                            $cart_quantity = $value[ 'quantity' ] ;
                            if ( $cart_quantity > $get_quantity ) {
                                $price           = $value[ 'data' ]->get_price() ;
                                $exceed_quantity = $cart_quantity - $get_quantity ;
                                $price           = $price * $exceed_quantity ;
                                $price           = ($price / $cart_quantity) ;
                                $value[ 'data' ]->set_price( $price ) ;
                            } else {
                                $value[ 'data' ]->set_price( 0 ) ;
                            }
                        }
                    }
                }
            }
        }

        public static function woocommerce_cart_item_price_custom( $price , $item , $key ) {
            if ( get_option( 'rs_enable_earned_level_based_reward_points' ) != 'yes' )
                return $price ;

            if ( get_option( 'rs_free_product_add_by_user_or_admin' ) == '2' )
                return $price ;

            if ( get_option( 'rs_free_product_add_quantity' ) == '1' )
                return $price ;

            if ( get_option( 'rs_free_product_quantity' ) == '' )
                return $price ;

            $productid = $item[ 'variation_id' ] != '' ? $item[ 'variation_id' ] : $item[ 'product_id' ] ;
            $_product  = wc_get_product( $productid ) ;
            return wc_price( $_product->get_price() ) ;
        }

        public static function display_free_product_after_cart_table() {
            if ( get_option( 'rs_enable_earned_level_based_reward_points' ) != 'yes' )
                return ;

            global $woocommerce ;
            $get_product_for_user = array() ;
            ?>
            <style type="text/css">
                .fp_rs_display_free_product h3 {
                    display:none;
                }
            </style>
            <?php
            echo "<div class='fp_rs_display_free_product'>" ;
            echo "<h3>" ;
            echo get_option( 'rs_free_product_msg_caption' ) ;
            echo "</h3>" ;
            $userid               = get_current_user_id() ;
            $total_earned_points  = get_option( 'rs_select_earn_points_based_on' ) == '1' ? RSPointExpiry::total_points_earned_in_site( $userid ) : RSPointExpiry::total_available_points_in_site( $userid ) ;
            $dynamicruleid        = self::fp_get_free_product_level_id( $total_earned_points ) ;
            $getproductlists      = self::fp_get_corresponding_product( $dynamicruleid ) ;
            if ( ! empty( $getproductlists ) ) {
                if ( is_array( $getproductlists ) ) {
                    foreach ( $getproductlists as $eachproduct ) {
                        $get_product_for_user = get_post_meta( $userid , 'product_id_for_free_prduct' , true ) ;
                        if ( ! in_array( $eachproduct , ( array ) $get_product_for_user ) ) {
                            if ( $eachproduct != '' ) {
                                $product_object = rs_get_product_object( $eachproduct ) ;
                                $VariationId    = (is_object( $product_object ) && $product_object->is_type( 'simple' )) ? 0 : ( int ) $eachproduct ;
                                $post_parent    = rs_get_post_parent( $product_object ) ;
                                if ( $post_parent > 0 ) {
                                    $parent_productid  = $post_parent ;
                                    $variation_object  = new WC_Product_Variation( $eachproduct ) ;
                                    $variations        = wc_get_formatted_variation( $variation_object->get_variation_attributes() , true ) ;
                                    $variation_explode = explode( ',' , $variations ) ;
                                    $quantity          = 1 ;
                                    $main_variations   = array() ;
                                    foreach ( $variation_explode as $eachvariation ) {
                                        $explode2 = explode( ': ' , $eachvariation ) ;
                                        foreach ( $explode2 as $eachexplode => $eachvalue ) {
                                            $main_variations[ 'attribute_' . $explode2[ 0 ] ] = $explode2[ 1 ] ;
                                        }
                                    }
                                    $variations  = $main_variations ;
                                    $cartitemkey = $woocommerce->cart->generate_cart_id( $parent_productid , $VariationId , $variations ) ;
                                } else {
                                    $parent_productid = $eachproduct ;
                                    $variations       = array() ;
                                    $quantity         = 1 ;
                                    $cartitemkey      = $woocommerce->cart->generate_cart_id( $parent_productid , $VariationId , $variations ) ;
                                }

                                $listofdeletedkeys = get_user_meta( get_current_user_id() , 'listsetofids' , true ) ;
                                if ( in_array( $cartitemkey , ( array ) $listofdeletedkeys ) && $total_earned_points > 0 ) {
                                    $getthetitle   = get_the_title( $eachproduct ) . '<br>' ;
                                    $postthumbnail = get_the_post_thumbnail_url( $eachproduct ) ;
                                    $thumbnail_img = $postthumbnail == false ? wc_placeholder_img_src() : $postthumbnail ;
                                    ?>
                                    <style type="text/css">
                                        .fp_rs_display_free_product h3 {
                                            display:block;
                                        }
                                    </style>
                                    <a href="javascript:void(0)" class="add_removed_free_product_to_cart" data-cartkey="<?php echo $cartitemkey ; ?>"><img src="<?php echo $thumbnail_img ; ?>" width="30" height="30"/>  <?php echo $getthetitle ; ?></a><br/>
                                        <?php
                                    }
                                }
                            }
                        }
                    }
                }
                echo "</div>" ;
                ?>
            <script type="text/javascript">
                jQuery( document ).ready( function () {
                    jQuery( '.add_removed_free_product_to_cart' ).click( function () {
                        var removed_key = jQuery( this ).attr( 'data-cartkey' ) ;
                        var current_user_id = '<?php echo get_current_user_id() ; ?>' ;
                        var removed_key_param = {
                            action : "delete_meta_current_key" ,
                            key_to_remove : removed_key ,
                            current_user_id : current_user_id ,
                        } ;
                        jQuery.post( "<?php echo admin_url( 'admin-ajax.php' ) ; ?>" , removed_key_param , function ( response ) {
                            var newresponse = response.replace( /\s/g , '' ) ;
                            if ( newresponse === '1' ) {
                                location.reload() ;
                            }
                            console.log( 'Success' ) ;
                        } ) ;
                        return false ;
                    } ) ;
                    return false ;
                } ) ;
            </script>
            <?php
        }

        public static function show_message_next_to_free_product( $product_name , $cart_item , $cart_item_key ) {
            $productid                       = $cart_item[ 'variation_id' ] != '' ? $cart_item[ 'variation_id' ] : $cart_item[ 'product_id' ] ;
            $userid                          = get_current_user_id() ;
            $total_earned_points             = get_option( 'rs_select_earn_points_based_on' ) == '1' ? RSPointExpiry::total_points_earned_in_site( $userid ) : RSPointExpiry::total_available_points_in_site( $userid ) ;
            $dynamicruleid                   = self::fp_get_free_product_level_id( $total_earned_points ) ;
            $getproductfromrule              = self::fp_get_corresponding_product( $dynamicruleid ) ;
            $user_id                         = get_current_user_id() ;
            $free_product_message_to_find    = "[current_level_points]" ;
            $free_product_message_to_replace = $total_earned_points ;
            $roundofftype                    = get_option( 'rs_round_off_type' ) == '1' ? '2' : '0' ;
            $roundvalueuserpoint             = round_off_type( $free_product_message_to_replace ) ;
            $total_quantity_code             = '[free_product_quantity]' ;
            if ( get_option( 'rs_free_product_add_quantity' ) == '1' ) {
                $free_product_message_replaced = str_replace( $free_product_message_to_find , $roundvalueuserpoint , get_option( 'rs_free_product_message_info' ) ) ;
            } else {
                $total_quantity                = get_option( 'rs_free_product_quantity' ) ;
                $free_product_message_replaced = str_replace( $free_product_message_to_find , $roundvalueuserpoint , str_replace( $total_quantity_code , $total_quantity , get_option( 'rs_free_product_quantity_message_info' ) ) ) ;
            }
            if ( in_array( $productid , ( array ) $getproductfromrule ) ) {
                $order_user_id        = get_current_user_id() ;
                $get_product_for_user = get_post_meta( $order_user_id , 'product_id_for_free_prduct' , true ) ;
                if ( ! in_array( $productid , ( array ) $get_product_for_user ) ) {
                    if ( get_option( 'rs_remove_msg_from_cart_order' ) == 'yes' ) {
                        if ( get_option( 'rs_enable_earned_level_based_reward_points' ) == 'yes' ) {
                            WC()->session->set( 'freeproductmsg' , $free_product_message_replaced ) ;
                            return $product_name . "<br>" . $free_product_message_replaced ;
                        } else {
                            return $product_name ;
                        }
                    }
                } else {
                    return $product_name ;
                }
            } else {
                return $product_name ;
            }
        }

        public static function alter_quantity_in_free_product( $productquantity , $values ) {
            ( array ) $getcartitemkeys = WC()->session->get( 'freeproductcartitemkeys' ) == NULL ? array() : WC()->session->get( 'freeproductcartitemkeys' ) ;

            if ( is_array( $getcartitemkeys ) ) {

                if ( in_array( $values , ( array ) $getcartitemkeys ) ) {
                    if ( get_option( 'rs_enable_earned_level_based_reward_points' ) == 'yes' ) {
                        echo sprintf( '1 <input type="hidden" name="cart[%s][qty]" value="1" />' , $values ) ;
                        return ;
                    } else {
                        return $productquantity ;
                    }
                } else {

                    return $productquantity ;
                }
            } else {

                return $productquantity ;
            }
        }

        public static function show_item_id_after_checkout( $item_name , $item ) {
            @$freeproductmsg = $item[ 'rsfreeproductmsg' ] ;
            if ( $freeproductmsg != NULL && $freeproductmsg != '' ) {
                if ( get_option( 'rs_remove_msg_from_cart_order' ) == 'yes' ) {
                    return $item_name . "<br>" . $freeproductmsg ;
                } else {
                    return $item_name ;
                }
            } else {
                return $item_name ;
            }
        }

    }

    FPRewardSystem_Free_Product::init() ;
}