<?php
if (!class_exists('ARM_manage_coupons'))
{
	class ARM_manage_coupons
	{
		var $isCouponFeature;
		function __construct()
		{
			global $wpdb, $ARMember, $arm_slugs;
			$is_coupon_feature = get_option('arm_is_coupon_feature', 0);
			$this->isCouponFeature = ($is_coupon_feature == '1') ? true : false;

			add_action('wp_ajax_arm_generate_code', array(&$this, 'arm_generate_code'));
			add_action('arm_admin_save_coupon_details', array(&$this, 'arm_admin_save_coupon_details'));
			add_action('wp_ajax_arm_apply_coupon_code', array(&$this, 'arm_apply_coupon_code'));
			add_action('wp_ajax_nopriv_arm_apply_coupon_code', array(&$this, 'arm_apply_coupon_code'));
			add_action('wp_ajax_arm_delete_single_coupon', array(&$this, 'arm_delete_single_coupon'));
			add_action('wp_ajax_arm_delete_bulk_coupons',array(&$this,'arm_delete_bulk_coupons'));
			add_action('wp_ajax_arm_update_coupons_status', array(&$this, 'arm_update_coupons_status'));
		}
		function arm_apply_coupon_code($coupon_code = '', $plan_id = null, $setup_id = 0, $payment_cycle = 0 , $arm_user_old_plan = array())
		{
            global $wpdb, $ARMember, $arm_subscription_plans, $arm_global_settings, $arm_payment_gateways, $arm_membership_setup;
			$return = array(
                'status' => 'error',
                'message' => __('You can not redeem this coupon code right now.', 'ARMember'),
                'validity' => 'invalid_coupon',
                'coupon_amt' => 0,
                'total_amt' => 0,
                'discount' => 0,
                'discount_type' => '',
            );
            $err_empty_coupon = $arm_global_settings->common_message['arm_empty_coupon'];
            $err_invalid_coupon = $arm_global_settings->common_message['arm_invalid_coupon'];
            $err_invalid_coupon_plan = $arm_global_settings->common_message['arm_invalid_coupon_plan'];
            $err_coupon_expire = $arm_global_settings->common_message['arm_coupon_expire'];
            $success_coupon = $arm_global_settings->common_message['arm_success_coupon'];
     
            $gateway = (isset($_REQUEST['gateway']) && !empty($_REQUEST['gateway'])) ? $_REQUEST['gateway'] : '';
            $payment_mode = (isset($_REQUEST['payment_mode']) && !empty($_REQUEST['payment_mode'])) ? $_REQUEST['payment_mode'] : '';
			if ($this->isCouponFeature) {
                $reqCoupon = (isset($_REQUEST['coupon_code']) && !empty($_REQUEST['coupon_code'])) ? $_REQUEST['coupon_code'] : '';
                $reqPlanID = (isset($_REQUEST['plan_id']) && !empty($_REQUEST['plan_id'])) ? $_REQUEST['plan_id'] : 0;
                $reqSetupID = (isset($_REQUEST['setup_id']) && !empty($_REQUEST['setup_id'])) ? $_REQUEST['setup_id'] : 0;
                $reqUserOldPlan = (isset($_REQUEST['user_old_plan']) && !empty($_REQUEST['user_old_plan'])) ? explode(",",$_REQUEST['user_old_plan']) : 0;
                $paymentCycle = (isset($_REQUEST['payment_cycle']) && !empty($_REQUEST['payment_cycle']))? $_REQUEST['payment_cycle'] : 0;
                $coupon_code = (!empty($coupon_code)) ? $coupon_code : $reqCoupon;
                $couponData = $this->arm_get_coupon($coupon_code);
                $setupid = (!empty($setup_id)) ? $setup_id : $reqSetupID;
                $arm_user_old_plan =  !empty($arm_user_old_plan) ? $arm_user_old_plan : $reqUserOldPlan; 
                $payment_cycle = ($payment_cycle!= '') ? $payment_cycle : $paymentCycle;
                $is_used_as_invitation_code = false;
                $planAmt = 0;
                if($setupid != 0)
                {
                    $setup_data = $arm_membership_setup->arm_get_membership_setup($setupid);
                    
                     if (!empty($setup_data) && !empty($setup_data['setup_modules']['modules'])) {
                         $setup_modules = $setup_data['setup_modules'];
                         $is_used_as_invitation_code= (isset($setup_modules['modules']['coupon_as_invitation']) && $setup_modules['modules']['coupon_as_invitation'] == 1) ? true : false;
                     }
                }
                if (!empty($couponData)) {
                    
                    $plan_id = ( null === $plan_id ) ? $reqPlanID : $plan_id;
                    if (is_object($plan_id)) {
                        $planObj = $plan_id;
                    } else {
                        $planObj = new ARM_Plan($plan_id);
                    }
                    if ($planObj->exists()) {
                        $plans = $couponData['arm_coupon_subscription'];
                        $allow_plan_ids = explode(',', $plans);
                        $allowOnTrial = $couponData['arm_coupon_allow_trial'];
                        $user_count = $couponData['arm_coupon_used'];
                        $allowed_uses = $couponData['arm_coupon_allowed_uses'];
                        if ($couponData['arm_coupon_status'] != '1') {
                            $return['message'] = $err_invalid_coupon;
                            $return['validity'] = 'invalid_coupon';
                        } elseif ($allowed_uses != 0 && $allowed_uses <= $user_count) {
                            $return['message'] = $err_coupon_expire;
                            $return['validity'] = 'expired';
                        } elseif ($couponData['arm_coupon_period_type'] == 'daterange' && time() < strtotime($couponData['arm_coupon_start_date'])) {
                            $return['message'] = $err_invalid_coupon;
                            $return['validity'] = 'invalid_coupon';
                        } elseif ($couponData['arm_coupon_period_type'] == 'daterange' && time() > strtotime($couponData['arm_coupon_expire_date'])) {
                            $return['message'] = $err_coupon_expire;
                            $return['validity'] = 'expired';
                        } elseif (!empty($plans) && !in_array($planObj->ID, $allow_plan_ids)) {
                            $return['message'] = $err_invalid_coupon_plan;
                            $return['validity'] = 'invalid_plan';
                        } else {
                            $arm_coupon_not_allowed_on_trial = 0;
                            
                            if($planObj->is_recurring()) {
                                if(isset($planObj->options['payment_cycles']) && !empty($planObj->options['payment_cycles'])) {
                                    $planAmt = str_replace(',','',$planObj->options['payment_cycles'][$payment_cycle]['cycle_amount']);
                                }
                                else {
                                    $planAmt = str_replace(',','',$planObj->amount);
                                }
                                $planAmt = str_replace(',','',$planAmt);
                            }
                            else {
                                $planAmt = str_replace(',','',$planObj->amount);
                            }
                            
                            if ($planObj->has_trial_period() && (empty($arm_user_old_plan) || $arm_user_old_plan == 0)) {
                                if ($allowOnTrial == '1') {
                                    $planAmt = !empty($planObj->options['trial']['amount']) ? $planObj->options['trial']['amount'] : 0;
                                }
                                else {
                                    $planAmt = 0;
                                    $arm_coupon_not_allowed_on_trial = 1;
                                }
                            }
                      
                            if (!empty($planAmt) && $planAmt != 0) {
                                do_action('arm_before_apply_coupon_code', $coupon_code, $planObj->ID);
                                $couponAmt = $couponData['arm_coupon_discount'];
                                if ($couponData['arm_coupon_discount_type'] == 'percentage') {
                                    $couponAmt = ($planAmt * $couponAmt) / 100;
                                }
                                $discount_amount = floatval(str_replace(',','',$planAmt));
                                if (!empty($couponAmt) && $couponAmt > 0) {
                                    if($couponAmt > $discount_amount){
                                        $couponAmt = $planAmt;
                                        $discount_amount = '0';
                                    } else {
                                        $discount_amount = $discount_amount - $couponAmt;
                                    }
                                }
                                $global_currency = $arm_payment_gateways->arm_get_global_currency();
                                $couponAmt = $arm_payment_gateways->arm_amount_set_separator($global_currency, $couponAmt, true);
                                $discount_amount = $arm_payment_gateways->arm_amount_set_separator($global_currency, $discount_amount);
                                $final_amount = $discount_amount . ' ' . $global_currency;
                                $return = array (
                                    'status' => 'success', 'message' => $success_coupon,
                                    'coupon_amt' => $couponAmt, 'total_amt' => $discount_amount,
                                    'discount_type' => $couponData['arm_coupon_discount_type'],
                                    'discount' => $couponData['arm_coupon_discount'],
                                    'arm_coupon_on_each_subscriptions' => $couponData['arm_coupon_on_each_subscriptions'],
                                );
                                do_action('arm_after_apply_coupon_code', $coupon_code, $planObj->ID);
                            } else {
                                if(($planAmt == 0 && $is_used_as_invitation_code == true && $arm_coupon_not_allowed_on_trial == 0) || (!empty($couponData['arm_coupon_on_each_subscriptions'])) )
                                {
                                    $couponAmt = $couponData['arm_coupon_discount'];
                                    $discount_amount = $planAmt;
                                    $return = array (
                                    'status' => 'success', 'message' => $success_coupon,
                                    'discount_type' => $couponData['arm_coupon_discount_type'],
                                    'discount' => $couponData['arm_coupon_discount'],
                                    'arm_coupon_on_each_subscriptions' => $couponData['arm_coupon_on_each_subscriptions'],
                                    );
                                }
                                else {
                                    $return['message'] = $err_invalid_coupon_plan;
                                    $return['validity'] = 'invalid_plan';
                                }
                            }
                        }
                    } else {
                        $return['message'] = $err_invalid_coupon;
                        $return['validity'] = 'invalid_coupon';
                    }
                } else {
                    $return['message'] = $err_invalid_coupon;
                    $return['validity'] = 'invalid_coupon';
                }
                /* Modify Coupon Code outside from plugin */
                $planObj = isset($planObj) ? $planObj : '';
                $return = apply_filters('arm_change_coupon_code_outside_from_'.$gateway,$return,$payment_mode,$couponData,$planAmt,$planObj);
            }

            if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'arm_apply_coupon_code') {
				echo json_encode($return);
				exit;
			}
			return $return;
        }
		function arm_redeem_coupon_html($content = '', $labels = array(), $plan_data = array(), $btn_style_class = '', $is_used_as_invitation_code = false , $setupRandomID = '',$formPosition = 'left')
		{
			global $wpdb, $ARMember, $arm_subscription_plans, $arm_global_settings;
			if ($this->isCouponFeature) {
				$coupon_code = (!empty($_REQUEST['arm_coupon_code'])) ? $_REQUEST['arm_coupon_code'] : '';
				$plan_id = (isset($plan_data['arm_subscription_plan_id'])) ? $plan_data['arm_subscription_plan_id'] : 0;
				$check_coupon = $this->arm_apply_coupon_code($coupon_code, $plan_id);
                
                $err_empty_coupon = $arm_global_settings->common_message['arm_empty_coupon'];
                $err_invalid_coupon = $arm_global_settings->common_message['arm_invalid_coupon'];
                $err_invalid_coupon_plan = $arm_global_settings->common_message['arm_invalid_coupon_plan'];
                $err_coupon_expire = $arm_global_settings->common_message['arm_coupon_expire'];
                $success_coupon = $arm_global_settings->common_message['arm_success_coupon'];
                $couponMessages = '<div data-ng-message="required" class="arm_error_msg"><div class="arm_error_box_arrow"></div>' . stripcslashes($err_empty_coupon) . '</div>';
                $couponMessages .= '<div data-ng-message="invalid_coupon" class="arm_error_msg"><div class="arm_error_box_arrow"></div>' . stripcslashes($err_invalid_coupon) . '</div>';
                $couponMessages .= '<div data-ng-message="invalid_plan" class="arm_error_msg"><div class="arm_error_box_arrow"></div>' . stripcslashes($err_invalid_coupon_plan) . '</div>';
                $couponMessages .= '<div data-ng-message="expired" class="arm_error_msg"><div class="arm_error_box_arrow"></div>' . stripcslashes($err_coupon_expire) . '</div>';
                
				$coupon_code_message = '';
				if ($check_coupon['status'] == 'success' && $check_coupon['plan_type'] != 'free') {
					$coupon_code_message = '<span class="success notify_msg">' . $check_coupon['message'] . '</span>';
				} else {
					$coupon_code = '';
				}
				$title_text = (!empty($labels['title'])) ? $labels['title'] : __('Have a coupon code?', 'ARMember');
				$button_text = (!empty($labels['button'])) ? $labels['button'] : __('Apply', 'ARMember');
				$content = apply_filters('arm_before_redeem_coupon_section', $content);
                $couponBoxID = arm_generate_random_code(20);
                
                switch($formPosition){
                    case 'left':
                        $coupon_style = $coupon_submit_style = "float:left;";
                        break;
                    case 'center':
                        $coupon_style = "float:none;margin:0 auto -6px !important;";
                        $coupon_submit_style = "float:none;";
                        break;
                    case 'right':
                        $coupon_style = $coupon_submit_style = "float:right;";
                        break;
                }
                
                $content .= '<div class="arm_apply_coupon_container arm_position_'.$formPosition.'" id="'.$couponBoxID.'">';
                    $coupon_style = "";
                    $coupon_submit_style = "";
                        $content .= '<div class="arm_coupon_field_wrapper arm_form_field_container arm_form_field_container_text" style="'.$coupon_style.'">';
                            $content .= '<div class="arm_form_input_wrapper">';
                                $content .= '<div class="arm_form_input_container arm_form_input_container_coupon_code">';
                                    $content .= '<md-input-container class="md-block" flex-gt-sm="">';
                                        if($is_used_as_invitation_code == true){
                                            $couponInputAttr = ' data-ng-required="isCouponRequired(\'#arm_setup_form_'.$setupRandomID.'\')" data-isRequiredCoupon="true" ';
                                        } else {
                                            $couponInputAttr = ' data-isRequiredCoupon="false" ';
                                        }
                                        $content .= '<label class="arm_material_label">' . $title_text . '</label>';
                                        $content .= '<input type="text" name="arm_coupon_code" data-ng-model="arm_form.coupon_code_val" value="'.$coupon_code.'" class="field_coupon_code arm_coupon_code" data-checkcouponcode="1" '.$couponInputAttr.' >';
                                        $content .= '<div data-ng-cloak data-ng-messages="arm_form.arm_coupon_code.$error" class="arm_error_msg_box ng-scope">';
                                            $content .= $couponMessages;
                                        $content .= '</div>';
                                    $content .= '</md-input-container>';
                                    $content .= $coupon_code_message;
                                $content .= '</div>';
                            $content .= '</div>';
                        $content .= '</div>';
                        $content .= '<div class="arm_coupon_submit_wrapper arm_form_field_container arm_form_field_container_submit" style="'.$coupon_submit_style.'">';
                            $content .= '<div class="arm_form_input_wrapper">';
                                $content .= '<div class="arm_form_input_container_submit arm_form_input_container" id="arm_setup_coupon_button_container">';
                                $content .= '<md-button type="button" class="arm_apply_coupon_btn arm_form_field_submit_button arm_form_field_container_button arm_form_input_box arm_material_input '.$btn_style_class.'"><span class="arm_spinner">'.file_get_contents(MEMBERSHIP_IMAGES_DIR."/loader.svg").'</span>' . esc_html(stripslashes($button_text)) . '</md-button>';
                                $content .= '</div>';
                            $content .= '</div>';
                        $content .= '</div>';
                    $content .= '</div>';
				$content = apply_filters('arm_after_redeem_coupon_section', $content);
			}
			return $content;
		}
		function arm_generate_coupon_code()
		{
			$couponCode = '';
			if (function_exists('arm_generate_random_code')) {
				$couponCode = arm_generate_random_code(8);
			} else {
				$coupon_char = array();
				$coupon_char[] = array('count' => 6, 'char' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
				$coupon_char[] = array('count' => 2, 'char' => '0123456789');
				$temp_array = array();
				foreach ($coupon_char as $char_set) {
					for ($i = 0; $i < $char_set['count']; $i++) {
						$temp_array[] = $char_set['char'][rand(0, strlen($char_set['char']) - 1)];
					}
				}
				shuffle($temp_array);
				$couponCode = implode('', $temp_array);
			}
			return $couponCode;
		}
		function arm_generate_code()
		{
			global $wpdb, $ARMember, $arm_slugs;
			$arm_code = $this->arm_generate_coupon_code();
			$old_coupon = $wpdb->get_var("SELECT `arm_coupon_id` FROM `" . $ARMember->tbl_arm_coupons . "` WHERE `arm_coupon_code`='" . $arm_code . "'");
			if ($old_coupon != null) {
				$this->arm_generate_code();
			} else {
				$response = array('arm_coupon_code' => $arm_code);
				echo json_encode($response);
			}
			die();
		}
        function arm_admin_save_coupon_details($coupon_data = array()) {
            global $wpdb, $ARMember, $arm_slugs, $arm_global_settings;
            $op_type = $coupon_data['op_type'];

            $coupon_code = (isset($coupon_data['arm_coupon_code']) && !empty($coupon_data['arm_coupon_code'])) ? $coupon_data['arm_coupon_code'] : '';
            $coupon_discount = (isset($coupon_data['arm_coupon_discount'])) ? $coupon_data['arm_coupon_discount'] : '';
            $arm_coupon_on_each_subscriptions = (isset($coupon_data['arm_coupon_on_each_subscriptions'])) ? $coupon_data['arm_coupon_on_each_subscriptions'] : 0;
            $coupon_discount_type = (isset($coupon_data['arm_discount_type']) && !empty($coupon_data['arm_discount_type'])) ? $coupon_data['arm_discount_type'] : '';
            $coupon_label = (isset($coupon_data['arm_coupon_label']) && !empty($coupon_data['arm_coupon_label'])) ? $coupon_data['arm_coupon_label'] : '';
            $coupon_period_type = (isset($coupon_data['arm_coupon_period_type']) && !empty($coupon_data['arm_coupon_period_type'])) ? $coupon_data['arm_coupon_period_type'] : 'daterange';
            $coupon_start = (isset($coupon_data['arm_coupon_start_date']) && !empty($coupon_data['arm_coupon_start_date'])) ? $coupon_data['arm_coupon_start_date'] : date('Y-m-d');
            $coupon_expire = (isset($coupon_data['arm_coupon_expire_date']) && !empty($coupon_data['arm_coupon_expire_date'])) ? $coupon_data['arm_coupon_expire_date'] : date('Y-m-d');
            $coupon_status = (isset($coupon_data['arm_coupon_status']) && !empty($coupon_data['arm_coupon_status'])) ? $coupon_data['arm_coupon_status'] : 0;
            $coupon_allow_trial = (isset($coupon_data['arm_coupon_allow_trial']) && !empty($coupon_data['arm_coupon_allow_trial'])) ? $coupon_data['arm_coupon_allow_trial'] : 0;
            $coupon_subscription = (isset($coupon_data['arm_subscription_coupons']) && !empty($coupon_data['arm_subscription_coupons'])) ? $coupon_data['arm_subscription_coupons'] : '';
            $coupon_subscription = (!empty($coupon_subscription)) ? @implode(',', $coupon_subscription) : '';
            $coupon_allowed_uses = (!empty($coupon_data['arm_allowed_uses']) && is_numeric($coupon_data['arm_allowed_uses'])) ? $coupon_data['arm_allowed_uses'] : 0;
            $coupon_apply_to = (isset($coupon_data['arm_coupon_apply_to']) && !empty($coupon_data['arm_coupon_apply_to'])) ? $coupon_data['arm_coupon_apply_to'] : '';
            $coupon_start_date = date('Y-m-d H:i:s', strtotime($coupon_start));
            $coupon_expire_date = date('Y-m-d 23:59:59', strtotime($coupon_expire));
            if ($coupon_period_type == 'unlimited') {
                $coupon_start_date = date('Y-m-d H:i:s');
                $coupon_expire_date = date('Y-m-d 23:59:59');
            }

            $c_where = '';
            if ($op_type == 'edit' && !empty($coupon_data['arm_edit_coupon_id']) && $coupon_data['arm_edit_coupon_id'] != 0) {
                $c_where = " AND `arm_coupon_id` != '" . $coupon_data['arm_edit_coupon_id'] . "'";
            }
            $old_coupon = $wpdb->get_var("SELECT `arm_coupon_id` FROM `" . $ARMember->tbl_arm_coupons . "` WHERE `arm_coupon_code`='" . $coupon_code . "' " . $c_where);
            $check_status = 0;
            if ($old_coupon != null) {
                $check_status = 1;
            }

            $coupons_values = array(
                'arm_coupon_code' => $coupon_code,
                'arm_coupon_label' => $coupon_label,
                'arm_coupon_discount' => $coupon_discount,
                'arm_coupon_on_each_subscriptions' => $arm_coupon_on_each_subscriptions,
                'arm_coupon_discount_type' => $coupon_discount_type,
                'arm_coupon_period_type' => $coupon_period_type,
                'arm_coupon_start_date' => $coupon_start_date,
                'arm_coupon_expire_date' => $coupon_expire_date,
                'arm_coupon_subscription' => $coupon_subscription,
                'arm_coupon_allow_trial' => $coupon_allow_trial,
                'arm_coupon_allowed_uses' => $coupon_allowed_uses,
                'arm_coupon_status' => $coupon_status,
                'arm_coupon_added_date' => date('Y-m-d H:i:s')
            );

            if ($op_type == 'add') {
                if ($check_status != 1) {
                    $ins = $wpdb->insert($ARMember->tbl_arm_coupons, $coupons_values);
                    if ($ins) {
                        $message = __('Coupon Added Successfully.', 'ARMember');
                        $status = 'success';
                        $coupon_id = $wpdb->insert_id;
                        $edit_coupon_link = admin_url('admin.php?page=' . $arm_slugs->coupon_management . '&action=edit_coupon&coupon_eid=' . $coupon_id);
                    } else {
                        $message = __('Error Adding Coupons, Please Again Try Again.', 'ARMember');
                        $status = 'failed';
                        $edit_coupon_link = admin_url('admin.php?page=' . $arm_slugs->coupon_management . '&action=add_coupon');
                    }
                } else {
                    $message = __('Could Not Perform The Operation, Because Coupon Code Already Exists.', 'ARMember');
                    $status = 'failed';
                    $edit_coupon_link = admin_url('admin.php?page=' . $arm_slugs->coupon_management . '&action=add_coupon');
                }
            } else {

                $c_id = $coupon_data['arm_edit_coupon_id'];
                if ($check_status != 1) {
                    $where = array('arm_coupon_id' => $c_id);
                    $up = $wpdb->update($ARMember->tbl_arm_coupons, $coupons_values, $where);
                    if ($up) {
                        $message = __('Coupon Updated Successfully.', 'ARMember');
                        $status = 'success';
                        $edit_coupon_link = admin_url('admin.php?page=' . $arm_slugs->coupon_management . '&action=edit_coupon&coupon_eid=' . $c_id);
                    } else {
                        $message = __('Error Updating Coupons, Please Again Try Again.', 'ARMember');
                        $status = 'failed';
                        $edit_coupon_link = admin_url('admin.php?page=' . $arm_slugs->coupon_management . '&action=edit_coupon&coupon_eid=' . $c_id);
                    }
                } else {
                    $message = __('Could Not Perform The Operation, Because Coupon Code Already Exists.', 'ARMember');
                    $status = 'failed';
                    $edit_coupon_link = admin_url('admin.php?page=' . $arm_slugs->coupon_management . '&action=edit_coupon&coupon_eid=' . $c_id);
                }
            }

            $ARMember->arm_set_message($status, __($message, 'ARMember'));
            if (!empty($edit_coupon_link)) {
                wp_redirect($edit_coupon_link);
                exit;
            }
        }
        function arm_op_coupons()
		{
			global $wpdb, $ARMember, $arm_slugs, $arm_global_settings;
			$op_type = $_REQUEST['op_type'];
			$coupon_code = (isset($_POST['arm_coupon_code']) && !empty($_POST['arm_coupon_code'])) ? $_POST['arm_coupon_code'] : '';
			$coupon_discount = (isset($_POST['arm_coupon_discount']) && !empty($_POST['arm_coupon_discount'])) ? $_POST['arm_coupon_discount'] : '';				
			$coupon_discount_type = (isset($_POST['arm_discount_type']) && !empty($_POST['arm_discount_type'])) ? $_POST['arm_discount_type'] : '';
			$coupon_period_type = (isset($_POST['arm_coupon_period_type']) && !empty($_POST['arm_coupon_period_type'])) ? $_POST['arm_coupon_period_type'] : 'daterange';								
            $coupon_start = (isset($_POST['arm_coupon_start_date']) && !empty($_POST['arm_coupon_start_date'])) ? $_POST['arm_coupon_start_date'] : date('Y-m-d');
			$coupon_expire = (isset($_POST['arm_coupon_expire_date']) && !empty($_POST['arm_coupon_expire_date'])) ? $_POST['arm_coupon_expire_date'] : date('Y-m-d');			
			$coupon_status = (isset($_POST['arm_coupon_status']) && !empty($_POST['arm_coupon_status'])) ? $_POST['arm_coupon_status'] : 0;
			$coupon_allow_trial = (isset($_POST['arm_coupon_allow_trial']) && !empty($_POST['arm_coupon_allow_trial'])) ? $_POST['arm_coupon_allow_trial'] : 0;
			$coupon_subscription = (isset($_POST['arm_subscription_coupons']) && !empty($_POST['arm_subscription_coupons'])) ? $_POST['arm_subscription_coupons'] : '';
			$coupon_subscription = (!empty($coupon_subscription)) ? @implode(',', $coupon_subscription) : '';
			$coupon_allowed_uses = (!empty($_POST['arm_allowed_uses']) && is_numeric($_POST['arm_allowed_uses'])) ? $_POST['arm_allowed_uses'] : 0;
			$coupon_apply_to = (isset($_POST['arm_coupon_apply_to']) && !empty($_POST['arm_coupon_apply_to'])) ? $_POST['arm_coupon_apply_to'] : '';
			$coupon_start_date = date('Y-m-d H:i:s', strtotime($coupon_start));
			$coupon_expire_date = date('Y-m-d 23:59:59', strtotime($coupon_expire));
			if ($coupon_period_type == 'unlimited') {
				$coupon_start_date = date('Y-m-d H:i:s');
				$coupon_expire_date = date('Y-m-d 23:59:59');
			}
			
			$c_where = '';
			if ($op_type == 'edit' && !empty($_REQUEST['arm_edit_coupon_id']) && $_REQUEST['arm_edit_coupon_id'] != 0) {
				$c_where = " AND `arm_coupon_id` != '" . $_REQUEST['arm_edit_coupon_id'] . "'";
			}
			$old_coupon = $wpdb->get_var("SELECT `arm_coupon_id` FROM `" . $ARMember->tbl_arm_coupons . "` WHERE `arm_coupon_code`='" . $coupon_code . "' ". $c_where);
			$check_status = 0;
			if ($old_coupon != null) {
				$check_status = 1;
			}
			
			$coupons_values = array(
				'arm_coupon_code' => $coupon_code,
				'arm_coupon_discount' => $coupon_discount,
				'arm_coupon_discount_type' => $coupon_discount_type,
                'arm_coupon_period_type' => $coupon_period_type,
				'arm_coupon_start_date' => $coupon_start_date,
				'arm_coupon_expire_date' => $coupon_expire_date,
				'arm_coupon_subscription' => $coupon_subscription,
				'arm_coupon_allow_trial' => $coupon_allow_trial,
				'arm_coupon_allowed_uses' => $coupon_allowed_uses,
				'arm_coupon_status' => $coupon_status,
				'arm_coupon_added_date' => date('Y-m-d H:i:s')
			);
			
			if ($op_type == 'add')
			{
				if ($check_status != 1) {
					$ins = $wpdb->insert($ARMember->tbl_arm_coupons, $coupons_values);
					if ($ins) {
						$message = __('Coupon Added Successfully.', 'ARMember');
						$status = 'success';
						$coupon_id = $wpdb->insert_id;
						$edit_coupon_link = admin_url('admin.php?page=' . $arm_slugs->coupon_management . '&action=edit_coupon&coupon_eid=' . $coupon_id);                                       
					} else {
						$message = __('Error Adding Coupons, Please Again Try Again.', 'ARMember');
						$status = 'failed';
						$edit_coupon_link = '';
					}				
				} else {
					$message = __('Could Not Perform The Operation, Because Coupon Code Already Exists.', 'ARMember');
					$status = 'failed';
					$edit_coupon_link = '';
				}
			} else {
				$c_id = $_REQUEST['arm_edit_coupon_id'];
				if ($check_status != 1) {					
					$where = array('arm_coupon_id' => $c_id);
					$up = $wpdb->update($ARMember->tbl_arm_coupons, $coupons_values, $where);
					if ($up) {
						$message = __('Coupon Updated Successfully.', 'ARMember');
						$status = 'success';
						$edit_coupon_link = admin_url('admin.php?page=' . $arm_slugs->coupon_management . '&action=edit_coupon&coupon_eid=' . $c_id);
					} else {
						$message = __('Error Updating Coupons, Please Again Try Again.', 'ARMember');
						$status = 'failed';
						$edit_coupon_link = admin_url('admin.php?page=' . $arm_slugs->coupon_management . '&action=edit_coupon&coupon_eid=' . $c_id);
					}
				} else {
					$message = __('Could Not Perform The Operation, Because Coupon Code Already Exists.', 'ARMember');
					$status = 'failed';
					$edit_coupon_link = admin_url('admin.php?page=' . $arm_slugs->coupon_management . '&action=edit_coupon&coupon_eid=' . $c_id);
				}	
			}
			$response = array('status' => $status, 'message' => $message, 'url' => $edit_coupon_link);
			echo json_encode($response);
			die();
		}
		function arm_update_coupons_status()
		{
			global $wpdb, $ARMember, $arm_slugs, $arm_global_settings;
			$response = array('type'=>'error', 'msg'=>__('Sorry, Something went wrong. Please try again.', 'ARMember'));
			if (!empty($_POST['arm_coupon_id']) && $_POST['arm_coupon_id'] != 0)
			{
				$coupon_id = $_POST['arm_coupon_id'];
				$arm_coupon_status = (!empty($_POST['arm_coupon_status'])) ? $_POST['arm_coupon_status'] : 0;
				$coupons_values = array(
					'arm_coupon_status' => $arm_coupon_status,
				);
				$update_temp = $wpdb->update($ARMember->tbl_arm_coupons, $coupons_values, array('arm_coupon_id' => $coupon_id));
				$response = array('type'=>'success', 'msg'=>__('Coupon Updated Successfully.', 'ARMember'));
			}
			echo json_encode($response);
			die();
		}
		function arm_get_coupon($coupon_code = '')
		{
			global $wpdb, $ARMember, $arm_slugs;
			$coupon_detail = FALSE;
			if (!empty($coupon_code)) {
				$coupon_detail = $wpdb->get_row("SELECT * FROM `" . $ARMember->tbl_arm_coupons . "` WHERE `arm_coupon_code` LIKE '$coupon_code'", ARRAY_A);
				if (empty($coupon_detail)) {
					$coupon_detail = FALSE;
				} else {
                    $couponCodeDB = $coupon_detail['arm_coupon_code'];
                    if( $couponCodeDB != $coupon_code  ){
                        $coupon_detail = FALSE;
                    }
                }
			}
			return $coupon_detail;
		}
		function arm_update_coupon_used_count($coupon_code = '')
		{
			global $wpdb, $ARMember, $arm_slugs;
			if (!empty($coupon_code)) {
				$used_coupons = $wpdb->get_results("UPDATE `" . $ARMember->tbl_arm_coupons . "` SET `arm_coupon_used` = `arm_coupon_used`+1 WHERE `arm_coupon_code` LIKE '$coupon_code'");
				return $used_coupons;
			} else {
				return FALSE;
			}
		}
		function arm_get_coupon_amount($coupon_code, $payment_amount = 0, $plan_id = 0)
		{
			global $wpdb, $ARMember, $arm_slugs;
			$coupon_amount = 0;
			if ($this->isCouponFeature) {
				$coupon_detail = $this->arm_get_coupon($coupon_code);
				if ($coupon_detail !== FALSE) {
					if ($coupon_detail['arm_coupon_discount'] != 0) {
						$plans = $coupon_detail['arm_coupon_subscription'];
						$allow_plan_ids = explode(',', $plans);
						$user_count = $this->arm_get_used_coupon_count($coupon_code);
						$allowed_uses = $coupon_detail['arm_coupon_allowed_uses'];
						if ($coupon_detail['arm_coupon_status'] != '1') {
							$coupon_amount = 0;
						} elseif ($allowed_uses != 0 && $allowed_uses <= $user_count) {
							$coupon_amount = 0;
						} elseif ($coupon_detail['arm_coupon_period_type'] == 'daterange' && time() < strtotime($coupon_detail['arm_coupon_start_date'])) {
							$coupon_amount = 0;
						} elseif ($coupon_detail['arm_coupon_period_type'] == 'daterange' && time() > strtotime($coupon_detail['arm_coupon_expire_date'])) {
							$coupon_amount = 0;
						} elseif (!empty($plans) && !in_array($plan_id, $allow_plan_ids)) {
							$coupon_amount = 0;
						} else {
							$coupon_amount = $coupon_detail['arm_coupon_discount'];
							if ($coupon_detail['arm_coupon_discount_type'] == 'percentage') {
								$coupon_amount = ($payment_amount * $coupon_amount) / 100;
							}
							$coupon_amount = number_format((float) $coupon_amount, 2);
						}
					}
				}
			}
			return $coupon_amount;
		}
		function arm_get_used_coupon_count($coupon_code = '')
		{
			global $wpdb, $ARMember, $arm_slugs;
			$used_count = 0;
			$coupon_used = $wpdb->get_var("SELECT `arm_coupon_used` FROM `" . $ARMember->tbl_arm_coupons . "` WHERE `arm_coupon_code` LIKE '" . $coupon_code . "'");
			if ($coupon_used != null) {
				$used_count = $coupon_used;
			}
			return $used_count;
		}
		function arm_get_all_coupons()
		{
			global $wpdb, $ARMember, $arm_slugs;
			return $row = $wpdb->get_results("SELECT * FROM `" . $ARMember->tbl_arm_coupons . "` ORDER BY `arm_coupon_id` DESC");
		}
		function arm_total_coupons()
		{
			global $wpdb, $ARMember;
			$coupon_count = $wpdb->get_var("SELECT COUNT(`arm_coupon_id`) FROM `" . $ARMember->tbl_arm_coupons . "`");
			return $coupon_count;
		}
		function arm_delete_single_coupon()
		{
			global $wp, $wpdb, $current_user, $arm_errors, $ARMember, $arm_members_class, $arm_member_forms, $arm_global_settings;
			$action = $_POST['act'];
			$id = $_POST['id'];
			if( $action == 'delete' )
			{
				if (empty($id)) {
					$errors[] = __('Invalid action.', 'ARMember');
				} else {
					if (!current_user_can('arm_manage_coupons')) {
						$errors[] = __('Sorry, You do not have permission to perform this action.', 'ARMember');
					} else {
						$res_var = $wpdb->delete($ARMember->tbl_arm_coupons, array('arm_coupon_id' => $id));
						if ($res_var) {
							$message = __('Coupon has been deleted successfully.', 'ARMember');
						}
					}
				}
			}
			$return_array = $arm_global_settings->handle_return_messages(@$errors, @$message);
			echo json_encode($return_array);
			exit;
		}
		function arm_delete_bulk_coupons()
		{
			if (!isset($_POST)) {
				return;
			}
			global $wp, $wpdb, $current_user, $arm_errors, $ARMember, $arm_members_class, $arm_member_forms, $arm_global_settings;
			$bulkaction = $arm_global_settings->get_param('action1');
			if ($bulkaction == -1) {
				$bulkaction = $arm_global_settings->get_param('action2');
			}
			$ids = $arm_global_settings->get_param('item-action', '');
			if (empty($ids))
			{
				$errors[] = __('Please select one or more records.', 'ARMember');
			} else {
				if (!current_user_can('arm_manage_coupons')) {
					$errors[] = __('Sorry, You do not have permission to perform this action.', 'ARMember');
				} else {
					if (!is_array($ids)) {
						$ids = explode(',', $ids);
					}
					if (is_array($ids)) {
						if ($bulkaction == 'delete_coupon') {
							foreach ($ids as $coupon_id) {
								$res_var = $wpdb->delete($ARMember->tbl_arm_coupons, array('arm_coupon_id' => $coupon_id));
							}
							if ($res_var) {
								$message = __('Coupon(s) has been deleted successfully.', 'ARMember');
							}
						} else {
							$errors[] = __('Please select valid action.', 'ARMember');
						}
					}
				}
			}
			$return_array = $arm_global_settings->handle_return_messages(@$errors, @$message);
			echo json_encode($return_array);
			exit;
		}

        function arm_coupon_apply_to_subscription($user_ID, $log_detail,$pgateway,$userPlanData)
        {
            global $wp, $wpdb, $ARMember, $arm_manage_coupons;

            $log_id = isset($log_detail->arm_log_id) ? $log_detail->arm_log_id : $log_detail;
                
            if(!empty($log_id))
            {
                if ($pgateway == 'bank_transfer') {
                    
                    $armLogTable = $ARMember->tbl_arm_bank_transfer_log;
                } else {
                    $armLogTable = $ARMember->tbl_arm_payment_log;
                }
                
                $arm_current_plan_detail = !empty($userPlanData['arm_current_plan_detail']) ? $userPlanData['arm_current_plan_detail'] : '';
                if(!empty($arm_current_plan_detail))
                {
                    if(MEMBERSHIP_DEBUG_LOG == true) {
                        $ARMember->arm_write_response("ARMember COUPON LOG 1 : arm_coupon_apply_to_subscription plan detail : ".maybe_serialize($arm_current_plan_detail));
                    }
                    $arm_subscription_plan_type = isset($arm_current_plan_detail['arm_subscription_plan_type']) ? $arm_current_plan_detail['arm_subscription_plan_type'] : '';
                    $arm_subscription_plan_id = isset($arm_current_plan_detail['arm_subscription_plan_id']) ? $arm_current_plan_detail['arm_subscription_plan_id'] : '';
                    $arm_subscription_plan_options = isset($arm_current_plan_detail['arm_subscription_plan_options']) ? maybe_unserialize($arm_current_plan_detail['arm_subscription_plan_options']) : '';
                    if($arm_subscription_plan_type=='recurring')
                    {
                        if(MEMBERSHIP_DEBUG_LOG == true) {
                            $ARMember->arm_write_response("ARMember COUPON LOG 2 : arm_coupon_apply_to_subscription inside recurring plan");
                        }
                        $user_subscription_payment_cycle = get_user_meta($user_ID, 'payment_cycle_'.$arm_subscription_plan_id, true);
                        $userPlanData = get_user_meta($user_ID, 'arm_user_plan_'.$arm_subscription_plan_id, true);
                        
                        if($user_subscription_payment_cycle=='') {
                            $user_subscription_payment_cycle = 0;
                        }
                        $arm_subscription_plan_amount = $arm_current_plan_detail['arm_subscription_plan_amount'];
                        if(isset($arm_current_plan_detail['arm_subscription_plan_amount_original']) && !empty($arm_current_plan_detail['arm_subscription_plan_amount_original']) )
                        {
                            $arm_subscription_plan_amount = $arm_current_plan_detail['arm_subscription_plan_amount_original'];
                        }

                        $log_details = $wpdb->get_row("SELECT * FROM `{$armLogTable}` WHERE `arm_log_id`='{$log_id}'");
                        if(!empty($log_details))
                        {
                            if(MEMBERSHIP_DEBUG_LOG == true) {
                                $ARMember->arm_write_response("ARMember COUPON LOG 3 : arm_coupon_apply_to_subscription log details : ". maybe_serialize($log_details));
                            }
                            $arm_coupon_discount = $log_details->arm_coupon_discount;
                            $arm_coupon_discount_type = $log_details->arm_coupon_discount_type;
                            $arm_coupon_code = $log_details->arm_coupon_code;
                            $arm_coupon_on_each_subscriptions = $log_details->arm_coupon_on_each_subscriptions;
                            if(!empty($arm_coupon_on_each_subscriptions))
                            {
                                if(MEMBERSHIP_DEBUG_LOG == true) {
                                    $ARMember->arm_write_response("ARMember COUPON LOG 4 : arm_coupon_apply_to_subscription each recurring true");
                                }
                                if(!empty($arm_coupon_code))
                                {
                                    $arm_user_payment_cycles = $arm_subscription_plan_options['payment_cycles'];
                                    if(MEMBERSHIP_DEBUG_LOG == true) {
                                        $ARMember->arm_write_response("ARMember COUPON LOG 5 : arm_coupon_apply_to_subscription arm_user_payment_cycles".maybe_serialize($arm_user_payment_cycles));
                                    }
                                    if(count($arm_user_payment_cycles)>0)
                                    {
                                        foreach ($arm_user_payment_cycles as $arm_user_payment_cycle_key => $arm_user_payment_cycle_value) {

                                            if(!isset($arm_user_payment_cycle_value['cycle_amount_original']))
                                            {
                                                $arm_user_payment_cycle_amount = $arm_user_payment_cycle_value['cycle_amount'];
                                            }
                                            else {
                                                $arm_user_payment_cycle_amount = $arm_user_payment_cycle_value['cycle_amount_original'];
                                            }

                                            $arm_couponApply_plan = $arm_manage_coupons->arm_apply_coupon_code($arm_coupon_code, $arm_subscription_plan_id, 0, $arm_user_payment_cycle_key);
                                            $arm_coupon_discount_type = isset($arm_couponApply_plan['discount_type']) ? $arm_couponApply_plan['discount_type'] : '';
                                            $arm_coupon_discount = isset($arm_couponApply_plan['discount']) ? $arm_couponApply_plan['discount'] : 0;
                                            if($arm_coupon_discount_type=='percentage')
                                            {
                                                $arm_subscription_plan_amount_couponed = ($arm_user_payment_cycle_amount * $arm_coupon_discount) / 100;
                                                $arm_subscription_plan_amount_couponed = $arm_user_payment_cycle_amount - $arm_subscription_plan_amount_couponed;
                                            }
                                            else {
                                                $arm_subscription_plan_amount_couponed = $arm_user_payment_cycle_amount-$arm_coupon_discount;
                                            }

                                            if($arm_subscription_plan_amount_couponed<0)
                                            {
                                                $arm_subscription_plan_amount_couponed = 0;
                                            }

                                            if(MEMBERSHIP_DEBUG_LOG == true) {
                                                $ARMember->arm_write_response("ARMember COUPON LOG 5.1 : arm_subscription_plan_amount_couponed=".maybe_serialize($arm_subscription_plan_amount_couponed));
                                            }

                                            if($user_subscription_payment_cycle==$arm_user_payment_cycle_key)
                                            {
                                                if(!isset($userPlanData['arm_current_plan_detail']['arm_subscription_plan_amount_original']))
                                                {
                                                    $userPlanData['arm_current_plan_detail']['arm_subscription_plan_amount_original'] = $arm_user_payment_cycle_amount;
						    $user_activity = $wpdb->get_row("SELECT arm_activity_id, arm_content FROM `" . $ARMember->tbl_arm_activity . "` WHERE `arm_type`='membership' AND `arm_user_id`='$user_ID' AND `arm_action` = 'new_subscription' AND `arm_item_id`='$arm_subscription_plan_id' ORDER BY `arm_activity_id` DESC LIMIT 1", ARRAY_A);

	                                            if(!empty($user_activity)) {

	                                                $user_activity_content = maybe_unserialize( $user_activity['arm_content'] );

	                                                if(isset($user_activity_content['plan_amount'])) {
	                                                    $user_activity_content['plan_amount'] = $arm_subscription_plan_amount_couponed;
	                                                }

	                                                if (isset($user_activity_content['plan_detail']['arm_subscription_plan_amount'])) {
	                                                    $user_activity_content['plan_detail']['arm_subscription_plan_amount'] = $arm_subscription_plan_amount_couponed;
	                                                }

	                                                if (isset($user_activity_content['plan_detail']['arm_subscription_plan_options'])) {

	                                                    $arm_subscription_plan_options = maybe_unserialize($user_activity_content['plan_detail']['arm_subscription_plan_options']);

	                                                    if(isset($arm_subscription_plan_options['payment_cycles'][0]['cycle_amount'])) {

	                                                        $arm_subscription_plan_options['payment_cycles'][0]['cycle_amount'] = $arm_subscription_plan_amount_couponed;

	                                                        $user_activity_content['plan_detail']['arm_subscription_plan_options'] = maybe_serialize($arm_subscription_plan_options);
	                                                    }
	                                                }

	                                                if(!empty($user_activity_content['plan_text'])) {
	                                                    $plan_text = $user_activity_content['plan_text'];

	                                                    $first_part_ind = strpos($plan_text, 'arm_plan_amount_span');

	                                                    $second_part_ind = strrpos($plan_text, '</span>');

	                                                    if($first_part_ind !== false && $second_part_ind !== false) {

	                                                        $first_part = substr($plan_text, 0, ($first_part_ind + 22));

	                                                        $second_part = substr($plan_text, $second_part_ind);

	                                                        $user_activity_content['plan_text'] = $first_part . number_format((float)$arm_subscription_plan_amount_couponed, 2) . $second_part;
	                                                    }
	                                                }

	                                                $user_activity_content = maybe_serialize($user_activity_content);

	                                                $user_activity_id = $user_activity['arm_activity_id'];

	                                                if(!empty($user_activity_id)) {
	                                                    $user_activity_update = $wpdb->update($ARMember->tbl_arm_activity, array('arm_content' => $user_activity_content), array('arm_activity_id' => $user_activity_id));
	                                                }
	                                            }
                                                }
                                                $userPlanData['arm_current_plan_detail']['arm_subscription_plan_amount'] = $arm_subscription_plan_amount_couponed;
                                            }
                                            
                                            if(!isset($arm_subscription_plan_options['payment_cycles'][$arm_user_payment_cycle_key]['cycle_amount_original']))
                                            {
                                                $arm_subscription_plan_options['payment_cycles'][$arm_user_payment_cycle_key]['cycle_amount_original'] =$arm_subscription_plan_options['payment_cycles'][$arm_user_payment_cycle_key]['cycle_amount'];
                                            }
                                            $arm_subscription_plan_options['payment_cycles'][$arm_user_payment_cycle_key]['cycle_amount'] = $arm_subscription_plan_amount_couponed;
                                        }

                                        $userPlanData['arm_current_plan_detail']['arm_subscription_plan_options'] = maybe_serialize($arm_subscription_plan_options);

                                        if(MEMBERSHIP_DEBUG_LOG == true) {
                                            $ARMember->arm_write_response("ARMember COUPON LOG 6 : arm_coupon_apply_to_subscription userPlanData".maybe_serialize($userPlanData));
                                        }

                                        update_user_meta($user_ID, 'arm_user_plan_'.$arm_subscription_plan_id, $userPlanData);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
	}
}
global $arm_manage_coupons;
$arm_manage_coupons = new ARM_manage_coupons();