function process_payment_data(&$payment_data, $cart_items)
{
    global $wpdb, $wp_eStore_config;
    $wp_eStore_config = WP_eStore_Config::getInstance();
    $products_table_name = WP_ESTORE_PRODUCTS_TABLE_NAME;
    $script_location = get_option('eStore_download_script');
    $random_key = get_option('eStore_random_code');
    $payment_currency = get_option('cart_payment_currency');
    $customvariables = get_custom_var($payment_data['custom']);
    $product_specific_instructions = "";
    $currency_symbol = get_option('cart_currency_symbol');
    //Fire the begin processing hook
    do_action('eStore_begin_payment_processing', $payment_data['payer_email'], $customvariables['ip']);
    $product_id_array = array();
    $product_name_array = array();
    $product_price_array = array();
    $product_qty_array = array();
    $download_link_array = array();
    $download_link_for_digital_item = array();
    $counter = 0;
    $product_key_data = "";
    foreach ($cart_items as $current_cart_item) {
        $cart_item_data_num = $current_cart_item['item_number'];
        $cart_item_data_name = $current_cart_item['item_name'];
        $cart_item_data_quantity = $current_cart_item['quantity'];
        $cart_item_data_total = $current_cart_item['mc_gross'];
        $cart_item_data_currency = $current_cart_item['mc_currency'];
        eStore_payment_debug('Item Number: ' . $cart_item_data_num, true);
        eStore_payment_debug('Item Name: ' . $cart_item_data_name, true);
        eStore_payment_debug('Item Quantity: ' . $cart_item_data_quantity, true);
        eStore_payment_debug('Item Total: ' . $cart_item_data_total, true);
        eStore_payment_debug('Item Currency: ' . $cart_item_data_currency, true);
        if ($cart_item_data_num != "SHIPPING") {
            // Compare the values with the values stored in the database
            $key = $cart_item_data_num;
            $retrieved_product = $wpdb->get_row("SELECT * FROM {$products_table_name} WHERE id = '{$key}'", OBJECT);
            if (!$retrieved_product) {
                eStore_payment_debug('No Item found for the Item ID: ' . $cart_item_data_num, false);
                return false;
            }
            $coupon_code = $customvariables['coupon'];
            if (!empty($coupon_code)) {
                eStore_payment_debug('Coupon Code Used : ' . $coupon_code, true);
                $coupon_table_name = $wpdb->prefix . "wp_eStore_coupon_tbl";
                $ret_coupon = $wpdb->get_row("SELECT * FROM {$coupon_table_name} WHERE coupon_code = '{$coupon_code}'", OBJECT);
                if ($ret_coupon) {
                    $discount_amount = $ret_coupon->discount_value;
                    $discount_type = $ret_coupon->discount_type;
                    if ($discount_type == 0) {
                        //apply % discount
                        $discount = $retrieved_product->price * $discount_amount / 100;
                        $true_product_price = $retrieved_product->price - $discount;
                        eStore_payment_debug('Product Price after applying % discount: ' . $true_product_price, true);
                    } else {
                        // apply value discount
                        $true_product_price = $retrieved_product->price - $discount_amount;
                        eStore_payment_debug('Product Price after applying fixed amount discount: ' . $true_product_price, true);
                    }
                } else {
                    eStore_payment_debug('Could not find the coupon in the database: ' . $coupon_code, false);
                }
            } else {
                if (is_numeric($retrieved_product->a3)) {
                    $true_product_price = 0;
                    //subscription product
                } else {
                    if (is_numeric($retrieved_product->price)) {
                        $true_product_price = $retrieved_product->price * $cart_item_data_quantity;
                    } else {
                        $true_product_price = 0;
                        //most likely a subscription
                    }
                }
            }
            $true_product_price = round($true_product_price, 2);
            if ($cart_item_data_total < $true_product_price) {
                eStore_payment_debug('Wrong Product Price Detected. Actual Product Price : ' . $true_product_price, false);
                eStore_payment_debug('Paid Product Price : ' . $cart_item_data_total, false);
                return false;
            }
            if ($payment_currency != $cart_item_data_currency) {
                eStore_payment_debug('Invalid Product Currency. Expected currency: ' . $payment_currency . ', Received Currency: ' . $cart_item_data_currency, false);
                return false;
            }
            //*** Handle Membership Payment ***
            eStore_payment_debug('Checking if membership inegration is being used.', true);
            $member_ref = $retrieved_product->ref_text;
            if (!empty($member_ref)) {
                if (get_option('eStore_enable_wishlist_int')) {
                    eStore_payment_debug('WishList integration is being used... creating member account... see the "subscription_handle_debug.log" file for details', true);
                    wl_handle_subsc_signup($payment_data, $member_ref, $payment_data['txn_id']);
                } else {
                    if (function_exists('wp_eMember_install')) {
                        $eMember_id = $customvariables['eMember_id'];
                        eStore_payment_debug('eMember integration is being used... creating member account... see the "subscription_handle_debug.log" file for details', true);
                        eMember_handle_subsc_signup($payment_data, $member_ref, $payment_data['txn_id'], $eMember_id);
                    }
                }
            }
            //== End of Membership payment handling ==
            $item_name = $cart_item_data_name;
            //$retrieved_product->name;
            $download_link = generate_download_link($retrieved_product, $item_name, $payment_data);
            eStore_payment_debug('Download Link: [hidden]', true);
            //$download_link
            $product_specific_instructions .= eStore_get_product_specific_instructions($retrieved_product);
            if ($retrieved_product->create_license == 1) {
                $license_key = eStore_generate_license_key($payment_data);
                $product_license_data .= "\n" . $cart_item_data_name . " License Key: " . $license_key;
                eStore_payment_debug('License Key: [hidden]', true);
                //$license_key
            }
            //Issue serial key if this feature is being used
            $product_key_data .= eStore_post_sale_retrieve_serial_key_and_update($retrieved_product, $cart_item_data_name, $cart_item_data_quantity);
            array_push($product_name_array, $cart_item_data_name);
            array_push($product_id_array, $cart_item_data_num);
            if (empty($cart_item_data_total)) {
                $cart_item_data_total = $retrieved_product->price;
            }
            array_push($product_price_array, $cart_item_data_total);
            array_push($product_qty_array, $cart_item_data_quantity);
            array_push($download_link_array, $download_link);
            if (eStore_check_if_string_contains_url($download_link)) {
                array_push($download_link_for_digital_item, $download_link);
            }
        }
        $counter++;
    }
    if (!empty($product_key_data)) {
        $payment_data['product_key_data'] = $product_key_data;
    }
    // How long the download link remain valid (hours)
    $download_url_life = get_option('eStore_download_url_life');
    // Emails
    $notify_email = get_option('eStore_notify_email_address');
    // Email which will recive notification of sale (sellers email)
    $download_email = get_option('eStore_download_email_address');
    // Email from which the mail wil be sent
    $email_subject = get_option('eStore_buyer_email_subj');
    $email_body = get_option('eStore_buyer_email_body');
    $notify_subject = get_option('eStore_seller_email_subj');
    $notify_body = get_option('eStore_seller_email_body');
    // Send the product
    for ($i = 0; $i < sizeof($product_name_array); $i++) {
        $constructed_products_name .= $product_name_array[$i];
        $constructed_products_name .= ", ";
        $constructed_products_price .= $product_price_array[$i];
        $constructed_products_price .= ", ";
        $constructed_products_id .= $product_id_array[$i];
        $constructed_products_id .= ", ";
        $constructed_products_details .= "\n" . $product_name_array[$i] . " x " . $product_qty_array[$i] . " - " . $currency_symbol . $product_price_array[$i] . " (" . $payment_currency . ")";
        $tax_inc_price = eStore_get_tax_include_price_by_prod_id($product_id_array[$i], $product_price_array[$i]);
        $constructed_products_details_tax_inc .= "\n" . $product_name_array[$i] . " x " . $product_qty_array[$i] . " - " . $currency_symbol . $tax_inc_price . " (" . $payment_currency . ")";
        //Download links list for all items in the cart
        $constructed_download_link .= "\n";
        if (is_array($download_link_array[$i])) {
            $package_downloads = $download_link_array[$i];
            for ($j = 0; $j < sizeof($package_downloads); $j++) {
                $constructed_download_link .= $package_downloads[$j];
                $constructed_download_link .= "\n";
            }
        } else {
            $constructed_download_link .= $download_link_array[$i];
        }
        //Download links for only digital items in the cart
        $constructed_download_link_for_digital_item .= "\n";
        if (is_array($download_link_for_digital_item[$i])) {
            $package_downloads2 = $download_link_for_digital_item[$i];
            for ($j = 0; $j < sizeof($package_downloads2); $j++) {
                $constructed_download_link_for_digital_item .= $package_downloads2[$j];
                $constructed_download_link_for_digital_item .= "\n";
            }
        } else {
            $constructed_download_link_for_digital_item .= $download_link_for_digital_item[$i];
        }
    }
    //Counter for incremental receipt number
    $last_records_id = $wp_eStore_config->getValue('eStore_custom_receipt_counter');
    //get_option('eStore_custom_receipt_counter');
    if (empty($last_records_id)) {
        $last_records_id = 0;
    }
    $receipt_counter = $last_records_id + 1;
    eStore_payment_debug('Incremental counter value: ' . $receipt_counter, true);
    $wp_eStore_config->setValue('eStore_custom_receipt_counter', $receipt_counter);
    $wp_eStore_config->saveConfig();
    $purchase_date = date("Y-m-d");
    //$total_purchase_amt = $payment_data['mc_gross'];
    $total_minus_total_tax = number_format($payment_data['mc_gross'] - $payment_data['mc_tax'], 2);
    $txn_id = $payment_data['txn_id'];
    $buyer_shipping_info = $payment_data['address'];
    $buyer_phone = $payment_data['phone'];
    $shipping_option = $customvariables['ship_option'];
    if (empty($shipping_option)) {
        $shipping_option = "Default";
    }
    $product_specific_instructions = eStore_apply_post_payment_dynamic_tags($product_specific_instructions, $payment_data, $cart_items);
    //$tags = array("{first_name}","{last_name}","{payer_email}","{product_name}","{product_link}","{product_price}","{product_id}","{download_life}","{product_specific_instructions}","{product_details}","{shipping_info}","{license_data}","{purchase_date}","{purchase_amt}","{transaction_id}","{shipping_option_selected}","{product_link_digital_items_only}","{total_tax}","{total_shipping}","{total_minus_total_tax}","{customer_phone}","{counter}","{coupon_code}","{serial_key}");
    //$vals = array($payment_data['first_name'],$payment_data['last_name'],$payment_data['payer_email'],$constructed_products_name,$constructed_download_link,$constructed_products_price,$constructed_products_id,$download_url_life,$product_specific_instructions,$constructed_products_details,$buyer_shipping_info,$product_license_data,$purchase_date,$payment_data['mc_gross'],$txn_id,$shipping_option,$constructed_download_link_for_digital_item,$payment_data['mc_tax'],$payment_data['mc_shipping'],$total_minus_total_tax,$buyer_phone,$receipt_counter,$coupon_code,$product_key_data);
    $additional_data = array();
    $additional_data['constructed_products_name'] = $constructed_products_name;
    $additional_data['constructed_products_price'] = $constructed_products_price;
    $additional_data['constructed_products_id'] = $constructed_products_id;
    $additional_data['constructed_products_details'] = $constructed_products_details;
    $additional_data['constructed_products_details_tax_inc'] = $constructed_products_details_tax_inc;
    $additional_data['product_specific_instructions'] = $product_specific_instructions;
    $additional_data['constructed_download_link'] = $constructed_download_link;
    $additional_data['constructed_download_link_for_digital_item'] = $constructed_download_link_for_digital_item;
    $additional_data['product_license_data'] = $product_license_data;
    //this is the license mgr key (not the normal serial key code)
    $subject = eStore_apply_post_payment_dynamic_tags($email_subject, $payment_data, $cart_items, $additional_data);
    //str_replace($tags,$vals,$email_subject);
    $body = eStore_apply_post_payment_dynamic_tags($email_body, $payment_data, $cart_items, $additional_data);
    //str_replace($tags,$vals,$email_body);
    $headers = 'From: ' . $download_email . "\r\n";
    $attachment = '';
    //Call the filter for email notification body
    eStore_payment_debug('Applying filter - eStore_notification_email_body_filter', true);
    $body = apply_filters('eStore_notification_email_body_filter', $body, $payment_data, $cart_items);
    eStore_payment_debug('Sending product email to : ' . $payment_data["payer_email"], true);
    if (get_option('eStore_use_wp_mail')) {
        wp_eStore_send_wp_mail($payment_data['payer_email'], $subject, $body, $headers);
        //wp_mail($payment_data['payer_email'], $subject, $body, $headers);
        eStore_payment_debug('Product Email successfully sent to ' . $payment_data['payer_email'] . '.', true);
    } else {
        if (@eStore_send_mail($payment_data['payer_email'], $body, $subject, $download_email, $attachment)) {
            eStore_payment_debug('Product Email successfully sent (using PHP mail) to ' . $payment_data['payer_email'] . '.', true);
        } else {
            eStore_payment_debug('Error sending product Email (using PHP mail) to ' . $payment_data['payer_email'] . '.', false);
        }
    }
    // Notify seller
    foreach ($payment_data as $key => $value) {
        $post_string .= "{$key}={$value}, ";
    }
    $n_subject = eStore_apply_post_payment_dynamic_tags($notify_subject, $payment_data, $cart_items, $additional_data);
    //str_replace($tags,$vals,$notify_subject);
    $n_body = eStore_apply_post_payment_dynamic_tags($notify_body, $payment_data, $cart_items, $additional_data);
    //str_replace($tags,$vals,$notify_body);
    if ($wp_eStore_config->getValue('eStore_add_payment_parameters_to_admin_email') == '1') {
        $n_body .= "\n\n------- User Email ----------\n" . $body . "\n\n------- Paypal Parameters (Only admin will receive this) -----\n" . $post_string;
    }
    $n_body = stripslashes($n_body);
    $notify_emails_array = explode(",", $notify_email);
    foreach ($notify_emails_array as $notify_email_address) {
        if (!empty($notify_email_address)) {
            $recipient_email_address = trim($notify_email_address);
            if (get_option('eStore_use_wp_mail')) {
                wp_eStore_send_wp_mail($recipient_email_address, $n_subject, $n_body, $headers);
                //wp_mail($recipient_email_address, $n_subject, $n_body, $headers);
                eStore_payment_debug('Notify Email successfully sent to ' . $recipient_email_address . '.', true);
            } else {
                if (@eStore_send_mail($recipient_email_address, $n_body, $n_subject, $download_email)) {
                    eStore_payment_debug('Notify Email successfully sent (using PHP mail) to ' . $recipient_email_address . '.', true);
                } else {
                    eStore_payment_debug('Error sending notify Email (using PHP mail) to ' . $recipient_email_address . '.', false);
                }
            }
        }
    }
    //Record details for the Thank You page display
    eStore_payment_debug('Creating transaction result display value', true);
    //Save transaction result for thank you page display
    $constructed_download_link = nl2br($constructed_download_link);
    $constructed_download_link = wp_eStore_replace_url_in_string_with_link($constructed_download_link);
    eStore_save_trans_result_for_thank_you_page_display($payment_data, $constructed_download_link, $cart_items);
    global $wp_eStore_transaction_result_display_content;
    $wp_eStore_transaction_result_display_content = $_SESSION['eStore_tx_result'];
    eStore_payment_debug('Transaction result display value set', true);
    return true;
}
function eStore_aff_award_commission($payment_data, $cart_items, $customReferrer = '')
{
    eStore_payment_debug('===> Start of Affiliate Commission Calculation <===', true);
    eStore_payment_debug('Checking if the WP Affiliate Platform Plugin is installed.', true);
    if (eStore_affiliate_capability_exists()) {
        global $wpdb;
        $products_table_name = WP_ESTORE_PRODUCTS_TABLE_NAME;
        $affiliates_table_name = WP_AFFILIATE_TABLE_NAME;
        $aff_sales_table = WP_AFFILIATE_SALES_TABLE_NAME;
        eStore_payment_debug('WP Affiliate Platform is installed, checking commission related details...', true);
        $customvariables = get_custom_var($payment_data['custom']);
        if (!empty($customReferrer)) {
            $referrer = $customReferrer;
            eStore_payment_debug('Revenue sharing feature is being used', true);
        } else {
            $referrer = $customvariables['ap_id'];
        }
        // Check affiliate leads table for referrer if enabled
        if (WP_ESTORE_CHECK_LEADS_TABLE_FOR_AFFILIATE_REFERRAL_CHECK === '1') {
            if (function_exists('wp_aff_get_referrer_from_leads_table_for_buyer')) {
                $buyer_email = $payment_data['payer_email'];
                $referrer = wp_aff_get_referrer_from_leads_table_for_buyer($buyer_email);
                eStore_payment_debug('Referrer value returned from the leads table check is:' . $referrer, true);
            } else {
                eStore_payment_debug('You need to update the affiliate plugin to use this feature', false);
            }
        }
        // Check if an eMember user with a referrer has purchased
        $eMember_member_id = $customvariables['eMember_id'];
        if (WP_ESTORE_CHECK_EMEMBER_REFERRER_FOR_AFFILIATE_ID === '1' && !empty($eMember_member_id)) {
            eStore_payment_debug('This purchase was made by a member with eMember ID: ' . $eMember_member_id . ' Looking to see if a referrer value exists in this member profile...', true);
            $eMember_resultset = dbAccess::find(WP_EMEMBER_MEMBERS_TABLE_NAME, ' member_id=' . esc_sql($eMember_member_id));
            $member_referrer = trim($eMember_resultset->referrer);
            eStore_payment_debug('Attached referrer value with this member profile is: ' . $member_referrer, true);
            if (!empty($member_referrer)) {
                $referrer = $member_referrer;
                eStore_payment_debug('Setting the referrer value of this sale to Affiliate ID: ' . $referrer, true);
            }
        }
        if (!empty($referrer)) {
            eStore_payment_debug('The referrer for this sale is:' . $referrer, true);
            $c_id = $customvariables['c_id'];
            //campaign id (if any)
            $txn_id = $payment_data['txn_id'];
            $buyer_email = $payment_data['payer_email'];
            $clientip = $customvariables['ip'];
            eStore_payment_debug('Additional debug data. Txn ID: ' . $txn_id . ' Campign ID: ' . $c_id . ' Buyer Email: ' . $buyer_email, true);
            //Check if no commission is to be awarded for self purchase
            if (WP_ESTORE_NO_COMMISSION_FOR_SELF_PURCHASE == '1') {
                //check if the referrer is the buyer
                if (function_exists('wp_aff_check_if_buyer_is_referrer')) {
                    if (wp_aff_check_if_buyer_is_referrer($referrer, $buyer_email)) {
                        eStore_payment_debug('The buyer (' . $buyer_email . ') is the referrer (' . $referrer . ') so this sale is NOT ELIGIBLE for generating any commission.', true);
                        return true;
                    } else {
                        eStore_payment_debug('The buyer is not the referrer so this sale is eligible for generating commission.', true);
                    }
                } else {
                    eStore_payment_debug('You need to update your affiliate plugin before you can use the No commission on self purchase feature.', false);
                }
            }
            $resultset = $wpdb->get_results("SELECT * FROM {$aff_sales_table} WHERE txn_id = '{$txn_id}'", OBJECT);
            if ($resultset) {
                //Commission for this transaction has already been awarded so no need to do anything.
                eStore_payment_debug('The database record shows that the commission for this transaction has already been awarded so no need to do anything.', true);
                eStore_payment_debug('===> End Affiliate Commission Check <===', true);
                return;
            }
            //Check if the "DO not award commission if coupon is used" feature is in use
            if (get_option('eStore_aff_no_commission_if_coupon_used') != '') {
                $coupon = $customvariables['coupon'];
                if (!empty($coupon)) {
                    eStore_payment_debug('Do Not Award Commission if Coupon Used feature is enabled. Commission will not be awarded for this transaction since a coupon code has been used. Coupon: ' . $coupon, true);
                    eStore_payment_debug('===> End Affiliate Commission Check <===', true);
                    return;
                }
                eStore_payment_debug('No coupon used for this transaction', true);
            }
            $wp_aff_affiliates_db = $wpdb->get_row("SELECT * FROM {$affiliates_table_name} WHERE refid = '{$referrer}'", OBJECT);
            $commission_level = $wp_aff_affiliates_db->commissionlevel;
            $second_tier_referrer = $wp_aff_affiliates_db->referrer;
            $second_tier_commission_level = 0;
            if (!empty($second_tier_referrer)) {
                //This affiliate has a 2nd tier referrer
                eStore_payment_debug('Retrieving the 2nd tier affiliate profile.', true);
                $second_tier_aff = $wpdb->get_row("SELECT * FROM {$affiliates_table_name} WHERE refid = '{$second_tier_referrer}'", OBJECT);
                if (!empty($second_tier_aff->sec_tier_commissionlevel)) {
                    $second_tier_commission_level = $second_tier_aff->sec_tier_commissionlevel;
                    eStore_payment_debug('The 2nd tier affiliate (' . $second_tier_referrer . ') has a profile specific 2nd tier commission level. Commission level is: ' . $second_tier_commission_level, true);
                } else {
                    $second_tier_commission_level = get_option('wp_aff_2nd_tier_commission_level');
                }
            }
            $counter = 1;
            $commission_amount = 0;
            $product_comm_amount = 0;
            $second_tier_commission_amount = 0;
            $purchased_items = '';
            global $eStore_affiliate_individual_product_commisions;
            foreach ($cart_items as $current_cart_item) {
                eStore_payment_debug('Processing Commission for : ' . $current_cart_item['item_name'], true);
                $cart_item_number = $current_cart_item['item_number'];
                //The total item price includes the (individual item price * quantity)
                $total_item_price = $current_cart_item['mc_gross'] - $current_cart_item['mc_shipping'];
                $item_qty = $current_cart_item['quantity'];
                eStore_payment_debug('Total Price of the currently processing item : ' . $total_item_price, true);
                $retrieved_product = $wpdb->get_row("SELECT * FROM {$products_table_name} WHERE id = '{$cart_item_number}'", OBJECT);
                if (!empty($retrieved_product->commission)) {
                    eStore_payment_debug('Using product specific commission specified in eStore', true);
                    if (get_option('wp_aff_use_fixed_commission')) {
                        eStore_payment_debug('Using fixed commission rate for this product specific commission', true);
                        //Give fixed commission from the product's specified level
                        $product_comm_amount = $item_qty * $retrieved_product->commission;
                        //Award fixed commission for 2nd tier from the product's specified level
                        if (!empty($retrieved_product->tier2_commission)) {
                            $product_second_tier_comm_amt = $item_qty * $retrieved_product->tier2_commission;
                        }
                    } else {
                        eStore_payment_debug('Using % based commission rate for this product specific commission', true);
                        //Award % commission from the product's specified level
                        //The total item price includes the (individual item price * quantity)
                        $product_comm_amount = $total_item_price * $retrieved_product->commission / 100;
                        //Award % commission for 2nd tier from the product's specified level
                        if (!empty($retrieved_product->tier2_commission)) {
                            $product_second_tier_comm_amt = $total_item_price * $retrieved_product->tier2_commission / 100;
                        }
                    }
                } else {
                    if ($retrieved_product->commission == "0") {
                        $product_comm_amount = 0;
                        $product_second_tier_comm_amt = 0;
                        eStore_payment_debug('This product will not generate any commission as the product specific commission for this product has been specified as 0', true);
                    } else {
                        eStore_payment_debug('Using commission rate from affiliate profile', true);
                        if (get_option('wp_aff_use_fixed_commission')) {
                            eStore_payment_debug('Using fixed commission rate for this commission. Qty:' . $item_qty . ', Fixed commission level:' . $commission_level, true);
                            //Give fixed commission from the affiliate's specified level
                            $product_comm_amount = $item_qty * $commission_level;
                            //Award fixed commission for 2nd tier from the affiliate's specified level
                            $product_second_tier_comm_amt = $item_qty * $second_tier_commission_level;
                        } else {
                            eStore_payment_debug('Using % based commission rate for this commission. Qty:' . $item_qty . ', Total price:' . $total_item_price . ', Commission level:' . $commission_level, true);
                            //The total item price includes the (individual item price * quantity)
                            $product_comm_amount = $total_item_price * ($commission_level / 100);
                            //Award fixed commission for 2nd tier from the affiliate's specified level
                            $product_second_tier_comm_amt = $total_item_price * ($second_tier_commission_level / 100);
                        }
                    }
                }
                $commission_amount = $commission_amount + $product_comm_amount;
                $second_tier_commission_amount = $second_tier_commission_amount + $product_second_tier_comm_amt;
                //Save the individual product commission details for later use
                $current_cart_item['product_commission'] = $product_comm_amount;
                $current_cart_item['product_commission_2nd_tier'] = $product_second_tier_comm_amt;
                $current_cart_item['product_commission_total'] = $product_comm_amount + $product_second_tier_comm_amt;
                array_push($eStore_affiliate_individual_product_commisions, $current_cart_item);
                if ($counter > 1) {
                    $purchased_items .= ", ";
                }
                $purchased_items .= $cart_item_number;
                $counter++;
            }
            $commission_amount = round($commission_amount, 2);
            $second_tier_commission_amount = round($second_tier_commission_amount, 2);
            $sale_amount = $payment_data['mc_gross'];
            $clientdate = date("Y-m-d");
            $clienttime = date("H:i:s");
            $txn_id = $payment_data['txn_id'];
            $item_id = $purchased_items;
            $buyer_name = $payment_data['first_name'] . " " . $payment_data['last_name'];
            $aff_version = get_option('wp_aff_platform_version');
            //Check if using the satellite affiliate plugin is being used then direct commision there
            if (defined('SATELLITE_WP_AFFILIATE_PLATFORM_VERSION')) {
                //WP_ESTORE_REDIRECT_COMMISSION_USING_SATELLITE_AFFILIATE_PLUGIN
                eStore_payment_debug('Satellite affiliate plugin is installed. Redirecting commission using the satellite affiliate plugin.', true);
                if (function_exists('satellite_aff_perform_remote_sale_tracking_eStore')) {
                    eStore_payment_debug('Redirecting commission using the direct commission awarding method. Commission amount: ' . $commission_amount, true);
                    satellite_aff_perform_remote_sale_tracking_eStore($commission_amount, $sale_amount, $referrer, $txn_id, $item_id, $buyer_email, $clientip, $buyer_name);
                } else {
                    if (function_exists('satellite_aff_perform_remote_sale_tracking')) {
                        satellite_aff_perform_remote_sale_tracking($sale_amount, $referrer, $txn_id, '', $buyer_email, $clientip);
                    }
                }
                return true;
            }
            eStore_payment_debug("WP Affiliate plugin version is: " . $aff_version, true);
            // Check if the commission per transaction option is enabled
            if (get_option('eStore_aff_enable_commission_per_transaction') != '') {
                eStore_payment_debug('Commission per transaction option is enabled so the commission will be awarded for the full transaction rather than on a per item basis', true);
                if (get_option('wp_aff_use_fixed_commission')) {
                    eStore_payment_debug('Using fixed commission model... Awarding fixed affiliate commission', true);
                    $updatedb = "INSERT INTO {$aff_sales_table} (refid,date,time,browser,ipaddress,payment,sale_amount,txn_id,item_id,buyer_email,campaign_id,buyer_name) VALUES ('{$referrer}','{$clientdate}','{$clienttime}','','{$clientip}','{$commission_amount}','{$sale_amount}','{$txn_id}','{$item_id}','{$buyer_email}','{$c_id}','{$buyer_name}')";
                    $results = $wpdb->query($updatedb);
                    eStore_payment_debug('===> End Affiliate Commission Check <===', true);
                    return;
                } else {
                    //For percentage based commission there is no difference between per transaction commission amount and the per item commission amount
                }
            }
            //% based commission
            $updatedb = "INSERT INTO {$aff_sales_table} (refid,date,time,browser,ipaddress,payment,sale_amount,txn_id,item_id,buyer_email,campaign_id,buyer_name) VALUES ('{$referrer}','{$clientdate}','{$clienttime}','','{$clientip}','{$commission_amount}','{$sale_amount}','{$txn_id}','{$item_id}','{$buyer_email}','{$c_id}','{$buyer_name}')";
            $results = $wpdb->query($updatedb);
            //Send commission notification email if enabled
            if (function_exists('wp_aff_send_commission_notification')) {
                if ($commission_amount > 0) {
                    eStore_payment_debug("Sending commission email notification request to the affiliate plugin", true);
                    wp_aff_send_commission_notification($wp_aff_affiliates_db->email, $txn_id);
                    eStore_payment_debug("Commission email notification request sending complete.", true);
                } else {
                    eStore_payment_debug("The commission amount is 0. No need to notify the affiliate", true);
                }
            }
            $message = 'The sale has been registered in the WP Affiliate Platform Database for referrer: ' . $referrer . ' with amount: ' . $commission_amount;
            eStore_payment_debug($message, true);
            //2nd tier affiliate commission
            eStore_payment_debug('Awarding 2nd tier commission if applicable', true);
            //$result = wp_aff_award_second_tier_commission($wp_aff_affiliates_db,$sale_amount,$txn_id,$item_id,$buyer_email);
            if (get_option('wp_aff_use_2tier') && !empty($wp_aff_affiliates_db->referrer)) {
                $award_tier_commission = true;
                $duration = get_option('wp_aff_2nd_tier_duration');
                if (!empty($duration)) {
                    $join_date = $wp_aff_affiliates_db->date;
                    $days_since_joined = round((strtotime(date("Y-m-d")) - strtotime($join_date)) / (60 * 60 * 24));
                    if ($days_since_joined > $duration) {
                        eStore_payment_debug('Tier commission award duration expried', true);
                        $award_tier_commission = false;
                    }
                }
                if ($award_tier_commission) {
                    $updatedb = "INSERT INTO {$aff_sales_table} (refid,date,time,browser,ipaddress,payment,sale_amount,txn_id,item_id,buyer_email) VALUES ('{$wp_aff_affiliates_db->referrer}','{$clientdate}','{$clienttime}','','','{$second_tier_commission_amount}','{$sale_amount}','{$txn_id}','{$item_id}','{$buyer_email}')";
                    //$updatedb = "INSERT INTO $aff_sales_table VALUES ('$wp_aff_affiliates_db->referrer','$clientdate','$clienttime','','','$second_tier_commission_amount','$sale_amount','$txn_id','$item_id','$buyer_email')";
                    $results = $wpdb->query($updatedb);
                    eStore_payment_debug('Tier commission awarded to: ' . $wp_aff_affiliates_db->referrer . '. Commission amount: ' . $second_tier_commission_amount, true);
                }
            }
            eStore_payment_debug('End of tier commission check', true);
        } else {
            eStore_payment_debug('No Referrer Found. This is not an affiliate referred sale.', true);
        }
    } else {
        eStore_payment_debug('WP Affiliate Platform capability is not present.', true);
    }
    eStore_payment_debug('===> End Affiliate Commission Check <===', true);
}
function extract_2co_general_payment_data_secondary($raw_data, $gateway, $cart_items)
{
    eStore_payment_debug("2CO IPN Processing - Creating payment data using thank you page post data.", true);
    $custom_data = $cart_items[0]['custom'];
    $customvariables = get_custom_var($custom_data);
    $eMember_id = $customvariables['eMember_id'];
    $coupon = $customvariables['coupon'];
    $total_shipping = $cart_items[0]['total_shipping'];
    $total_tax = $cart_items[0]['total_tax'];
    $sub_total = $cart_items[0]['subtotal'];
    $gross_total = $sub_total + $total_shipping + $total_tax;
    $address = $raw_data['street_address'] . " " . $raw_data['street_address2'] . ", " . $raw_data['street_address'] . ", " . $raw_data['state'] . " " . $raw_data['zip'] . ", " . $raw_data['country'];
    //item_type_# = bill or refund
    $payment_data = array('gateway' => $gateway, 'custom' => $custom_data, 'txn_id' => $raw_data['invoice_id'], 'txn_type' => "ORDER_CREATED", 'transaction_subject' => $raw_data['message_description'], 'first_name' => $raw_data['first_name'], 'last_name' => $raw_data['last_name'], 'payer_email' => $raw_data['email'], 'num_cart_items' => count($cart_items), 'subscr_id' => $raw_data['invoice_id'], 'address' => $address, 'phone' => $raw_data['phone'], 'coupon_used' => $coupon, 'eMember_username' => $eMember_id, 'eMember_userid' => $eMember_id, 'mc_gross' => $gross_total, 'mc_shipping' => $total_shipping, 'mc_tax' => $total_tax, 'address_street' => $raw_data['street_address'], 'address_city' => $raw_data['city'], 'address_state' => $raw_data['state'], 'address_country' => $raw_data['country']);
    return $payment_data;
}