/**
 * Magic Members get extend buttons/packs
 * display the current pack for extend if the pack is set as renewable/ active on extend page
 * show all packs active on extend page otherwise
 *
 * @package MagicMembers
 * @since 2.0
 * @param none
 * @return formatted html
 */
function mgm_get_extend_button()
{
    global $wpdb;
    // current user
    $user = wp_get_current_user();
    // validate user
    if (!$user->ID) {
        // query string
        $user = mgm_get_user_from_querystring();
    }
    // validate
    if (!$user->ID) {
        return __('No such user', 'mgm');
    }
    // set
    $username = $user->user_login;
    // get member
    $member = mgm_get_member($user->ID);
    //this is a fix for issue#: 589, see the notes for details:
    //This is to read saved coupons as array in order to fix the fatal error on some servers.
    //This will change the object on each users profile view.
    //Also this will avoid using patch for batch update,
    $arr_coupon = array('upgrade', 'extend');
    $oldcoupon_found = 0;
    foreach ($arr_coupon as $cpn_type) {
        if (isset($member->{$cpn_type}['coupon']) && is_object($member->{$cpn_type}['coupon'])) {
            $member->{$cpn_type}['coupon'] = (array) $member->{$cpn_type}['coupon'];
            $oldcoupon_found++;
        }
    }
    if ($oldcoupon_found) {
        $member->save();
    }
    // other objects
    $system_obj = mgm_get_class('system');
    $packs_obj = mgm_get_class('subscription_packs');
    // selected pack
    $pack_id = (int) strip_tags($_GET['pack_id']);
    // action
    $action = isset($_GET['action']) ? strip_tags($_GET['action']) : 'extend';
    // extend
    // query_arg
    $form_action = mgm_get_custom_url('transactions', false, array('action' => $action, 'pack_id' => $pack_id, 'username' => $username));
    // if extending multiple purchase subscriptions
    if (isset($_GET['multiple_purchase'])) {
        $form_action = add_query_arg(array('multiple_purchase' => strip_tags($_GET['multiple_purchase'])), $form_action);
    }
    //$cancel_url = mgm_get_custom_url('membership_details');
    //issue 1009
    if (isset($system_obj->setting['membership_details_url'])) {
        $membership_details_url = $system_obj->setting['membership_details_url'];
    } else {
        $membership_details_url = get_admin_url() . 'profile.php?page=mgm/profile';
    }
    // cancel
    $cancel_url = $membership_details_url;
    // active modules
    $a_payment_modules = $system_obj->get_active_modules('payment');
    // active packs
    $active_packs = array();
    // init html
    $html = $error = '';
    // pack id passed in get, coming from profile membership details
    if ($pack_id = (int) strip_tags($_GET['pack_id'])) {
        // get selected pack
        $selected_pack = $packs_obj->get_pack($pack_id);
        // validate
        if ($selected_pack !== false) {
            // check if extend allowed on the current pack of subscriber/user
            if (!mgm_pack_extend_allowed($selected_pack)) {
                // error
                $error = __('Renewal of the current subscription is not allowed.', 'mgm');
                // get packs
                $active_packs = $packs_obj->get_packs('extend');
                // check
                if (count($active_packs) > 0) {
                    // error
                    $error = '';
                    // reset error
                    // html head
                    $html = sprintf('<p class="message register">%s</p>', __('Choose a subscription package', 'mgm'));
                }
            } else {
                // html
                $html = sprintf('<p class="message register">%s</p>', __('Extend current subscription', 'mgm'));
                // active packs
                $active_packs[] = $selected_pack;
            }
        }
    }
    // post form---------------------------------------------------------------------
    if ($_POST && isset($_POST['submit']) && isset($_POST['subs_opt'])) {
        //mgm_pr($_POST);die;
        // process post
        // get pack data
        $selected_pack = mgm_decode_package($_POST['subs_opt']);
        // check selected pack
        $valid = false;
        // loop packs
        foreach ($active_packs as $pack) {
            // check
            //check pack id as well: issue#: 580
            if ($pack['cost'] == $selected_pack['cost'] && $pack['duration'] == $selected_pack['duration'] && $pack['duration_type'] == $selected_pack['duration_type'] && $pack['membership_type'] == $selected_pack['membership_type'] && $pack['id'] == $selected_pack['pack_id']) {
                // valid
                $valid = true;
                break;
            }
        }
        // error
        if (!$valid) {
            wp_die(__('Invalid data. Cheatin!', 'mgm'));
        }
        //update description if not set
        if (!isset($selected_pack['description'])) {
            $selected_pack['description'] = $pack['description'];
        }
        //update num_cycles if not set
        if (!isset($selected_pack['num_cycles'])) {
            //Note the above break in for loop:
            $selected_pack['num_cycles'] = $pack['num_cycles'];
        }
        //issue#: 658
        if (isset($pack['role'])) {
            $selected_pack['role'] = $pack['role'];
        }
        //applicable modules
        $selected_pack['modules'] = $pack['modules'];
        $selected_pack['product'] = $pack['product'];
        if ($pack['trial_on']) {
            $selected_pack['trial_on'] = $pack['trial_on'];
            $selected_pack['trial_duration'] = $pack['trial_duration'];
            $selected_pack['trial_duration_type'] = $pack['trial_duration_type'];
            $selected_pack['trial_cost'] = $pack['trial_cost'];
            $selected_pack['trial_num_cycles'] = $pack['trial_num_cycles'];
        }
        // save member data including coupon etc, MUST save after all validation passed, we dont want any
        // unwanted value in member object unless its a valid upgrdae
        $member = mgm_save_partial_fields(array('on_extend' => true), 'mgm_extend_field', $selected_pack['cost'], true, 'extend');
        // is using a coupon ? reset prices	- issue #1226
        if (isset($_POST['mgm_extend_field']) && !empty($_POST['mgm_extend_field']['coupon'])) {
            //issue #1250 - Coupon validation
            if (!empty($_POST['form_action'])) {
                // check if its a valid coupon
                if (!($coupon = mgm_get_coupon_data($_POST['mgm_extend_field']['coupon']))) {
                    //redirect back to the form
                    $q_arg = array('error_field' => 'Coupon', 'error_type' => 'invalid', 'error_field_value' => $_POST['mgm_extend_field']['coupon']);
                    $redirect = add_query_arg($q_arg, $_POST['form_action']);
                    mgm_redirect($redirect);
                    exit;
                } else {
                    // get subs
                    if ($subs_pack = mgm_decode_package(mgm_post_var('subs_opt'))) {
                        // values
                        $coupon_values = mgm_get_coupon_values(NULL, $coupon['value'], true);
                        // check
                        if (isset($coupon_values['new_membership_type']) && $coupon_values['new_membership_type'] != $subs_pack['membership_type']) {
                            $new_membership_type = mgm_get_membership_type_name($coupon_values['new_membership_type']);
                            $q_arg = array('error_field' => 'Coupon', 'error_type' => 'invalid', 'membership_type' => $coupon_values['new_membership_type'], 'error_field_value' => $_POST['mgm_extend_field']['coupon']);
                            $redirect = add_query_arg($q_arg, $_POST['form_action']);
                            mgm_redirect($redirect);
                            exit;
                        }
                    }
                }
            }
            if ($coupon) {
                mgm_get_extend_coupon_pack($member, $selected_pack);
            }
        }
        // Eg: $_POST['mgm_payment_gateways'] = mgm_paypal
        $cf_payment_gateways = isset($_POST['mgm_payment_gateways']) && !empty($_POST['mgm_payment_gateways']) ? $_POST['mgm_payment_gateways'] : null;
        // bypass step2 if payment gateway is submitted: issue #: 469
        if (!is_null($cf_payment_gateways)) {
            // cost
            if ((double) $selected_pack['cost'] > 0) {
                //get an object of the payment gateway:
                $mod_obj = mgm_get_module($cf_payment_gateways, 'payment');
                // tran options
                $tran_options = array('user_id' => $user->ID, 'subscription_option' => 'extend');
                // is register & purchase
                if (isset($_POST['post_id'])) {
                    $tran_options['post_id'] = (int) $_POST['post_id'];
                }
                // is register & purchase postpack
                if (isset($_POST['postpack_post_id']) && isset($_POST['postpack_id'])) {
                    $tran_options['postpack_post_id'] = (int) $_POST['postpack_post_id'];
                    $tran_options['postpack_id'] = (int) $_POST['postpack_id'];
                }
                // create transaction
                // $tran_id = $mod_obj->_create_transaction($selected_pack, $tran_options);
                $tran_id = mgm_add_transaction($selected_pack, $tran_options);
                //bypass directly to process return if manual payment:
                if ($cf_payment_gateways == 'mgm_manualpay') {
                    // set
                    $_POST['custom'] = $tran_id;
                    // direct call to module return function:
                    $mod_obj->process_return();
                    // exit
                    exit;
                }
                // encode id:
                $tran_id = mgm_encode_id($tran_id);
                $redirect = $mod_obj->_get_endpoint('html_redirect', true);
                $redirect = add_query_arg(array('tran_id' => $tran_id), $redirect);
                // redirect
                mgm_redirect($redirect);
                // this goes to subscribe, mgm_functions.php/mgm_get_subscription_buttons
                // exit
                exit;
            }
        }
        $html = '<div>';
        // free package
        if (($selected_pack['cost'] == 0 || $selected_pack['membership_type'] == 'free') && in_array('mgm_free', $a_payment_modules) && mgm_get_module('mgm_free')->enabled == 'Y') {
            // html
            $html .= sprintf('<div>%s - %s</div>', __('Create a free account ', 'mgm'), ucwords($selected_pack['membership_type']));
            // module
            $module = 'mgm_free';
            // payments url
            $payments_url = mgm_get_custom_url('transactions');
            // if tril module selected and cost is 0 and free moduleis not active
            if ($selected_pack['membership_type'] == 'trial') {
                // check
                if (in_array('mgm_trial', $a_payment_modules)) {
                    // module
                    $module = 'mgm_trial';
                }
            }
            $arr_custom = array($user->ID, $selected_pack['duration'], $selected_pack['duration_type'], $pack_id);
            // if multiple purchase
            if (isset($_GET['multiple_purchase']) && $_GET['multiple_purchase'] == 'Y') {
                $arr_custom['is_another_membership_purchase'] = 'Y';
            }
            // query_args
            $query_args = array('method' => 'payment_return', 'module' => $module, 'custom' => implode('_', $arr_custom));
            // redirector
            if (isset($_REQUEST['redirector'])) {
                // set
                $query_args['redirector'] = $_REQUEST['redirector'];
            }
            // redirect to module to mark the payment as complete
            $redirect = add_query_arg($query_args, $payments_url);
            // redirect
            if (!headers_sent()) {
                @header('location: ' . $redirect);
            } else {
                // js redirect
                $html .= sprintf('<script type="text/javascript">window.location = "%s";</script><div>%s</div>', $redirect, $packs_obj->get_pack_desc($pack));
            }
        } else {
            // paid package, generate payment buttons
            // set html
            $html .= sprintf('<div class="mgm_get_subs_btn">%s</div>', $packs_obj->get_pack_desc($selected_pack));
            // coupon - issue #1226
            if (isset($member->extend['coupon']['id']) && isset($_POST['mgm_extend_field']) && !empty($_POST['mgm_extend_field']['coupon']) && mgm_get_coupon_data($_POST['mgm_extend_field']['coupon'])) {
                // set html
                $html .= sprintf('<div class="mgm_get_subs_btn">%s</div>', sprintf(__('Using Coupon "%s" - %s', 'mgm'), $member->extend['coupon']['name'], $member->extend['coupon']['description']));
            }
            // set html
            $html .= sprintf('<div class="mgm_get_subs_btn" >%s</div>', __('Please Select from Available Payment Gateways', 'mgm'));
        }
        // init
        $payment_modules = array();
        // active
        if (count($a_payment_modules) > 0) {
            // loop
            foreach ($a_payment_modules as $payment_module) {
                // not trial
                if (in_array($payment_module, array('mgm_free', 'mgm_trial'))) {
                    continue;
                }
                // consider only the modules assigned to pack
                if (isset($selected_pack['modules']) && !in_array($payment_module, (array) $selected_pack['modules'])) {
                    continue;
                }
                // store
                $payment_modules[] = $payment_module;
            }
        }
        // loop payment module if not free
        if (count($payment_modules) && $selected_pack['cost']) {
            // transaction
            $tran_id = false;
            // loop
            foreach ($payment_modules as $module) {
                // module
                $mod_obj = mgm_get_module($module, 'payment');
                // create transaction
                if (!$tran_id) {
                    // args
                    $args = array('user_id' => $user->ID, 'subscription_option' => 'extend');
                    // if extending multiple purchase subscription
                    if (isset($_GET['multiple_purchase']) && $_GET['multiple_purchase'] == 'Y') {
                        $args['is_another_membership_purchase'] = true;
                    }
                    // tran id
                    // $tran_id = $mod_obj->_create_transaction($selected_pack, $args);
                    $tran_id = mgm_add_transaction($selected_pack, $args);
                }
                // set html
                $html .= sprintf('<div class="mgm_get_subs_btn" >%s</div>', $mod_obj->get_button_subscribe(array('pack' => $selected_pack, 'tran_id' => $tran_id)));
            }
        } else {
            // no module error
            if ($selected_pack['cost']) {
                // set html
                $html .= sprintf('<div class="mgm_get_subs_btn" >%s</div>', __('Error, no payment gateways active on extend page, notify administrator.', 'mgm'));
            }
        }
        // html
        $html .= '</div>';
        // end post form
    } else {
        // generate form ----------------------------------------------------------------
        // check error
        if ($error) {
            // html
            $html .= $error;
        } else {
            // generate
            // extend packages
            $extend_packages = '';
            // pack to modules
            $pack_modules = array();
            // loop
            foreach ($active_packs as $pack) {
                // default
                $checked = '';
                // checked
                if ($pack['id'] == $pack_id) {
                    $checked = ' checked="checked"';
                } elseif ((int) $pack['default'] == 1) {
                    $checked = ' checked="checked"';
                }
                // duration
                if ($pack['duration'] == 1) {
                    $dur_str = rtrim($duration_str[$pack['duration_type']], 's');
                } else {
                    $dur_str = $duration_str[$pack['duration_type']];
                }
                // encode pack
                $subs_opt_enc = mgm_encode_package($pack);
                // set
                $pack_modules[$subs_opt_enc] = $pack['modules'];
                // css
                $css_group = mgm_get_css_group();
                //issue #867
                if ($css_group != 'none') {
                    //expand this if needed
                    $css_link_format = '<link rel="stylesheet" href="%s" type="text/css" media="all" />';
                    $css_file = MGM_ASSETS_URL . 'css/' . $css_group . '/mgm.form.fields.css';
                    $extend_packages .= sprintf($css_link_format, $css_file);
                }
                // free
                if (($pack['cost'] == 0 || strtolower($pack['membership_type']) == 'free') && in_array('mgm_free', $a_payment_modules) && mgm_get_module('mgm_free')->enabled == 'Y') {
                    // input
                    $input = sprintf('<input type="radio" %s class="mgm_subs_radio" name="subs_opt" id="subs_opt_%d" value="%s" rel="mgm_subscription_options"/>', $checked, $pack['id'], $subs_opt_enc);
                    // html
                    $extend_packages .= '  
						<div class="mgm_subs_wrapper ' . $pack['membership_type'] . '">
							<div class="mgm_subs_option ' . $pack['membership_type'] . '">
								' . $input . '
							</div>
							<div class="mgm_subs_pack_desc ' . $pack['membership_type'] . '">
								' . $packs_obj->get_pack_desc($pack) . '
							</div>
							<div class="clearfix"></div>
							<div class="mgm_subs_desc ' . $pack['membership_type'] . '">
								' . mgm_stripslashes_deep($pack['description']) . '
							</div>
						</div>';
                } else {
                    // input
                    $input = sprintf('<input type="radio" %s class="mgm_subs_radio" name="subs_opt" id="subs_opt_%d" value="%s" rel="mgm_subscription_options"/>', $checked, $pack['id'], $subs_opt_enc);
                    // html
                    $extend_packages .= '  
						<div class="mgm_subs_wrapper ' . $pack['membership_type'] . '">
							<div class="mgm_subs_option ' . $pack['membership_type'] . '">
								' . $input . '
							</div>
							<div class="mgm_subs_pack_desc ' . $pack['membership_type'] . '">
								' . $packs_obj->get_pack_desc($pack) . '
							</div>
							<div class="clearfix"></div>
							<div class="mgm_subs_desc ' . $pack['membership_type'] . '">
								' . mgm_stripslashes_deep($pack['description']) . '
							</div>
						</div>';
                }
            }
            // show error
            if (!$extend_packages) {
                // html
                $html .= '<div class="mgm_subs_wrapper">
							<div class="mgm_subs_pack_desc">
								' . __('Sorry, no extend available.', 'mgm') . '
							</div>
						</div>';
                $html .= '<p>						
							<input type="button" name="cancel" onclick="window.location=\'' . $cancel_url . '\'" value="' . __('Cancel', 'mgm') . '" class="button-primary" />&nbsp;					
						  </p>';
            } else {
                // check errors if any:
                $html .= mgm_subscription_purchase_errors();
                // form
                $html .= '<form action="' . $form_action . '" method="post" class="mgm_form"><div class="mgm_get_pack_form_container">';
                $html .= $extend_packages;
                // get coupon field
                $html .= mgm_get_partial_fields(array('on_extend' => true), 'mgm_extend_field');
                // html
                // $html .= '<input type="hidden" name="ref" value="'. md5($member->amount .'_'. $member->duration .'_'. $member->duration_type .'_'. $member->membership_type) .'" />';
                $html .= '<input type="hidden" name="form_action" value="' . $form_action . '" />';
                // set
                $html .= '<p>							
							<input class="button button-primary" type="submit" name="submit" value="' . __('Next', 'mgm') . '" />&nbsp;&nbsp;
							<input class="button button-primary" type="button" name="cancel" onclick="window.location=\'' . $cancel_url . '\'" value="' . __('Cancel', 'mgm') . '" />&nbsp;					
						  </p>';
                // html
                $html .= '</div></form>';
            }
            // add pack_modules as json data, may consider jquery data later
            if (!empty($pack_modules)) {
                $html .= sprintf('<script language="javascript">var mgm_pack_modules = %s</script>', json_encode($pack_modules));
            }
            // end generate
        }
    }
    // return
    return $html;
}
/**
 * Membership extend link
 *
 * @param string $label : link lable
 * @param boolean $return: whether return the link or echo
 * @return the link
 */
function mgm_membership_extend_link($label, $return = true)
{
    //default label
    if (empty($label)) {
        $label = __('Extend', 'mgm');
    }
    $extend_link = "";
    //logged in user:
    $user = wp_get_current_user();
    if (!isset($user->ID) || isset($user->ID) && $user->ID == 0 || is_super_admin()) {
        return "";
    }
    $subscription_packs = mgm_get_class('subscription_packs');
    $member = mgm_get_member($user->ID);
    $pack_id = $member->pack_id;
    if ($pack_id) {
        $pack = $subscription_packs->get_pack($member->pack_id);
        $num_cycles = isset($member->active_num_cycles) && !empty($member->active_num_cycles) ? $member->active_num_cycles : $pack['num_cycles'];
        // check cycles
        if ($num_cycles > 0 && mgm_pack_extend_allowed($pack)) {
            $extend_link = '<a href="' . mgm_get_custom_url('transactions', false, array('action' => 'extend', 'pack_id' => $pack_id, 'username' => $user->user_login)) . '">' . $label . '</a>';
        }
    }
    //if return
    if ($return) {
        return $extend_link;
    } else {
        echo $extend_link;
    }
}