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

    class RSFunctionForOrder {

        public static function init() {
            global $woocommerce ;
            if ( ( float ) $woocommerce->version > ( float ) ('3.0.0') ) {
                add_action( 'woocommerce_order_details_after_order_table_items' , array ( __CLASS__ , 'display_total_redem_points_order' ) ) ;
            } else {
                add_action( 'woocommerce_order_items_table' , array ( __CLASS__ , 'display_total_redem_points_order' ) ) ;
            }

            add_action( 'woocommerce_email_after_order_table' , array ( __CLASS__ , 'get_the_total_earned_points_for_order' ) ) ;

            add_action( 'woocommerce_email_after_order_table' , array ( __CLASS__ , 'get_the_total_redeem_points_for_order' ) ) ;

            add_filter( 'woocommerce_get_formatted_order_total' , array ( __CLASS__ , 'display_total_point_price' ) , 10 , 2 ) ;

            add_filter( 'woocommerce_order_formatted_line_subtotal' , array ( __CLASS__ , 'display_line_total' ) , 8 , 3 ) ;

            add_filter( 'woocommerce_order_subtotal_to_display' , array ( __CLASS__ , 'display_line_total1' ) , 8 , 3 ) ;

            add_filter( 'woocommerce_get_order_item_totals' , array ( __CLASS__ , 'display_redeemed_value_for_order_in_thank_you_page' ) , 8 , 3 ) ;

            add_shortcode( 'rs_order_status' , array ( __CLASS__ , 'order_status_shortcode' ) ) ;
        }

        public static function display_redeemed_value_for_order_in_thank_you_page( $total_rows , $order , $tax_display ) {
            $OrderObj           = rs_get_order_obj( $order ) ;
            $OrderId            = $OrderObj[ 'order_id' ] ;
            $UserID             = $OrderObj[ 'order_userid' ] ;
            $UserData           = get_user_by( 'id' , $UserID ) ;
            $UserName           = is_object( $UserData ) ? $UserData->user_login : 'Guest' ;
            $SumoCouponName     = 'sumo_' . strtolower( $UserName ) ;
            $AutoSumoCouponName = 'auto_redeem_' . strtolower( $UserName ) ;
            $CouponsUsedInOrder = $order->get_items( array ( 'coupon' ) ) ;
            $CouponData         = array () ;
            $redeempoints       = RSFunctionToApplyCoupon::update_redeem_reward_points_to_user( $OrderId , $UserID ) ;
            foreach ( $CouponsUsedInOrder as $value ) {
                $CouponData[ $value[ 'code' ] ] = $value[ 'discount' ] ;
            }

            if ( array_key_exists( $SumoCouponName , $CouponData ) || array_key_exists( $AutoSumoCouponName , $CouponData ) ) {
                unset( $total_rows[ 'discount' ] ) ;
                $RedeemedPoints   = isset( $CouponData[ $SumoCouponName ] ) ? $CouponData[ $SumoCouponName ] : $CouponData[ $AutoSumoCouponName ] ;
                $OtherCouponValue = array_sum( $CouponData ) - $RedeemedPoints ;

                $ArrayKeys         = array_keys( $total_rows ) ;
                $IndexofArray      = array_search( 'cart_subtotal' , $ArrayKeys ) ;
                $PositionOfanIndex = false === $IndexofArray ? count( $total_rows ) : $IndexofArray + 1 ;

                if ( $RedeemedPoints > 0 ) {
                    $total_rows = array_slice( $total_rows , 0 , $PositionOfanIndex , true ) +
                            array ( 'redeeming' => array (
                                    'label' => __( 'Redeemed Points :' , 'rewardsystem' ) ,
                                    'value' => __( '-' . $order->get_discount_to_display( $tax_display ) , 'rewardsystem' ) ,
                                ) ) +
                            array_slice( $total_rows , $PositionOfanIndex , count( $total_rows ) - 1 , true ) ;
                }
                if ( $OtherCouponValue > 0 ) {
                    $total_rows = array_slice( $total_rows , 0 , $PositionOfanIndex , true ) +
                            array ( 'othercoupon' => array (
                                    'label' => __( 'Discount :' , 'rewardsystem' ) ,
                                    'value' => __( '-' . get_woocommerce_formatted_price( $OtherCouponValue ) , 'rewardsystem' ) ,
                                ) ) +
                            array_slice( $total_rows , $PositionOfanIndex , count( $total_rows ) - 1 , true ) ;
                }
            }
            return $total_rows ;
        }

        public static function display_line_total1( $line_total1 , $id , $order ) {
            $orderid       = rs_get_order_obj( $order ) ;
            $order_id      = $orderid[ 'order_id' ] ;
            $rewardgateway = RSFunctionForSavingMetaValues::rewardsystem_get_post_meta( $order_id , '_payment_method' ) ;
            $array         = array () ;
            $linetotal     = array () ;
            $updatedvalue  = array () ;
            if ( $rewardgateway == 'reward_gateway' ) {
                foreach ( $order->get_items()as $item ) {
                    $productid = $item[ 'variation_id' ] != 0 ? $item[ 'variation_id' ] : $item[ 'product_id' ] ;
                    if ( check_display_price_type( $productid ) == '2' ) {
                        if ( get_option( 'rs_enable_disable_point_priceing' ) == '1' && get_option( 'rs_point_price_activated' ) == 'yes' ) {
                            $label                = get_option( 'rs_label_for_point_value' ) ;
                            $replace              = str_replace( "/" , "" , $label ) ;
                            $enable               = calculate_point_price_for_products( $productid ) ;
                            $bundle_product_check = isset( $item[ 'bundled_by' ] ) ? $item[ 'bundled_by' ] : 0 ;
                            if ( $enable[ $productid ] != '' && $bundle_product_check == null ) {
                                $cart_object = $enable[ $productid ] * $item[ 'qty' ] ;
                                $array[]     = $cart_object ;
                            }
                        }
                    } else {
                        $label                = get_option( 'rs_label_for_point_value' ) ;
                        $replace              = str_replace( "/" , "" , $label ) ;
                        $enable               = calculate_point_price_for_products( $productid ) ;
                        $bundle_product_check = isset( $item[ 'bundled_by' ] ) ? $item[ 'bundled_by' ] : 0 ;
                        if ( $enable[ $productid ] != '' && $bundle_product_check == null ) {
                            $cart_object = $enable[ $productid ] * $item[ 'qty' ] ;
                            $array[]     = $cart_object ;
                        } else {
                            $linetotal      = $item[ 'line_subtotal' ] ;
                            $point_amount   = RSMemberFunction::user_role_based_redeem_points( $orderid[ 'order_userid' ] ) ;
                            $newvalue       = $linetotal / $point_amount ;
                            $updatedvalue[] = $newvalue * wc_format_decimal( get_option( 'rs_redeem_point' ) ) ;
                        }
                    }
                }

                $amount        = array_sum( $array ) + array_sum( $updatedvalue ) ;
                $roundofftype  = get_option( 'rs_round_off_type' ) == '1' ? '2' : '0' ;
                $amount        = round_off_type( $amount ) ;
                $labelposition = get_option( 'rs_sufix_prefix_point_price_label' ) ;
                $pxel          = get_option( 'rs_pixel_val' ) ;
                if ( $labelposition == '1' ) {
                    $product_price = "{$replace}<span style='margin-left:{$pxel}px;'>{$amount}</span>" ;
                } else {
                    $product_price = "{$amount}<span style='margin-left:{$pxel}px;'>{$replace}</span>" ;
                }
                return $product_price ;
            } else {
                return $line_total1 ;
            }
        }

        public static function order_status_shortcode() {
            $orderstatuslist = get_option( 'rs_order_status_control' ) ;
            $order_status    = implode( "," , $orderstatuslist ) ;
            return '{' . $order_status . '}' ;
        }

        public static function display_line_total( $line_total1 , $id , $order ) {
            $orderid       = rs_get_order_obj( $order ) ;
            $order_id      = $orderid[ 'order_id' ] ;
            $rewardgateway = RSFunctionForSavingMetaValues::rewardsystem_get_post_meta( $order_id , '_payment_method' ) ;
            if ( $rewardgateway == 'reward_gateway' ) {
                $product_id = $id[ 'variation_id' ] != 0 ? $id[ 'variation_id' ] : $id[ 'product_id' ] ;
                $label      = get_option( 'rs_label_for_point_value' ) ;
                $replace    = str_replace( "/" , "" , $label ) ;
                $enable     = calculate_point_price_for_products( $product_id ) ;
                if ( $enable[ $product_id ] != '' ) {
                    $cart_object   = $enable[ $product_id ] * $id[ 'qty' ] ;
                    $array         = $cart_object ;
                    $roundofftype  = get_option( 'rs_round_off_type' ) == '1' ? '2' : '0' ;
                    $array         = round_off_type( $array ) ;
                    $labelposition = get_option( 'rs_sufix_prefix_point_price_label' ) ;
                    $pxel          = get_option( 'rs_pixel_val' ) ;
                    if ( $labelposition == '1' ) {
                        $product_price = "{$replace}<span style='margin-left:{$pxel}px;'>{$array}</span>" ;
                    } else {
                        $product_price = "{$array}<span style='margin-left:{$pxel}px;'>{$replace}</span>" ;
                    }
                    return $product_price ;
                } else {
                    $linetotal     = $id[ 'line_subtotal' ] ;
                    $point_amount  = RSMemberFunction::user_role_based_redeem_points( $orderid[ 'order_userid' ] ) ;
                    $newvalue      = $linetotal / $point_amount ;
                    $updatedvalue  = $newvalue * wc_format_decimal( get_option( 'rs_redeem_point' ) ) ;
                    $roundofftype  = get_option( 'rs_round_off_type' ) == '1' ? '2' : '0' ;
                    $updatedvalue  = round_off_type( $updatedvalue ) ;
                    $labelposition = get_option( 'rs_sufix_prefix_point_price_label' ) ;
                    if ( $labelposition == '1' ) {
                        $product_price = $replace . $updatedvalue ;
                    } else {
                        $product_price = $updatedvalue . '<span style="margin-left:10px;">' . $replace . '</span>' ;
                    }

                    return $product_price ;
                }
            } else {
                return $line_total1 ;
            }
        }

        public static function display_total_point_price( $order1 , $order ) {
            $orderid       = rs_get_order_obj( $order ) ;
            $order_id      = $orderid[ 'order_id' ] ;
            $rewardgateway = RSFunctionForSavingMetaValues::rewardsystem_get_post_meta( $order_id , '_payment_method' ) ;
            if ( $rewardgateway == 'reward_gateway' ) {
                $updatedvalue        = array () ;
                $replace             = '' ;
                global $woocommerce ;
                $shipping_total      = '' ;
                $updatedvalue1       = '' ;
                $couponamount        = '' ;
                $couponamount1       = array () ;
                $updatedvalue        = array () ;
                $array               = array () ;
                $rewardpointscoupons = $order->get_items( array ( 'coupon' ) ) ;
                foreach ( $rewardpointscoupons as $coupon ) {
                    $couponamount1[] = $coupon[ 'discount_amount' ] ;
                }
                $couponamount = array_sum( $couponamount1 ) ;

                foreach ( $order->get_items()as $item ) {

                    if ( get_option( 'woocommerce_prices_include_tax' ) === 'yes' ) {
                        $shipping_total = $order->get_total_shipping() ;
                        $tax_total      = 0 ;
                    } else {
                        $shipping_total = $order->get_total_shipping() ;
                        $tax_total      = $order->get_total_tax() ;
                    }
                    $shipping_total       = $shipping_total + $tax_total ;
                    $point_amount         = RSMemberFunction::user_role_based_redeem_points( $orderid[ 'order_userid' ] ) ;
                    $newvalue1            = $shipping_total / $point_amount ;
                    $updatedvalue1        = $newvalue1 * wc_format_decimal( get_option( 'rs_redeem_point' ) ) ;
                    $product_id           = $item[ 'variation_id' ] != 0 ? $item[ 'variation_id' ] : $item[ 'product_id' ] ;
                    $label                = get_option( 'rs_label_for_point_value' ) ;
                    $replace              = str_replace( "/" , "" , $label ) ;
                    $enable               = calculate_point_price_for_products( $product_id ) ;
                    $bundle_product_check = isset( $item[ 'bundled_by' ] ) ? $item[ 'bundled_by' ] : 0 ;
                    if ( $enable[ $product_id ] != '' && $bundle_product_check == null ) {
                        $cart_object = $enable[ $product_id ] * $item[ 'qty' ] ;
                        $array[]     = $cart_object ;
                    } else {
                        $linetotal      = $item[ 'line_subtotal' ] ;
                        $point_amount   = RSMemberFunction::user_role_based_redeem_points( $orderid[ 'order_userid' ] ) ;
                        $newvalue       = $linetotal / $point_amount ;
                        $updatedvalue[] = $newvalue * wc_format_decimal( get_option( 'rs_redeem_point' ) ) ;
                    }
                }


                $amount        = array_sum( $array ) + array_sum( $updatedvalue ) - $couponamount ;
                $amount        = $amount + $updatedvalue1 ;
                $roundofftype  = get_option( 'rs_round_off_type' ) == '1' ? '2' : '0' ;
                $amount        = round_off_type( $amount ) ;
                $labelposition = get_option( 'rs_sufix_prefix_point_price_label' ) ;
                $pxel          = get_option( 'rs_pixel_val' ) ;
                if ( $labelposition == '1' ) {
                    $product_price = "{$replace}<span style='margin-left:{$pxel}px;'>{$amount}</span>" ;
                } else {
                    $product_price = "{$amount}<span style='margin-left:{$pxel}px;'>{$replace}</span>" ;
                }
                return $product_price ;
            } else {
                return $order1 ;
            }
        }

        public static function display_total_redem_points_order( $order ) {
            if ( get_option( 'rs_product_purchase_activated' ) != 'yes' )
                return ;

            if ( get_option( 'rs_show_hide_total_points_order_field' ) == '2' )
                return ;

            $orderid      = rs_get_order_obj( $order ) ;
            $order_id     = $orderid[ 'order_id' ] ;
            $redeem_check = get_post_meta( $order_id , 'rs_check_enable_option_for_redeeming' , true ) ;
            if ( $redeem_check != 'no' )
                return ;

            $payment_plan_pts   = get_payment_product_price( $order_id , true ) ;
            $producttotalpoints = get_post_meta( $order_id , 'points_for_current_order' , true ) ;
            $carttotalpoints    = get_post_meta( $order_id , 'points_for_current_order_based_on_cart_total' , true ) ;
            $points             = $producttotalpoints == '' ? $carttotalpoints : $producttotalpoints ;

            if ( $points == '' )
                return ;

            $OrderTotal          = $order->get_total() ;
            $Setup               = get_option( 'rs_enable_product_category_level_for_product_purchase' ) ;
            $RewardPointsBasedOn = get_option( 'rs_award_points_for_cart_or_product_total' ) ;
            if ( $Setup == 'no' && $RewardPointsBasedOn == '2' ) {
                $OrderTotal   = get_reward_points_based_on_cart_total( $OrderTotal ) ;
                $OrderTotal   = RSMemberFunction::user_role_based_reward_points( get_current_user_id() , $OrderTotal ) ;
                $total_points = $OrderTotal ;
                $getcals      = $OrderTotal / wc_format_decimal( get_option( 'rs_redeem_point' ) ) ;
                $point_amount = RSMemberFunction::user_role_based_redeem_points( $orderid[ 'order_userid' ] ) ;
                $updatedvalue = $getcals * $point_amount ;
            } else {
                $total_points    = array_sum( ( array ) $producttotalpoints ) - $payment_plan_pts ;
                $getcals         = $total_points / wc_format_decimal( get_option( 'rs_redeem_point' ) ) ;
                $point_amount    = RSMemberFunction::user_role_based_redeem_points( $orderid[ 'order_userid' ] ) ;
                $updatedvalue    = $getcals * $point_amount ;
                $PointstoDisplay = RSMemberFunction::user_role_based_reward_points( get_current_user_id() , $total_points ) ;
            }
            $reward_value      = get_woocommerce_formatted_price( round_off_type_for_currency( $updatedvalue ) ) ;
            $message           = '' ;
            $eq_price_enable   = 'rs_show_hide_equivalent_price_for_points_thankyou' ;
            $custom_msg_enable = 'rs_show_hide_custom_msg_for_points_thankyou' ;
            $custom_msg        = 'rs_custom_message_for_points_thankyou' ;
            if ( $total_points != 0 && (get_current_user_id() != 0 ) ) {
                ?>
                <tfoot>
                    <tr class="cart-total">
                        <th><?php echo do_shortcode( get_option( 'rs_total_earned_point_caption_thank_you' ) ) ; ?></th>
                        <td><?php
                            echo display_custom_message_in_point_can_earned( $OrderTotal , $total_points , $message , $reward_value , $eq_price_enable , $custom_msg_enable , $custom_msg , $payment_plan_pts = 0 ) ;
                            ?></td>
                    </tr>
                </tfoot>
                <?php
            }
        }

        /* To get the total earned for order */

        public static function get_the_total_earned_points_for_order( $order ) {
            global $wpdb ;
            $status             = get_option( 'rs_order_status_control' ) ;
            $table_name         = $wpdb->prefix . 'rsrecordpoints' ;
            $orderid            = rs_get_order_obj( $order ) ;
            $orderstatus        = $orderid[ 'order_status' ] ;
            $user_id            = $orderid[ 'order_userid' ] ;
            $order_id           = $orderid[ 'order_id' ] ;
            $gettotalearnpoints = $wpdb->get_results( "SELECT earnedpoints FROM $table_name WHERE orderid = $order_id AND userid = $user_id AND checkpoints = 'PPRP'" , ARRAY_A ) ;
            $ReplacedPoints     = $wpdb->get_results( "SELECT earnedpoints FROM $table_name WHERE orderid = $order_id AND reasonindetail = 'Replaced' AND userid = $user_id AND checkpoints = 'PPRP'" , ARRAY_A ) ;
            if ( is_array( $status ) ) {
                foreach ( $status as $statuses ) {
                    $statusstr = $statuses ;
                }
            }
            $replacestatus = str_replace( 'wc-completed' , $statusstr , $orderstatus ) ;
            if ( get_option( 'rs_enable_msg_for_earned_points' ) == 'yes' ) {
                if ( in_array( $replacestatus , $status ) ) {
                    $totalearnedvalue = 0 ;
                    $earned_total     = (is_array( $ReplacedPoints ) && ! empty( $ReplacedPoints )) ? $ReplacedPoints : $gettotalearnpoints ;
                    if ( is_array( $earned_total ) ) {
                        foreach ( $earned_total as $key => $value ) {
                            $totalearnedvalue += ( float ) $value[ 'earnedpoints' ] ;
                        }
                        $msgforearnedpoints        = get_option( 'rs_msg_for_earned_points' ) ;
                        $roundofftype              = get_option( 'rs_round_off_type' ) == '1' ? '2' : '0' ;
                        $replacemsgforearnedpoints = str_replace( '[earnedpoints]' , $totalearnedvalue != "" ? round_off_type( $totalearnedvalue ) : "0" , $msgforearnedpoints ) ;
                        echo apply_filters( 'rs_display_total_earnpoints_for_order' , '<br><br>' . '<b>' . $replacemsgforearnedpoints . '<b>' . '<br><br>' ) ;
                    }
                }
            }
        }

        /* To get the total redeem for order */

        public static function get_the_total_redeem_points_for_order( $order ) {
            $status               = get_option( 'rs_order_status_control' ) ;
            global $wpdb ;
            $table_name           = $wpdb->prefix . 'rsrecordpoints' ;
            $orderid              = rs_get_order_obj( $order ) ;
            $orderstatus          = $orderid[ 'order_status' ] ;
            $orderid              = $orderid[ 'order_id' ] ;
            $gettotalredeempoints = $wpdb->get_results( "SELECT redeempoints FROM $table_name WHERE orderid=$orderid" , ARRAY_A ) ;
            if ( is_array( $status ) ) {
                foreach ( $status as $statuses ) {
                    $statusstr = $statuses ;
                }
            }
            $replacestatus = str_replace( 'wc-completed' , $statusstr , $orderstatus ) ;
            if ( get_option( 'rs_enable_msg_for_redeem_points' ) == 'yes' ) {
                if ( in_array( $replacestatus , $status ) ) {
                    $totalredeemvalue = 0 ;
                    $redeem_total     = $gettotalredeempoints ;
                    if ( is_array( $redeem_total ) ) {
                        foreach ( $redeem_total as $key => $value ) {
                            $totalredeemvalue += ( float ) $value[ 'redeempoints' ] ;
                        }
                        $msgforredeempoints        = get_option( 'rs_msg_for_redeem_points' ) ;
                        $roundofftype              = get_option( 'rs_round_off_type' ) == '1' ? '2' : '0' ;
                        $replacemsgforredeempoints = str_replace( '[redeempoints]' , $totalredeemvalue != "" ? round_off_type( $totalredeemvalue ) : "0" , $msgforredeempoints ) ;
                        echo apply_filters( 'rs_display_total_redeempoints_for_order' , '<b>' . $replacemsgforredeempoints . '</b>' ) ;
                    }
                }
            }
        }

    }

    RSFunctionForOrder::init() ;
}