<?php
/***************************************************************************
 *                                                                          *
 * Copyright (c) 2005 ISPG Technologies (I) Pvt Ltd. All rights reserved.   *
 *                                                                          *
 * This  is  commercial  software,  only  users  who have purchased a valid *
 * license  and  accept  to the terms of the  License Agreement can install *
 * and use this program.                                                    *
 *                                                                          *
 ****************************************************************************
 * PLEASE READ THE FULL TEXT  OF THE SOFTWARE  LICENSE   AGREEMENT  IN  THE *
 * "copyright.txt" FILE PROVIDED WITH THIS DISTRIBUTION PACKAGE.            *
 ****************************************************************************/
//
//$Id: AffiliateController.php, v 1.0 2011/06/14 20:52:11
//
class AffiliateController extends Controller {
    public function __construct() {
        $this->init();
        if (!__AFFILIATE_MODULE) {
            $this->setRedirect('index/');
        }
    }
    //LIST ALL AFFILIATES
    public function indexAction() {
        $ObjAffiliate       = new AffiliateModel();
        $languageIDs        = $this->ObjView->languageIDs;
        $settingsDateFormat = $this->getSettingValue('site_settings', 'date_format');
        /* Privileges*/
        $affeditprivilage   = $this->ObjCommon->hasPrivilege('affiliate/edit/');
        $this->ObjView->assign("affeditprivilage", $affeditprivilage);
        $affdeleteprivilage = $this->ObjCommon->hasPrivilege('affiliate/destroy/');
        $this->ObjView->assign("affdeleteprivilage", $affdeleteprivilage);
        $affshowprivilage = $this->ObjCommon->hasPrivilege('affiliate/show/');
        $this->ObjView->assign("affshowprivilage", $affshowprivilage);
        /* Privileges*/
        $link = 'affiliate/index/';
        if (isset($_POST['changeStatus'])) {
            $changestatus = $ObjAffiliate->changeAffiliateStatus($_POST, $_POST['checkaffiliatesIDs'], $affdeleteprivilage);
            if ($changestatus && $_POST['changeStatus'] == "Deleted") {
                $this->setMessage("language.msgAffiliateDelete", "success");
            } else if ($changestatus) {
                $this->setMessage("language.msgStatus", "success");
            }
            $this->setRedirect();
        }
        if (isset($_POST['submitSearch'])) {
            if ($_POST['affiliateID'] != '') {
                $link .= 'affiliateId/' . $this->escape($_POST['affiliateID']) . '/';
            }
            if ($_POST['affiliateName'] != '') {
                $link .= 'name/' . $this->encodeUrlString($_POST['affiliateName']) . '/';
            }
            if ($_POST['affDate']) {
                $date     = explode(" - ", $this->escape($_POST['affDate']));
                $fromdate = $date[0];
                $toDate   = isset($date[1]) ? $date[1] : '';
                $link .= "from/" . $this->urlDate($fromdate, 'set', $settingsDateFormat) . "/";
                if ($toDate) {
                    $link .= "to/" . $this->urlDate($todate, 'set', $settingsDateFormat) . "/";
                }
            }
            $this->setRedirect($link);
        }
        $affiliateID   = $this->escape($this->getRequestValue('affiliateId'));
        $affiliateName = $this->escape($this->decodeUrlString($this->getRequestValue('name')));
        $fromDate      = $this->escape($this->urlDate($this->getRequestValue('from'), 'get', $settingsDateFormat));
        $toDate        = $this->escape($this->urlDate($this->getRequestValue('to'), 'get', $settingsDateFormat));
        $affDate       = $fromDate;
        if ($toDate) {
            $affDate .= " - " . $toDate;
        }
        // pagination settings
        list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
        $resAffiliates = $ObjAffiliate->listAffiliates($limitFrom, $limitTo, '', $affiliateID, $affiliateName, 'No', $this->convertDateForSQL($fromDate, $settingsDateFormat), $this->convertDateForSQL($toDate, $settingsDateFormat));
        $resPagesCount = $this->setPagesCount($key = 'page');
        $this->ObjView->assign('affiliateID', $affiliateID);
        $this->ObjView->assign('affiliateName', $affiliateName);
        $this->ObjView->assign('resAffiliates', $resAffiliates);
        $this->ObjView->assign('affDate', $affDate);
        $this->ObjView->display('AffiliateList.tpl');
    }
    //EDIT AN EXISTING AFFILIATE
    public function editAction($affiliateReqID = '') {
        $ObjCountry                = new CountryModel();
        $ObjAffiliate              = new AffiliateModel();
        $ObjProduct                = new ProductModel();
        $ObjEmailtemplate          = new EmailtemplateModel();
        $affiliateUserID           = $this->getRequestValue('id');
        $affiliateID               = '';
        $globalCommisionPercentage = $this->getSettingValue('affiliate_settings', 'affiliate_commission_value');
        if ($affiliateUserID > 0) {
            $resAffiliate = $ObjAffiliate->getAffiliateDetails($affiliateUserID);
        } //$affiliateUserID > 0
        else if ($affiliateReqID > 0) {
            $resAffiliate = $ObjAffiliate->getAffiliateReqForApprove($affiliateReqID);
            $affiliateID  = $ObjProduct->getRandomCode(6, 'Alphanumerics');
            $this->ObjView->assign('affiliateReqID', $affiliateReqID);
        } //$affiliateReqID > 0
        if (empty($resAffiliate)) {
            $this->setRedirect('/affiliate/index/');
        }
        //Status Change from Listing Page
        $changeStatus['changeStatus'] = $this->getRequestValue('newstatus');
        if (isset($changeStatus['changeStatus']) && $changeStatus['changeStatus'] != '' && $affiliateUserID > 0) {
            if ($changeStatus['changeStatus'] == "Active" || $changeStatus['changeStatus'] == "Inactive") {
                $changestatus = $ObjAffiliate->changeAffiliateStatus($changeStatus, $affiliateUserID, $this->ObjCommon->hasPrivilege('affiliate/destroy/'));
                if ($changestatus) {
                    $this->setMessage("language.msgStatus", "success");
                }
            }
            $this->setRedirect('affiliate/index/');
        }
        $languageIDs                       = $this->ObjView->languageIDs;
        $resAffiliate['affiliatePassword'] = '';
        if ($this->ObjForm->isValid('frmAffiliate', 'submitAffiliate')) {
            $ObjAffiliate->saveAffiliate($_POST, $affiliateUserID, $affiliateID, $affiliateReqID, 1);
            if ($affiliateReqID > 0) {
                $ObjAffiliate->changeAffiliateRequestStatus($affiliateReqID, 'Approved');
                // sent mail to affiliate with their login crdentials.
                $languageIDsCustom            = $languageIDs;
                $languageIDsCustom['Current'] = $_POST['preferredLanguage'];
                $emailbody                    = $ObjEmailtemplate->getEmailTemlateDetails($languageIDsCustom, '', 'affiliate-request-approved');
                $from                         = array(
                    $emailbody['emailFromEmail'],
                    $emailbody['emailFromName']
                );
                $siteName                     = $this->getSettingValue('site_settings', 'site_name');
                $siteUrl                      = $this->getSettingValue('site_settings', 'global_http_url');
                $companyLogo                  = $this->getSettingValue('company_information', 'company_logo');
                $userName                     = $_POST['affiliateFirstName'] . " " . $_POST['affiliateLastName'];
                $subject                      = $emailbody['emailSubject'];
                $bodytag                      = str_replace('{$siteName}', $siteName, $emailbody['emailHtml']);
                $bodytag                      = str_replace('{$userName}', $userName, $bodytag);
                $bodytag                      = str_replace('{$affiliateLogin}', $_POST['affiliateUserName'], $bodytag);
                $bodytag                      = str_replace('{$affiliatePassword}', $_POST['affiliatePassword'], $bodytag);
                $bodytag                      = str_replace('{$companyLogo}', $companyLogo, $bodytag);
                $bodytag                      = str_replace('{url}', rtrim($siteUrl, "/") . '/affiliate/', $bodytag);
                $this->ObjView->assign('emailbody', $bodytag);
                $this->ObjView->assign('siteUrl', $siteUrl);
                $this->ObjView->assign('siteName', $siteName);
                $this->ObjView->assign('userName', $userName);
                $this->ObjView->assign('companyLogo', $companyLogo);
                $body                           = $this->ObjCommon->fetch("email_templates/Layout.tpl", $languageIDsCustom);
                $mail_settings                  = $this->getSettingValue('mail_settings');
                $mail_settings['smtp_password'] = $this->encryptDecrypt("decrypt", $mail_settings['smtp_password']);
                $ObjMail                        = new Mail($mail_settings);
                $emailID                        = trim(addslashes($_POST['affiliateEmail']));
                $ObjMail->IsHTML();
                $ObjMail->sendMail($from, $emailID, $subject, $body);
                if ($ObjMail->Send()) {
                } //$ObjMail->Send()
            } //$affiliateReqID > 0
            else if ((trim($_POST['affiliatePassword']) != '') && (trim($_POST['affiliatePassword']) == trim($_POST['affiliatePasswordnew'])) && (trim($_POST['affiliatePasswordnew']) != '')) { // sent mail to affiliate user
                $languageIDsCustom            = $languageIDs;
                $languageIDsCustom['Current'] = $_POST['preferredLanguage'];
                $emailbody                    = $ObjEmailtemplate->getEmailTemlateDetails($languageIDsCustom, '', 'user-password-changed');
                $from                         = array(
                    $emailbody['emailFromEmail'],
                    $emailbody['emailFromName']
                );
                $siteName                     = $this->getSettingValue('site_settings', 'site_name');
                $siteUrl                      = $this->getSettingValue('site_settings', 'global_http_url');
                $companyLogo                  = $this->getSettingValue('company_information', 'company_logo');
                $userName                     = $_POST['affiliateFirstName'] . " " . $_POST['affiliateLastName'];
                $subject                      = $emailbody['emailSubject'];
                $bodytag                      = str_replace('{$siteName}', $siteName, $emailbody['emailHtml']);
                $bodytag                      = str_replace('{$userName}', $userName, $bodytag);
                $bodytag                      = str_replace('{$affiliateLogin}', $_POST['affiliateLoginName'], $bodytag);
                $bodytag                      = str_replace('{$userPassword}', $_POST['affiliatePassword'], $bodytag);
                $bodytag                      = str_replace('{$companyLogo}', $companyLogo, $bodytag);
                $bodytag                      = str_replace('{url}', rtrim($siteUrl, "/") . '/affiliate/', $bodytag);
                $this->ObjView->assign('emailbody', $bodytag);
                $this->ObjView->assign('siteUrl', $siteUrl);
                $this->ObjView->assign('siteName', $siteName);
                $this->ObjView->assign('userName', $userName);
                $this->ObjView->assign('companyLogo', $companyLogo);
                $body                           = $this->ObjCommon->fetch("email_templates/Layout.tpl", $languageIDsCustom);
                $mail_settings                  = $this->getSettingValue('mail_settings');
                $mail_settings['smtp_password'] = $this->encryptDecrypt("decrypt", $mail_settings['smtp_password']);
                $ObjMail                        = new Mail($mail_settings);
                $emailID                        = trim(addslashes($_POST['affiliateEmail']));
                $ObjMail->IsHTML();
                $ObjMail->sendMail($from, $emailID, $subject, $body);
                if ($ObjMail->Send()) {
                } //$ObjMail->Send()
            }
            if ($affiliateReqID > 0) {
                $this->setMessage("language.msgAffiliateRequestApproved", 'success', 'Affiliate', 'request_approve_message');
                $this->setRedirect('/affiliaterequest/index/');
            } //$affiliateReqID > 0
            else {
                if (ctype_space($_POST['affiliatePassword'])) {
                    $this->setMessage("language.msgAffiliateUpdatePasswordCase", "success");
                } //ctype_space($_POST['affiliatePassword'])
                else {
                    $this->setMessage("language.msgAffiliateUpdate", "success");
                }
            }
            $this->setRedirect('/affiliate/index/');
        } //$this->ObjForm->isValid('frmAffiliate', 'submitAffiliate')
        $this->ObjView->assignValues($resAffiliate);
        $this->ObjView->assign('resCountry', $ObjCountry->listCountriesForOption($languageIDs, 'Yes'));
        $this->ObjView->assign('globalCommisionPercentage', $globalCommisionPercentage);
        $resCommissionSettings   = $ObjAffiliate->getAffCommissionSettings($affiliateUserID);
        $globalSettingsArray[0]  = $this->getSettingValue('affiliate_settings', 'affiliate_enable_sales_commission');
        $globalSettingsArray[1]  = $this->getSettingValue('affiliate_settings', 'affiliate_first_purchase_commission_type');
        $globalSettingsArray[2]  = $this->getSettingValue('affiliate_settings', 'affiliate_first_purchase_commission_value');
        $globalSettingsArray[3]  = $this->getSettingValue('affiliate_settings', 'affiliate_recurring_purchase_commission_type');
        $globalSettingsArray[4]  = $this->getSettingValue('affiliate_settings', 'affiliate_recurring_purchase_commission_value');
        $globalSettingsArray[5]  = $this->getSettingValue('affiliate_settings', 'affiliate_enable_tier_commission');
        $globalSettingsArray[6]  = $this->getSettingValue('affiliate_settings', 'affiliate_tier_commission_level');
        $globalSettingsArray[7]  = $this->getSettingValue('affiliate_settings', 'affiliate_tier_commission_type');
        $globalSettingsArray[8]  = $this->getSettingValue('affiliate_settings', 'affiliate_tier_commission_value');
        $globalSettingsArray[9]  = $this->getSettingValue('affiliate_settings', 'affiliate_subscription_commission');
        $globalSettingsArray[10] = $this->getSettingValue('affiliate_settings', 'affiliate_subscription_commission_amount');
        $globalSettingsArray[11] = $this->getSettingValue('affiliate_settings', 'affiliate_registeration_commission');
        $globalSettingsArray[12] = $this->getSettingValue('affiliate_settings', 'affiliate_registeration_commission_amount');
        $globalSettingsArray[13] = $this->getSettingValue('affiliate_settings', 'affiliate_bulk_subscriber_import');
        $globalSettingsArray[14] = $this->getSettingValue('affiliate_settings', 'affiliate_bulk_subsc_import_commission');
        $globalSettingsArray[15] = $this->getSettingValue('affiliate_settings', 'affiliate_bulk_user_import');
        $globalSettingsArray[16] = $this->getSettingValue('affiliate_settings', 'affiliate_bulk_user_import_commission');
        $globalCh                = 0;
        $k                       = 2;
        for ($i = 0; $i < count($globalSettingsArray); $i++, $k++) {
            if ($resCommissionSettings[$k] == $globalSettingsArray[$i]) {
                $globalCh = 1;
            } else {
                $globalCh = 0;
                break;
            }
        }
        if (isset($_POST['stateID'])) {
            $resAffiliate['affiliateStateID'] = $_POST['stateID'];
        } //isset($_POST['stateID'])
        $resAffiliate['affiliateStateID'] = isset($resAffiliate['affiliateStateID']) ? $resAffiliate['affiliateStateID'] : '';
        $resAffiliate['affiliateCityID']  = isset($resAffiliate['affiliateCityID']) ? $resAffiliate['affiliateCityID'] : '';
        $this->ObjView->assign('globalCh', $globalCh);
        $this->ObjView->assign('affiliateReqID', $affiliateReqID);
        $this->ObjView->assign('statehidValue', $resAffiliate['affiliateStateID']);
        $this->ObjView->assign('cityhidValue', $resAffiliate['affiliateCityID']);
        $this->ObjView->assign('resCommissionSettings', $resCommissionSettings);
        $this->ObjView->assign("showPrivilege", $this->ObjCommon->hasPrivilege('affiliate/show/'));
        $this->ObjView->display('AffiliateAdd.tpl');
    }
    //ADD A NEW AFFILIATE
    public function newAction() {
        $ObjCountry       = new CountryModel();
        $ObjAffiliate     = new AffiliateModel();
        $ObjProduct       = new ProductModel();
        $ObjEmailtemplate = new EmailtemplateModel();
        $affiliateUserID  = $this->getRequestValue('id');
        $affiliateReqID   = $this->getRequestValue('rid');
        $affiliateID      = $ObjProduct->getRandomCode(6, 'Alphanumerics');
        $languageIDs      = $this->ObjView->languageIDs;
        if ($this->ObjForm->isValid('frmAffiliate', 'submitAffiliate')) {
            $ObjAffiliate->saveAffiliate($_POST, $affiliateUserID, $affiliateID, $affiliateReqID, 1);
            $ObjAffiliate->changeAffiliateRequestStatus($affiliateReqID, 'Approved');
            // sent mail to affiliate with their login crdentials
            $languageIDsCustom            = $languageIDs;
            $languageIDsCustom['Current'] = $_POST['preferredLanguage'];
            $emailbody                    = $ObjEmailtemplate->getEmailTemlateDetails($languageIDsCustom, '', 'affiliate-request-approved');
            $from                         = array(
                $emailbody['emailFromEmail'],
                $emailbody['emailFromName']
            );
            $siteName                     = $this->getSettingValue('site_settings', 'site_name');
            $siteUrl                      = $this->getSettingValue('site_settings', 'global_http_url');
            $companyLogo                  = $this->getSettingValue('company_information', 'company_logo');
            $userName                     = $_POST['affiliateFirstName'] . " " . $_POST['affiliateLastName'];
            $subject                      = $emailbody['emailSubject'];
            $bodytag                      = str_replace('{$siteName}', $siteName, $emailbody['emailHtml']);
            $bodytag                      = str_replace('{$userName}', $userName, $bodytag);
            $bodytag                      = str_replace('{$affiliateLogin}', $_POST['affiliateUserName'], $bodytag);
            $bodytag                      = str_replace('{$affiliatePassword}', $_POST['affiliatePassword'], $bodytag);
            $bodytag                      = str_replace('{$companyLogo}', $companyLogo, $bodytag);
            $bodytag                      = str_replace('{url}', rtrim($siteUrl, "/") . '/affiliate/', $bodytag);
            $this->ObjView->assign('emailbody', $bodytag);
            $this->ObjView->assign('siteUrl', $siteUrl);
            $this->ObjView->assign('siteName', $siteName);
            $this->ObjView->assign('userName', $userName);
            $this->ObjView->assign('companyLogo', $companyLogo);
            $body                           = $this->ObjCommon->fetch("email_templates/Layout.tpl", $languageIDsCustom);
            $mail_settings                  = $this->getSettingValue('mail_settings');
            $mail_settings['smtp_password'] = $this->encryptDecrypt("decrypt", $mail_settings['smtp_password']);
            $ObjMail                        = new Mail($mail_settings);
            $emailID                        = trim(addslashes($_POST['affiliateEmail']));
            $ObjMail->IsHTML();
            $ObjMail->sendMail($from, $emailID, $subject, $body);
            if ($ObjMail->Send()) {
            } //$ObjMail->Send()
            $this->setMessage("language.msgAffiliateAdded", "success");
            $this->setRedirect('/affiliate/index/');
        } //$this->ObjForm->isValid('frmAffiliate', 'submitAffiliate')
        if (isset($_POST['stateID'])) {
            $resAffiliate['affiliateStateID'] = $_POST['stateID'];
        } //isset($_POST['stateID'])
        $resAffiliate['affiliateStateID'] = isset($resAffiliate['affiliateStateID']) ? $resAffiliate['affiliateStateID'] : '';
        $resAffiliate['affiliateCityID']  = isset($resAffiliate['affiliateCityID']) ? $resAffiliate['affiliateCityID'] : '';
        $this->ObjView->assign('statehidValue', $resAffiliate['affiliateStateID']);
        $this->ObjView->assign('cityhidValue', $resAffiliate['affiliateCityID']);
        $this->ObjView->assign('resCountry', $ObjCountry->listCountriesForOption($languageIDs, 'Yes'));
        $this->ObjView->assign('globalCommisionPercentage', $this->getSettingValue('affiliate_settings', 'affiliate_commission_value'));
        $this->ObjView->display('AffiliateAdd.tpl');
    }
    //AFFILIATE DETAILS VIEW
    public function showAction() {
        $ObjAffiliate    = new AffiliateModel();
        $ObjLanguage     = new LanguageModel();
        $affiliateUserID = $this->getRequestValue('id');
        $previousURl     = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
        $history         = $this->getPreviousURL();
        $languageIDs     = $this->ObjView->languageIDs;
        /*For addresss modifier*/
        $this->ObjView->assign('currentLangID', $languageIDs['Current']);
        /*For addresss modifier*/
        $siteUrl = rtrim($this->getSettingValue('site_settings', 'global_http_url'), '/') . '/manage';
        if (strpos($previousURl, '/affiliate/index/') > 0 || !strpos($previousURl, '/affiliate/edit/id/') > 0) {
            $previousURl = str_replace($siteUrl, '', $previousURl);
        } else
            $previousURl = "/affiliate/index/";
        if ($affiliateUserID > 0) {
            $resAffiliates          = $ObjAffiliate->getAffiliateDetails($affiliateUserID, "view", '', $languageIDs, 'admin');
            $languageDetails        = $ObjLanguage->getLanguageDetails($resAffiliates['preferredLanguage']);
            //To get Preferred Language Details
            $resCommissionSettings  = $ObjAffiliate->getAffCommissionSettings($affiliateUserID);
            $resGlobalSettings      = $ObjAffiliate->getAffiliateGlobalSettings('affiliate_settings', 'parent');
            //To get Affiliate Global Settings
            $resGlobalSettingsCount = count($resGlobalSettings);
            for ($i = 0; $i < $resGlobalSettingsCount; $i++) {
                $resGlobalValue[$resGlobalSettings[$i]['settingsKey']] = $resGlobalSettings[$i]['settingsValue'];
            }
            $resAffiliates['languageName'] = $languageDetails['languageName'];
            $this->ObjView->assignValues($resAffiliates);
        } //$affiliateUserID > 0
        //$previousURl               = $this->getPreviousURL();
        $resPayDetails                           = $ObjAffiliate->getAffPaymentDetails($affiliateUserID);
        $resAffiliateOtherSettings               = $ObjAffiliate->getAffiliateOtherDetails($affiliateUserID);
        $resAffiliatePaid                        = $ObjAffiliate->listAffiliatePaymentPaid('', '', $affiliateUserID);
        $resAffiliateNotPaid                     = $ObjAffiliate->listAffiliatePaymentNotPaid('', '', $affiliateUserID);
        $resPerformance                          = $ObjAffiliate->listAffiliatePerformance($affiliateUserID);
        $resWidgetDetails                        = $ObjAffiliate->listWidgetDetails($languageIDs, '', '', $affiliateUserID);
        $languageLabel[]                         = $this->getLanguageValue('lblNew');
        $languageLabel[]                         = $this->getLanguageValue('lblActive');
        $languageLabel[]                         = $this->getLanguageValue('msgApiSuspend');
        $languageLabel[]                         = $this->getLanguageValue('msgApiDelete');
        $resAffiliatePaid[0]['commissionAmount'] = isset($resAffiliatePaid[0]['commissionAmount']) ? $resAffiliatePaid[0]['commissionAmount'] : '';
        $resReferrals                            = $ObjAffiliate->getReferralDetails('', '', $affiliateUserID, '', '');
        $this->ObjView->assign('resReferrals', $resReferrals);
        $this->ObjView->assign('resWidgetDetails', $resWidgetDetails);
        $this->ObjView->assignValues($resAffiliateOtherSettings);
        $this->ObjView->assign('resCommissionSettings', $resCommissionSettings);
        $this->ObjView->assignValues($resGlobalValue);
        $this->ObjView->assign('paidAmount', $resAffiliatePaid[0]['commissionAmount']);
        $this->ObjView->assign('notPaidAmount', isset($resAffiliateNotPaid[0]['commissionAmount']) ? $resAffiliateNotPaid[0]['commissionAmount'] : '');
        $this->ObjView->assign('resPerformance', $resPerformance);
        $this->ObjView->assign('previousURl', $previousURl);
        $this->ObjView->assign('affiliateUserID', $affiliateUserID);
        $this->ObjView->assign('affiliateDetails', $resAffiliates);
        /* Privileges*/
        $this->ObjView->assign("editPrivilege", $this->ObjCommon->hasPrivilege('affiliate/edit/'));
        /* Privileges*/
        $this->ObjView->display('AffiliateView.tpl');
    }
    //AFFILIATE PAYMENT ACTION
    public function paymentAction() {
        $this->paymentpaidAction();
    }
    //AFFILIATE PAYMENT PAID ACTION
    public function paymentpaidAction() {
        $this->ObjCommon->askPrivilege('affiliate/paymentnotpaid/');
        $ObjAffiliate       = new AffiliateModel();
        $settingsDateFormat = $this->getSettingValue("site_settings", "date_format");
        $fromDate           = $this->urlDate($this->getRequestValue('fromDate'), 'get', $settingsDateFormat);
        $toDate             = $this->urlDate($this->getRequestValue('toDate'), 'get', $settingsDateFormat);
        $link               = "fromDate/" . $this->urlDate($fromDate, 'set', $settingsDateFormat) . "/toDate/" . $this->urlDate($toDate, 'set', $settingsDateFormat) . "/";
        if (isset($_POST['submitPaidSearch'])) {
            $link1 = "/affiliate/paymentpaid/";
            if ($_POST['payDate']) {
                $date     = explode(" - ", $this->escape($_POST['payDate']));
                $fromDate = $date[0];
                $toDate   = isset($date[1]) ? $date[1] : '';
            }
            $affiliateUserID = ($_POST['affiliateUserID']);
            $link            = (($fromDate != "") ? "fromDate/" . $this->urlDate($fromDate, 'set', $settingsDateFormat) . "/" : "");
            $link .= (($toDate != "") ? "toDate/" . $this->urlDate($toDate, 'set', $settingsDateFormat) . "/" : "");
            $link .= (($affiliateUserID != "") ? "id/" . $affiliateUserID . "/" : "");
            $redirectLink = $link1 . $link;
            $this->setRedirect($redirectLink);
        } //$this->ObjForm->isValid('formOrderSearch', 'submitPaidSearch')
        $affiliateUserID = ($this->getRequestValue('id'));
        /*assigning from and to values for search*/
        $fromDateNull    = (!$fromDate) ? $this->urlDate($this->getFormattedDate(date("Y-m-") . "01"), 'get', $settingsDateFormat) : $fromDate;
        $toDateNull      = (!$toDate) ? $this->urlDate($this->getFormattedDate(date('Y-m-d')), 'get', $settingsDateFormat) : $toDate;
        $assignFromDate  = $fromDate;
        $assignToDate    = $toDate;
        if ($fromDate == '' && $toDate == '') {
            $assignFromDate = $fromDate = $fromDateNull;
            $assignToDate   = $toDate = $toDateNull;
        } else if ($toDate == '') {
            $toDate = $fromDate;
        }
        $this->ObjView->assign("affiliateUserID", $affiliateUserID);
        $resAffiliatePaid = $ObjAffiliate->listAffiliatePaymentPaid($this->convertDateForSQL($fromDate, $settingsDateFormat), $this->convertDateForSQL($toDate, $settingsDateFormat), $affiliateUserID);
        $resCurrency      = $this->ObjView->_currencies[$this->ObjView->_defaultCurrency];
        $currencySymbol   = ($resCurrency['currencySymbolLeft'] != '') ? $resCurrency['currencySymbolLeft'] : $resCurrency['currencySymbolRight'];
        if (isset($_POST['PaidExport'])) {
            //$resAffliatePayments           =  $resAffiliatePaid;
            $resAffliate_Payments = $resAffiliatePaid;
            $MAX                  = 4; // maximum number of elements
            $header               = array(
                $this->getLanguageValue("lblAffiliateName"),
                $this->getLanguageValue("lblContactEmail"),
                $this->getLanguageValue("lblPhone"),
                $this->getLanguageValue("lblPaidAmount") . " ( " . $currencySymbol . ")"
            );
            foreach ($resAffliate_Payments as &$keyval) {
                $keyval = array_slice($keyval, 0, $MAX);
            } //$resAffliate_Payments as &$keyval
            $ObjCsv = new Csv();
            // $countofarray = count($resAffliatePayments);
            if (!empty($resAffliate_Payments)) {
                $dateTime = date('d_m_Y_H_i_s');
                $data     = $ObjCsv->output($dateTime . '.csv', $resAffliate_Payments, $header);
            } //!empty($resAffliate_Payments)
            else {
                $this->setMessage("language.msgNoPayments", 'error');
                $this->setRedirect();
            }
        } //isset($_POST['paidExport'])
        $link = "fromDate/" . $this->urlDate($fromDate, 'set', $settingsDateFormat) . "/toDate/" . $this->urlDate($toDate, 'set', $settingsDateFormat) . "/";
        $this->ObjView->assign('link', $link);
        /*assigning from and to values for search*/
        if ($assignFromDate && $assignToDate == '') {
            $this->ObjView->assign('payDate', $assignFromDate);
        } else if ($assignFromDate && $assignToDate) {
            $this->ObjView->assign('payDate', $assignFromDate . ' - ' . $assignToDate);
        } else {
            $this->ObjView->assign('payDate', '');
        }
        /* Privileges*/
        $this->ObjView->assign("affaddprivilage", $this->ObjCommon->hasPrivilege('affiliate/new/'));
        /* Privileges*/
        $this->ObjView->assign('date_format', $settingsDateFormat);
        $this->ObjView->assign('listAffiliateOptions', $ObjAffiliate->listAffiliatesForSearch());
        $this->ObjView->assign('resAffiliatePaid', $resAffiliatePaid);
        $this->ObjView->display('AffiliatePaymentPaid.tpl');
    }
    //AFFILIATE PAYMENT ACTION FOR ORDERS
    public function affiliateOrderPaymentPaidAction() {
        $this->ObjCommon->askPrivilege('affiliate/paymentnotpaid/');
        $ObjAffiliate       = new AffiliateModel();
        $settingsDateFormat = $this->getSettingValue("site_settings", "date_format");
        $affiliateUserID    = $this->getRequestValue('id');
        if (isset($_POST['submitPaidSearch'])) {
            $link1 = "/affiliate/affiliateOrderPaymentPaid/id/" . $affiliateUserID . "/";
            if ($_POST['payDate']) {
                $date     = explode(" - ", $this->escape($_POST['payDate']));
                $fromDate = $date[0];
                $toDate   = isset($date[1]) ? $date[1] : '';
            }
            $commissionType = trim($_POST['commissionType']);
            $commissionType = ($commissionType != 'Any' ? $commissionType : '');
            $transactionID  = trim($_POST['transactionID']);
            $link           = ($fromDate != "") ? "fromDate/" . $this->urlDate($fromDate, 'set', $settingsDateFormat) . "/" : "";
            $link .= ($toDate != "") ? "toDate/" . $this->urlDate($toDate, 'set', $settingsDateFormat) . "/" : "";
            $link .= (($transactionID != "") ? "transid/" . $transactionID . "/" : "");
            $link .= (($commissionType != "") ? "commissiontype/" . $commissionType . "/" : "");
            $redirectLink = $link1 . $link;
            $this->setRedirect($redirectLink);
        } //$this->ObjForm->isValid('formOrderSearch', 'submitPaidSearch')
        $commissionType = $this->getRequestValue('commissiontype');
        $transid        = $this->getRequestValue('transid');
        //search variables
        $fromDate       = $this->urlDate($this->getRequestValue('fromDate'), 'get', $settingsDateFormat);
        $toDate         = $this->urlDate($this->getRequestValue('toDate'), 'get', $settingsDateFormat);
        /*assigning from and to values for search*/
        $fromDateNull   = (!$fromDate) ? $this->urlDate($this->getFormattedDate(date("Y-m-") . "01"), 'get', $settingsDateFormat) : $fromDate;
        $toDateNull     = (!$toDate) ? $this->urlDate($this->getFormattedDate(date('Y-m-d')), 'get', $settingsDateFormat) : $toDate;
        $assignFromDate = $fromDate;
        $assignToDate   = $toDate;
        if ($fromDate == '' && $toDate == '') {
            $assignFromDate = $fromDate = $fromDateNull;
            $assignToDate   = $toDate = $toDateNull;
        } else if ($toDate == '') {
            $toDate = $fromDate;
        }
        $this->ObjView->assign("transactionID", isset($transactionID) ? $transactionID : '');
        $languageLabel[]  = $this->getLanguageValue('lblOrder');
        $languageLabel[]  = $this->getLanguageValue('lblRegistration');
        $languageLabel[]  = $this->getLanguageValue('lblSubscription');
        $languageLabel[]  = $this->getLanguageValue('lblImportedUsers');
        $languageLabel[]  = $this->getLanguageValue('lblImportedSubscribers');
        $resAffiliatePaid = $ObjAffiliate->listAffiliateOrderPaymentPaid($affiliateUserID, $this->convertDateForSQL($fromDate, $settingsDateFormat), $this->convertDateForSQL($toDate, $settingsDateFormat), $transid, $commissionType, 'stransId', 'desc', '', $languageLabel);
        $resCurrency      = $this->ObjView->_currencies[$this->ObjView->_defaultCurrency];
        $currencySymbol   = ($resCurrency['currencySymbolLeft'] != '') ? $resCurrency['currencySymbolLeft'] : $resCurrency['currencySymbolRight'];
        if (isset($_POST['paidExport'])) {
            $resAffiliatePayments = $resAffiliatePaid;
            $MAX                  = 7; // maximum number of elements
            $header               = array(
                $this->getLanguageValue("lblType"),
                $this->getLanguageValue("lblTransactionID"),
                $this->getLanguageValue("lblActionDate"),
                $this->getLanguageValue("lblTransactionDate"),
                $this->getLanguageValue("lblSubtotal") . " ( " . $currencySymbol . ")",
                $this->getLanguageValue("lblCommission") . " (%)",
                $this->getLanguageValue("lblCommissionAmount") . " ( " . $currencySymbol . ")"
            );
            $totalOrderTotal      = 0;
            $totalCommissionAmt   = 0;
            foreach ($resAffiliatePayments as $key => $element) {
                $array[$key]        = array_slice($element, 0, $MAX);
                $totalOrderTotal    = $totalOrderTotal + $element['subTotal'];
                $totalCommissionAmt = $totalCommissionAmt + $element['commissionAmount'];
            } //$resAffiliatePayments as $key => $element
            $array[$key + 1]['Total']              = $this->getLanguageValue("lblTotal");
            $array[$key + 1]['id']                 = "";
            $array[$key + 1]['date']               = "";
            $array[$key + 1]['dates']              = "";
            $array[$key + 1]['totalOrders']        = $totalOrderTotal;
            $array[$key + 1]['totalCommission']    = "";
            $array[$key + 1]['totalCommissionAmt'] = $totalCommissionAmt;
            $ObjCsv                                = new Csv();
            if (!empty($resAffiliatePayments)) {
                $dateTime = date('d_m_Y_H_i_s');
                $data     = $ObjCsv->output($dateTime . '.csv', $array, $header);
            } //!empty($resAffiliatePayments)
            else {
                $this->setMessage("language.msgNoPayments", 'error');
                $this->setRedirect();
            }
        } //isset($_POST['paidExport'])
        $date_format = $this->getSettingValue('site_settings', 'date_format');
        $link        = "fromDate/" . $this->urlDate($fromDate, 'set', $settingsDateFormat) . "/toDate/" . $this->urlDate($toDate, 'set', $settingsDateFormat) . "/";
        $this->ObjView->assign('link', $link);
        /*assigning from and to values for search*/
        if ($assignFromDate && $assignToDate == '') {
            $this->ObjView->assign('payDate', $assignFromDate);
        } else if ($assignFromDate && $assignToDate) {
            $this->ObjView->assign('payDate', $assignFromDate . ' - ' . $assignToDate);
        } else {
            $this->ObjView->assign('payDate', '');
        }
        /* Privileges*/
        $this->ObjView->assign("affaddprivilage", $this->ObjCommon->hasPrivilege('affiliate/new/'));
        /* Privileges*/
        $getAffiliate = $ObjAffiliate->getAffiliates('', $affiliateUserID);
        $previousURl  = $this->getPreviousURL();
        $this->ObjView->assign('date_format', $date_format);
        $this->ObjView->assign('affiliateUserID', $affiliateUserID);
        $this->ObjView->assign('affiliateName', $getAffiliate['affiliateName']);
        $this->ObjView->assign('resAffiliatePaid', $resAffiliatePaid);
        $this->ObjView->assign('previousURl', $previousURl);
        $this->ObjView->assign("transactionID", $transid);
        $this->ObjView->assign("commissionType", $commissionType);
        $this->ObjView->display('AffiliateOrderPaymentPaid.tpl');
    }
    //BALANCE PAYMENT ACTION
    public function paymentnotpaidAction() {
        $this->ObjCommon->askPrivilege('affiliate/paymentnotpaid/');
        $ObjAffiliate       = new AffiliateModel();
        $settingsDateFormat = $this->getSettingValue("site_settings", "date_format");
        $link               = "/affiliate/paymentnotpaid/";
        if (isset($_POST['submitSearch'])) {
            if ($_POST['payDate']) {
                $date     = explode(" - ", $this->escape($_POST['payDate']));
                $fromDate = $date[0];
                $toDate   = isset($date[1]) ? $date[1] : '';
            }
            $affiliateUserID = ($_POST['affiliateUserID']);
            $link .= ($fromDate != "") ? "fromDate/" . $this->urlDate($fromDate, 'set', $settingsDateFormat) . "/" : "";
            $link .= ($toDate != "") ? "toDate/" . $this->urlDate($toDate, 'set', $settingsDateFormat) . "/" : "";
            $link .= (($affiliateUserID != "") ? "id/" . $affiliateUserID . "/" : "");
            $this->setRedirect($link);
        }
        //search variables
        $fromDate       = $this->urlDate($this->getRequestValue('fromDate'), 'get', $settingsDateFormat);
        $toDate         = $this->urlDate($this->getRequestValue('toDate'), 'get', $settingsDateFormat);
        /*assigning from and to values for search*/
        $fromDateNull   = (!$fromDate) ? $this->urlDate($this->getFormattedDate(date("Y-m-") . "01"), 'get', $settingsDateFormat) : $fromDate;
        $toDateNull     = (!$toDate) ? $this->urlDate($this->getFormattedDate(date('Y-m-d')), 'get', $settingsDateFormat) : $toDate;
        $assignFromDate = $fromDate;
        $assignToDate   = $toDate;
        if ($fromDate == '' && $toDate == '') {
            $assignFromDate = $fromDate = $fromDateNull;
            $assignToDate   = $toDate = $toDateNull;
        } else if ($toDate == '') {
            $toDate = $fromDate;
        }
        $affiliateUserID = ($this->getRequestValue('id'));
        $this->ObjView->assign('date_format', $settingsDateFormat);
        $this->ObjView->assign("affiliateUserID", $affiliateUserID);
        $resAffiliateNotPaid = $ObjAffiliate->listAffiliatePaymentNotPaid($this->convertDateForSQL($fromDate, $settingsDateFormat), $this->convertDateForSQL($toDate, $settingsDateFormat), $affiliateUserID);
        $resCurrency         = $this->ObjView->_currencies[$this->ObjView->_defaultCurrency];
        $currencySymbol      = ($resCurrency['currencySymbolLeft'] != '') ? $resCurrency['currencySymbolLeft'] : $resCurrency['currencySymbolRight'];
        if (isset($_POST['notPaidExport'])) {
            $resAffiliatePayments = $resAffiliateNotPaid;
            $MAX                  = 4; // maximum number of elements
            $header               = array(
                $this->getLanguageValue("lblAffiliateName"),
                $this->getLanguageValue("lblContactEmail"),
                $this->getLanguageValue("lblPhone"),
                $this->getLanguageValue("lblAffiliateBalance") . " ( " . $currencySymbol . ")"
            );
            foreach ($resAffiliatePayments as &$element) {
                $element = array_slice($element, 0, $MAX);
            } //$resAffiliatePayments as &$element
            $ObjCsv = new Csv();
            if (!empty($resAffiliatePayments)) {
                $dateTime = date('d_m_Y_H_i_s');
                $data     = $ObjCsv->output($dateTime . '.csv', $resAffiliatePayments, $header);
            } //!empty($resAffiliatePayments)
            else {
                $this->setMessage("language.msgNoPayments", 'error');
                $this->setRedirect();
            }
        } //isset($_POST['notPaidExport'])
        $link = "fromDate/" . $this->urlDate($fromDate, 'set', $settingsDateFormat) . "/toDate/" . $this->urlDate($toDate, 'set', $settingsDateFormat) . "/";
        $link = "fromDate/" . $this->urlDate($fromDate, 'set', $settingsDateFormat) . "/toDate/" . $this->urlDate($toDate, 'set', $settingsDateFormat) . "/";
        $this->ObjView->assign('link', $link);
        /*assigning from and to values for search*/
        if ($assignFromDate && $assignToDate == '') {
            $this->ObjView->assign('payDate', $assignFromDate);
        } else if ($assignFromDate && $assignToDate) {
            $this->ObjView->assign('payDate', $assignFromDate . ' - ' . $assignToDate);
        } else {
            $this->ObjView->assign('payDate', '');
        }
        /* Privileges*/
        $this->ObjView->assign("affaddprivilage", $this->ObjCommon->hasPrivilege('affiliate/new/'));
        /* Privileges*/
        $this->ObjView->assign('listAffiliateOptions', $ObjAffiliate->listAffiliatesForSearch());
        $this->ObjView->assign('resAffiliateNotPaid', $resAffiliateNotPaid);
        $this->ObjView->display('AffiliatePaymentNotPaid.tpl');
    }
    // AFFILIATE BALANCE PAYMENT ACTION FOR ORDERS
    public function affiliateOrderPaymentNotPaidAction() {
        $this->ObjCommon->askPrivilege('affiliate/paymentnotpaid/');
        $ObjAffiliate       = new AffiliateModel();
        $affiliateUserID    = $this->getRequestValue('id');
        $settingsDateFormat = $this->getSettingValue("site_settings", "date_format");
        if (isset($_POST['submitSearch'])) {
            $link1 = "/affiliate/affiliateOrderPaymentNotPaid/id/" . $affiliateUserID . "/";
            if ($_POST['payDate']) {
                $date     = explode(" - ", $this->escape($_POST['payDate']));
                $fromDate = $date[0];
                $toDate   = isset($date[1]) ? $date[1] : '';
            }
            $commissionType = ($_POST['commissionType'] != 'Any' ? $_POST['commissionType'] : '');
            $link1 .= ($commissionType) ? 'commissiontype/' . $commissionType . '/' : '';
            $link = ($fromDate != "") ? "fromDate/" . $this->urlDate($fromDate, 'set', $settingsDateFormat) . "/" : "";
            $link .= ($toDate != "") ? "toDate/" . $this->urlDate($toDate, 'set', $settingsDateFormat) . "/" : "";
            $redirectLink = $link1 . $link;
            $this->setRedirect($redirectLink);
        } //$this->ObjForm->isValid('formOrderSearch', 'submitSearch')
        $commissionType = $this->getRequestValue('commissiontype');
        //search variables
        $fromDate       = $this->urlDate($this->getRequestValue('fromDate'), 'get', $settingsDateFormat);
        $toDate         = $this->urlDate($this->getRequestValue('toDate'), 'get', $settingsDateFormat);
        $repName        = $this->decodeUrlString($this->getRequestValue("repname"));
        /*assigning from and to values for search*/
        $fromDateNull   = (!$fromDate) ? $this->urlDate($this->getFormattedDate(date("Y-m-") . "01"), 'get', $settingsDateFormat) : $fromDate;
        $toDateNull     = (!$toDate) ? $this->urlDate($this->getFormattedDate(date('Y-m-d')), 'get', $settingsDateFormat) : $toDate;
        $assignFromDate = $fromDate;
        $assignToDate   = $toDate;
        if ($fromDate == '' && $toDate == '') {
            $assignFromDate = $fromDate = $fromDateNull;
            $assignToDate   = $toDate = $toDateNull;
        } else if ($toDate == '') {
            $toDate = $fromDate;
        }
        $languageLabel[]     = $this->getLanguageValue('lblOrder');
        $languageLabel[]     = $this->getLanguageValue('lblRegistration');
        $languageLabel[]     = $this->getLanguageValue('lblSubscription');
        $languageLabel[]     = $this->getLanguageValue('lblImportedUsers');
        $languageLabel[]     = $this->getLanguageValue('lblImportedSubscribers');
        $resAffiliateNotPaid = $ObjAffiliate->listAffiliateOrderPaymentNotPaid('', '', $affiliateUserID, $this->convertDateForSQL($fromDate, $settingsDateFormat), $this->convertDateForSQL($toDate, $settingsDateFormat), $commissionType, '', '', $languageLabel);
        $resCurrency         = $this->ObjView->_currencies[$this->ObjView->_defaultCurrency];
        $currencySymbol      = ($resCurrency['currencySymbolLeft'] != '') ? $resCurrency['currencySymbolLeft'] : $resCurrency['currencySymbolRight'];
        if (isset($_POST['notPaidExport'])) {
            $resAffiliatePayments = $resAffiliateNotPaid;
            $MAX                  = 5; // maximum number of elements
            $header               = array(
                $this->getLanguageValue("lblType"),
                $this->getLanguageValue("lblActionDate"),
                $this->getLanguageValue("lblSubtotal") . " ( " . $currencySymbol . ")",
                $this->getLanguageValue("lblCommission") . " (%)",
                $this->getLanguageValue("lblCommissionAmount") . " ( " . $currencySymbol . ")"
            );
            $totalOrderTotal      = 0;
            $totalCommissionAmt   = 0;
            foreach ($resAffiliatePayments as $key => $element) {
                // $element = array_slice($element, 0, $MAX);
                $array[$key]        = array_slice($element, 0, $MAX);
                $totalOrderTotal    = $totalOrderTotal + $element['subTotal'];
                $totalCommissionAmt = $totalCommissionAmt + $element['commissionAmount'];
            } //$resAffiliatePayments as $key => $element
            $array[$key + 1]['Total']              = $this->getLanguageValue("lblTotal");
            $array[$key + 1]['date']               = "";
            $array[$key + 1]['totalOrders']        = $totalOrderTotal;
            $array[$key + 1]['totalCommission']    = "";
            $array[$key + 1]['totalCommissionAmt'] = $totalCommissionAmt;
            $ObjCsv                                = new Csv();
            if (!empty($array)) {
                $dateTime = date('d_m_Y_H_i_s');
                $data     = $ObjCsv->output($dateTime . '.csv', $array, $header);
            } //!empty($array)
            else {
                $this->setMessage("language.msgNoPayments", 'error');
                $this->setRedirect();
            }
        } //isset($_POST['notPaidExport'])
        $date_format = $this->getSettingValue('site_settings', 'date_format');
        $link        = "fromDate/" . $this->urlDate($fromDate, 'set', $settingsDateFormat) . "/toDate/" . $this->urlDate($toDate, 'set', $settingsDateFormat) . "/";
        $this->ObjView->assign('link', $link);
        /*assigning from and to values for search*/
        if ($assignFromDate && $assignToDate == '') {
            $this->ObjView->assign('payDate', $assignFromDate);
        } else if ($assignFromDate && $assignToDate) {
            $this->ObjView->assign('payDate', $assignFromDate . ' - ' . $assignToDate);
        } else {
            $this->ObjView->assign('payDate', '');
        }
        /* Privileges*/
        $this->ObjView->assign("affaddprivilage", $this->ObjCommon->hasPrivilege('affiliate/new/'));
        /* Privileges*/
        $getAffiliate = $ObjAffiliate->getAffiliates('', $affiliateUserID);
        $previousURl  = $this->getPreviousURL();
        $this->ObjView->assign('date_format', $date_format);
        $this->ObjView->assign('affiliateUserID', $affiliateUserID);
        $this->ObjView->assign('affiliateName', $getAffiliate['affiliateName']);
        $this->ObjView->assign('resAffiliateNotPaid', $resAffiliateNotPaid);
        $this->ObjView->assign('previousURl', $previousURl);
        $this->ObjView->assign("commissionType", $commissionType);
        $this->ObjView->display('AffiliateOrderPaymentNotPaid.tpl');
    }
    //AFFILIATE ORDER TRANSACTION
    public function affiliateOrderTransactionAction() {
        $this->ObjCommon->askPrivilege('affiliate/paymentnotpaid/');
        $ObjAffiliate       = new AffiliateModel();
        $affiliateUserID    = $this->getRequestValue('id');
        $settingsDateFormat = $this->getSettingValue("site_settings", "date_format");
        //search variables
        $fromDate           = $this->urlDate($this->getRequestValue('fromDate'), 'get', $settingsDateFormat);
        $toDate             = $this->urlDate($this->getRequestValue('toDate'), 'get', $settingsDateFormat);
        if (isset($_POST['submitTransSearch'])) {
            $link1 = "/affiliate/affiliateOrderTransaction/id/" . $affiliateUserID . "/";
            if ($_POST['payDate']) {
                $date     = explode(" - ", $this->escape($_POST['payDate']));
                $fromDate = $date[0];
                if (isset($date[1]))
                    $toDate = $date[1];
            }
            $transactionID = $this->encodeUrlString($_POST['transactionID']);
            $link          = ($fromDate != "") ? "fromDate/" . $this->urlDate($fromDate, 'set', $settingsDateFormat) . "/" : "";
            $link .= ($toDate != "" && isset($toDate)) ? "toDate/" . $this->urlDate($toDate, 'set', $settingsDateFormat) . "/" : "";
            $link .= (($transactionID != "") ? "transid/" . $transactionID . "/" : "");
            $redirectLink = $link1 . $link;
            $this->setRedirect($redirectLink);
        }
        $transid        = $this->decodeUrlString($this->getRequestValue('transid'));
        /*assigning from and to values for search*/
        $fromDateNull   = (!$fromDate) ? $this->urlDate($this->getFormattedDate(date("Y-m-") . "01"), 'get', $settingsDateFormat) : $fromDate;
        $toDateNull     = (!$toDate) ? $this->urlDate($this->getFormattedDate(date('Y-m-d')), 'get', $settingsDateFormat) : $toDate;
        $assignFromDate = $fromDate;
        $assignToDate   = $toDate;
        if ($fromDate == '' && $toDate == '') {
            $assignFromDate = $fromDate = $fromDateNull;
            $assignToDate   = $toDate = $toDateNull;
        } else if ($toDate == '') {
            $toDate = $fromDate;
        }
        $this->ObjView->assign("transactionID", $transid);
        $resAffiliateTrans = $ObjAffiliate->listAffiliateOrderTransaction($affiliateUserID, $this->convertDateForSQL($fromDate, $settingsDateFormat), $this->convertDateForSQL($toDate, $settingsDateFormat), $transid);
        $date_format       = $this->getSettingValue('site_settings', 'date_format');
        $link              = "fromDate/" . $this->urlDate($fromDate, 'set', $settingsDateFormat) . "/toDate/" . $this->urlDate($toDate, 'set', $settingsDateFormat) . "/";
        $this->ObjView->assign('link', $link);
        /*assigning from and to values for search*/
        if ($assignFromDate && $assignToDate == '') {
            $this->ObjView->assign('payDate', $assignFromDate);
        } else if ($assignFromDate && $assignToDate) {
            $this->ObjView->assign('payDate', $assignFromDate . ' - ' . $assignToDate);
        } else {
            $this->ObjView->assign('payDate', '');
        }
        /* Privileges*/
        $this->ObjView->assign("affaddprivilage", $this->ObjCommon->hasPrivilege('affiliate/new/'));
        /* Privileges*/
        $previousURl  = $this->getPreviousURL();
        $getAffiliate = $ObjAffiliate->getAffiliates('', $affiliateUserID);
        $this->ObjView->assign('date_format', $date_format);
        $this->ObjView->assign('affiliateUserID', $affiliateUserID);
        $this->ObjView->assign('affiliateName', $getAffiliate['affiliateName']);
        $this->ObjView->assign('resAffiliateTrans', $resAffiliateTrans);
        $this->ObjView->assign('previousURl', $previousURl);
        $this->ObjView->display('AffiliateOrderTransaction.tpl');
    }
    //PAY AFFILIATE COMMISSION ACTION
    public function transactionAction() {
        $this->ObjCommon->askPrivilege('affiliate/paymentnotpaid/');
        $ObjAffiliate    = new AffiliateModel();
        $commissionIDS   = $this->getRequestValue('orderIDs');
        $commissionIDS   = explode(":", $commissionIDS);
        $status          = $this->getRequestValue('status');
        $affiliateUserID = $this->getRequestValue('affiliateUserID');
        if (isset($_POST['submitTransaction'])) {
            if ($commissionIDS) {
                $getBusinessTransaction = $ObjAffiliate->getAffiliateOrderTransaction($affiliateUserID, $commissionIDS, $_POST, $status);
            } //$commissionIDS            
            echo '<script type="text/javascript">parent.location.reload();$.colorbox.close(); </script>';
            $this->setMessage("language.msgStatus", "success");
            exit;
        }
        $totalCommissionAmount = $ObjAffiliate->totalAmountForAffiliate($commissionIDS);
        $resRollbackOrders     = $ObjAffiliate->listRollbackOrdersForAff($affiliateUserID);
        $resCurrency           = $this->ObjView->_currencies[$this->ObjView->_defaultCurrency];
        $this->ObjView->assign('currencySymbolLeft', $resCurrency['currencySymbolLeft']);
        $this->ObjView->assign('currencySymbolRight', $resCurrency['currencySymbolRight']);
        $this->ObjView->assign('resRollbackOrders', $resRollbackOrders);
        $this->ObjView->assign('totalCommissionAmount', $totalCommissionAmount);
        $this->ObjView->display('AffiliateTransaction.tpl');
    }
    //CANCEL PAYMENT TRANSACTION
    public function transactionCancelAction() {
        $this->ObjCommon->askPrivilege('affiliate/paymentnotpaid/');
        $ObjAffiliate   = new AffiliateModel();
        $transactionIDs = $this->getRequestValue("transactionIDs");
        $transactionIDs = explode(":", $transactionIDs);
        if (isset($_POST['affiliateTransDescription'])) {
            $resCancelAffiliateTransactions = $ObjAffiliate->cancelAffiliateTransactions($transactionIDs, $_POST);
            echo '<script type="text/javascript">parent.location.reload();$.colorbox.close(); </script>';
            $this->setMessage("language.msgPaidBusiness", "success");
            exit;
        } //isset($_POST['affiliateTransDescription'])
        $totalCommissionAmount = $ObjAffiliate->totalCancelledAmountForAffiliate($transactionIDs);
        $this->ObjView->assign('totalCommissionAmount', $totalCommissionAmount);
        $this->ObjView->display('AffiliateTransaction.tpl');
    }
    // TRANSACTION DETAILS 
    public function transactiondetailsAction() {
        $this->ObjCommon->askPrivilege('affiliate/paymentnotpaid/');
        $ObjAffiliate       = new AffiliateModel();
        $transactionid      = $this->getRequestValue("transactionid");
        $settingsDateFormat = $this->getSettingValue("site_settings", "date_format");
        $settingsTimeFormat = $this->getSettingValue("site_settings", "time_format");
        $link               = '';
        // Search
        if (isset($_POST['searchTransaction'])) {
            $commissionType = trim($_POST['commissionType']);
            $commissionType = ($commissionType != 'Any' ? $commissionType : '');
            $link .= (($commissionType != "") ? "commissiontype/" . $commissionType . "/" : "");
            $this->setRedirect('affiliate/transactiondetails/transactionid/' . $transactionid . "/" . $link);
        } //isset($_POST['searchTransaction'])
        else {
            $commissionType = $this->getRequestValue('commissiontype');
        }
        $languageLabel[]      = $this->getLanguageValue('lblOrder');
        $languageLabel[]      = $this->getLanguageValue('lblRegistration');
        $languageLabel[]      = $this->getLanguageValue('lblSubscription');
        $languageLabel[]      = $this->getLanguageValue('lblImportedUsers');
        $languageLabel[]      = $this->getLanguageValue('lblImportedSubscribers');
        $resTransactionAmount = $ObjAffiliate->listAffiliateOrderPaymentPaid('', '', '', $transactionid, $commissionType, '', '', 'Yes', $languageLabel);
        $previousURl          = $this->getPreviousURL();
        $this->ObjView->assign('settingsDateFormat', $settingsDateFormat);
        $this->ObjView->assign('settingsTimeFormat', $settingsTimeFormat);
        $this->ObjView->assign('commissionType', $commissionType);
        $this->ObjView->assign('previousURl', $previousURl);
        $this->ObjView->assign('transactionid', $transactionid);
        $this->ObjView->assign('resTransactionAmount', $resTransactionAmount);
        $this->ObjView->display('AffliateTransactionDetails.tpl');
    }
    //END OF FUNCTION    
    //Start : FUNCTION to import the CSV file having Subscribers details 
    public function importUserAction() {
        $ObjAffiliate = new AffiliateModel();
        if ($this->ObjForm->isValid('user_import', 'submit_import')) {
            $affiliateID = $this->escape($_POST['affiliateID']);
            $ObjCsv      = new Csv();
            if ($_FILES['csvFile']['tmp_name'] != '') {
                $importFile = $_FILES['csvFile']['tmp_name'];
            } else {
                $this->setMessage($this->getLanguageValue('errFile'), 'error');
                $this->setRedirect("affiliate/importuser/");
            }
            $ObjCsv->auto($importFile);
            $resImportSubscribers = $ObjCsv->data;
            if (!empty($resImportSubscribers)) {
                $fields      = array_keys($resImportSubscribers[0]);
                $validFields = array(
                    'userEmail',
                    'userFirstName',
                    'userLastName',
                    'userPhone',
                    'userCity',
                    'userAddress1',
                    'userAddress2',
                    'userZip'
                );
            } else {
                //invalid/empty csv
                $this->setMessage($this->getLanguageValue('errInvalidCsv'), 'error');
                $this->setRedirect("affiliate/importuser/");
            }
            if ($fields != $validFields) //invalid headers
                {
                $this->setMessage($this->getLanguageValue('errInvalidCsvFormat'), 'error');
                $this->setRedirect("affiliate/importuser/");
            } else {
                $campaignName = $this->getSettingValue('third_paty_mail_settings', 'campaign_name');
                //Object declaration : If all the CSV validations completed
                if ($campaignName != '' && $campaignName != 'mail_chimp') {
                    $ObjThirdPartyMail = new ThirdPartyMailModel();
                    $uniqueDate        = date('YmdHis');
                    $campaignListID    = $ObjThirdPartyMail->createListBulkID("AFF_$affiliateID -" . $uniqueDate);
                    $campaignListName  = "AFF_$affiliateID -" . $uniqueDate;
                } else {
                    $campaignListID   = '-';
                    $campaignListName = '-';
                }
                $resImport = $ObjAffiliate->importUsers($affiliateID, $resImportSubscribers, $campaignListID, $campaignListName);
                if ($resImport) {
                    if (count($resImport['successList']) == 0) {
                        $this->setMessage($this->getLanguageValue('msgContactImportFailure'), 'error');
                    } //$resImport['inserted'] == 0 && $resImport['updated'] == 0 && $resImport['failed'] >= 1
                    else {
                        $this->setMessage($this->getLanguageValue('msgContactImprotSuccess') . count($resImport['successList']) . $this->getLanguageValue('msgContactsInserted') . $resImport['updated'] . $this->getLanguageValue('msgContactsUpdated') . $resImport['failed'] . $this->getLanguageValue('msgContactsFailed'), 'success');
                        $this->setRedirect("affiliate/importuser/");
                    }
                }
            }
        }
        $this->ObjView->assign('affiliates', $ObjAffiliate->listAffiliatesForSearch());
        $this->ObjView->assign("listPrivilege", $this->ObjCommon->hasPrivilege('affiliate/importuserlist/'));
        $this->ObjView->display('AffiliateUserImport.tpl');
    }
    //END : FUNCTION importUser
    //Start : FUNCTION to import the CSV file having Subscribers details 
    public function importSubscriberAction() {
        $ObjAffiliate = new AffiliateModel();
        $languageIDs  = $this->ObjView->languageIDs;
        if ($this->ObjForm->isValid('subscriber_import', 'submit_import')) {
            $affiliateID = $this->escape($_POST['affiliateID']);
            $ObjCsv      = new Csv();
            if ($_FILES['csvFile']['tmp_name'] != '') {
                $importFile = $_FILES['csvFile']['tmp_name'];
            } //$_FILES['csvFile']['tmp_name'] != ''
            else {
                $this->setMessage($this->getLanguageValue('errFile'), 'error');
                $this->setRedirect("affiliate/importsubscriber/");
            }
            $ObjCsv->auto($importFile);
            $resImportSubscribers = $ObjCsv->data;
            $fields               = array();
            if (!empty($resImportSubscribers)) {
                $fields      = array_keys($resImportSubscribers[0]);
                $validFields = array(
                    'userEmail',
                    'userPhone'
                );
                if (isset($fields) && $fields === $validFields) {
                    $campaignName = $this->getSettingValue('third_paty_mail_settings', 'campaign_name');
                    //Object declaration : If all the CSV validations completed
                    if ($campaignName != '' && $campaignName != 'mail_chimp') {
                        $uniqueDate        = date('YmdHis');
                        $ObjThirdPartyMail = new ThirdPartyMailModel();
                        $campaignListID    = $ObjThirdPartyMail->createListBulkID("AFF_$affiliateID -" . $uniqueDate);
                        $campaignListName  = "AFF_$affiliateID -" . $uniqueDate;
                    } else {
                        $campaignListID   = '-';
                        $campaignListName = '-';
                    }
                    $resImport = $ObjAffiliate->importAffiliateSubscribers($affiliateID, $resImportSubscribers, $campaignListID, $campaignListName);
                    if ($resImport) {
                        if (count($resImport['successList']) == 0) {
                            $this->setMessage($this->getLanguageValue('msgContactImportFailure'), 'error');
                        } //count($resImport['successList']) == 0
                        else {
                            $this->setMessage($this->getLanguageValue('msgContactImprotSuccess') . count($resImport['successList']) . $this->getLanguageValue('msgContactsInserted') . (count($resImport['existsLists']) + count($resImport['duplicateEmailsList']) + count($resImport['invalidEmailList'])) . $this->getLanguageValue('msgContactsFailed'), 'success');
                            $this->setRedirect("affiliate/importsubscriber/");
                        }
                    } //$resImport
                } else {
                    //invalid header
                    $this->setMessage($this->getLanguageValue('errInvalidCsvFormat'), 'error');
                }
            } else {
                //invalid/empty csv
                $this->setMessage($this->getLanguageValue('errInvalidCsv'), 'error');
            }
            $this->setRedirect("affiliate/importsubscriber/");
        }
        $this->ObjView->assign('affiliates', $ObjAffiliate->listAffiliatesForSearch());
        $this->ObjView->assign("listPrivilege", $this->ObjCommon->hasPrivilege('affiliate/importsubscriberslist/'));
        $this->ObjView->display('AffiliateSubscriberImport.tpl');
    }
    //END : FUNCTION import
    //SAMPLE CSV
    public function ajaxSampleCsvUserAction() {
        $ObjCsv             = new Csv();
        $header             = Array(
            'userEmail',
            'userFirstName',
            'userLastName',
            'userPhone',
            'userCity',
            'userAddress1',
            'userAddress2',
            'userZip'
        );
        $resListSubscribers = array();
        for ($i = 1; $i <= 10; $i++)
            array_push($resListSubscribers, array(
                "mail-$i@domain.com",
                "FirstName-$i",
                "LastName-$i",
                "987456321" . ($i - 1),
                "City-$i",
                "Address1-$i",
                "Address2-$i",
                "68567$i"
            ));
        $data = $ObjCsv->output('example.csv', $resListSubscribers, $header);
    }
    public function ajaxSampleCsvSubscribeAction() {
        $ObjCsv             = new Csv();
        $header             = Array(
            'userEmail',
            'userPhone'
        );
        $resListSubscribers = array();
        for ($i = 1; $i <= 6; $i++)
            array_push($resListSubscribers, array(
                "mail-$i@domain.com",
                "987456329" . ($i - 1)
            ));
        $data = $ObjCsv->output('example.csv', $resListSubscribers, $header);
    }
    //Start : FUNCTION to list the imported users
    public function importUserListAction() {
        $ObjAffiliate = new AffiliateModel();
        $campaignName = $this->getSettingValue('third_paty_mail_settings', 'campaign_name');
        if (isset($_POST['submitSearchList'])) {
            $link          = "affiliate/importUserList";
            $affiliateID   = $this->escape($_POST['affiliateID']);
            $affiliateName = $this->encodeUrlString(trim($_POST['affiliateName']));
            if ($affiliateID)
                $link .= "/id/$affiliateID";
            if ($affiliateName)
                $link .= "/aff/$affiliateName";
            $this->setRedirect("$link/");
        } //isset($_POST['submitSearchList'])
        if (isset($_POST['scheduleSubmitUser'])) {
            if (isset($_POST['scheduleIDUser']) && $_POST['scheduleIDUser'] != '') {
                $shDate = (isset($_POST['scheduleDateUser'])) ? $this->escape($_POST['scheduleDateUser']) : '';
                $this->schedule($_POST['scheduleIDUser'], $shDate, 'user');
                $this->setRedirect();
            }
        }
        $affiliateID   = $this->escape($this->getRequestValue('id'));
        $affiliateName = $this->decodeUrlString($this->getRequestValue('aff'));
        list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
        $resList       = $ObjAffiliate->listImportUser(1, $limitFrom, $limitTo, $affiliateID, $affiliateName);
        $resPagesCount = $this->setPagesCount($key = 'page');
        $affiliates    = $ObjAffiliate->listAffiliatesForSearch();
        foreach ($resList as $key => $res) {
            $resList[$key]['importLog'] = unserialize($resList[$key]['importLog']);
            $resList[$key][10]          = (isset($resList[$key][10]) && $resList[$key][10] != 0) ? unserialize($resList[$key][10]) : 0;
        }
        if ($campaignName == '' || $campaignName == 'mail_chimp') {
            $this->ObjView->assign('mailEnable', 'no');
        } else {
            $this->ObjView->assign('mailEnable', 'yes');
        }
        $this->ObjView->assign('resAffiliateIDs', $affiliates);
        $this->ObjView->assign('affiliateID', $affiliateID);
        $this->ObjView->assign('affiliateName', $affiliateName);
        $this->ObjView->assign('resList', $resList);
        $this->ObjView->assign('date_format', $this->getSettingValue("site_settings", "date_format"));
        $this->ObjView->display('AffiliateImportUsersList.tpl');
    }
    //END : FUNCTION import list
    //Start : FUNCTION to list the imported users
    public function importSubscribersListAction() {
        $ObjAffiliate = new AffiliateModel();
        $campaignName = $this->getSettingValue('third_paty_mail_settings', 'campaign_name');
        if (isset($_POST['submitSearchList'])) {
            $link          = "affiliate/importsubscriberslist";
            $affiliateID   = $this->escape($_POST['affiliateID']);
            $affiliateName = $this->encodeUrlString(trim($_POST['affiliateName']));
            if ($affiliateID)
                $link .= "/id/$affiliateID";
            if ($affiliateName)
                $link .= "/aff/$affiliateName";
            $this->setRedirect("$link/");
        }
        if (isset($_POST['scheduleSubmit'])) {
            if (isset($_POST['scheduleID'])) {
                $shDate = (isset($_POST['scheduleDate'])) ? $this->escape($_POST['scheduleDate']) : '';
                $this->schedule($_POST['scheduleID'], $shDate, 'sub');
                $this->setRedirect();
            }
        }
        $affiliateID   = (int) $this->getRequestValue('id');
        $affiliateName = $this->decodeUrlString($this->getRequestValue('aff'));
        list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
        $resList       = $ObjAffiliate->listImportSubscribers(1, $limitFrom, $limitTo, $affiliateID, $affiliateName);
        $resPagesCount = $this->setPagesCount($key = 'page');
        $affiliates    = $ObjAffiliate->listAffiliatesForSearch();
        foreach ($resList as $key => $res) {
            $resList[$key]['importLog'] = unserialize($resList[$key]['importLog']);
            $resList[$key][10]          = (isset($resList[$key][10]) && $resList[$key][10] != 0) ? unserialize($resList[$key][10]) : 0;
        }
        if ($campaignName == '' || $campaignName == 'mail_chimp') {
            $this->ObjView->assign('mailEnable', 'no');
        } else {
            $this->ObjView->assign('mailEnable', 'yes');
        }
        $this->ObjView->assign('resAffiliateIDs', $affiliates);
        $this->ObjView->assign('affiliateID', $affiliateID);
        $this->ObjView->assign('affiliateName', $affiliateName);
        $this->ObjView->assign('resList', $resList);
        $this->ObjView->assign('date_format', $this->getSettingValue("site_settings", "date_format"));
        $this->ObjView->display('AffiliateImportSubscribersList.tpl');
    }
    //END : FUNCTION import list
    function schedule($bulkID, $campaignDate, $action) {
        $ObjAffiliate = new AffiliateModel();
        if (trim($campaignDate) == '') {
            $campaignDate = date('Y-m-d H:i:s');
        } else {
            $settingsDateFormat = $this->getSettingValue("site_settings", "date_format");
            $campaignDate       = $this->convertDateForSQL($campaignDate, $settingsDateFormat);
        }
        $actionArray = array(
            'sub',
            'user'
        );
        $resExists   = $ObjAffiliate->checkBulkIDScheduled($bulkID);
        if ($bulkID && $campaignDate && in_array($action, $actionArray) && !$resExists['exist']) {
            $Emailtemplate = new EmailtemplateModel();
            $objTimeZone   = new TimezoneModel();
            $languageIDs   = $this->ObjView->languageIDs;
            $siteName      = rtrim($this->getSettingValue('site_settings', 'site_name'), "/");
            $siteUrl       = rtrim($this->getSettingValue('site_settings', 'global_http_url'), "/");
            $companyLogo   = $this->getSettingValue('company_information', 'company_logo');
            //Get list of imported Subcribers and Campaign List ID
            if ($action == 'sub')
                $result = $ObjAffiliate->getImportSubcribers($bulkID);
            else
                $result = $ObjAffiliate->getImportUsers($bulkID);
            $affiliateLangID              = $ObjAffiliate->getAffiliateLanguageID($result[0]['affiliateUserID']);
            $languageIDsCustom            = $languageIDs;
            $languageIDsCustom['Current'] = $affiliateLangID;
            //Array for storing emailID of subscribers
            $emailList                    = array();
            foreach ($result as $res) {
                array_push($emailList, array(
                    'subscEmailID' => $res['subscEmailID']
                ));
                $emails[] = $res['subscEmailID'];
            } //$result as $res
            //Assign campaign List ID into $campaignListID
            $campaignListID  = $result[0]['campaignListID'];
            //Get Email Template
            $resEmailContent = $Emailtemplate->getEmailTemlateDetails($languageIDsCustom, '', 'affiliate-invite');
            //Link in the email body
            if ($action == 'sub')
                $referralLink = $siteUrl . '/referral/affsubsc/';
            else
                $referralLink = $siteUrl . '/referral/affuser/';
            $mailContent = str_replace('{$siteUrl}', $referralLink, $resEmailContent['emailHtml']);
            $mailContent = str_replace('{$siteUrl}', $referralLink, $resEmailContent['emailHtml']);
            $mailContent = html_entity_decode($mailContent);
            $this->ObjView->assign('emailbody', $mailContent);
            $this->ObjView->assign('siteUrl', $siteUrl);
            $this->ObjView->assign('siteName', $siteName);
            $this->ObjView->assign('userName', '');
            $this->ObjView->assign('companyLogo', $companyLogo);
            $body                     = $this->ObjCommon->fetch("email_templates/Layout.tpl", $languageIDsCustom);
            //$settings array provided for Third Party Model, Function Name : scheduleMailList
            $settings['campaignDate'] = $campaignDate;
            $settings['timezone']     = $this->getSettingValue('site_settings', 'default_timezone');
            $settings['timeZoneDiff'] = $objTimeZone->getTimezoneDetails($settings['timezone']);
            $settings['campaign']     = $this->getSettingValue('third_paty_mail_settings', 'campaign_name');
            //Create HTML page using Get template
            $fileName                 = 'userMail_Subscriber.html';
            file_put_contents('public/uploads/temp/' . $fileName, $body);
            //HTML file path for Email Provider
            $fileUrl                   = $siteUrl . '/public/uploads/temp/' . $fileName;
            //OPTION array for Create campaign Function [Campaign Class]
            $options['html_url']       = $fileUrl;
            $options['text_url']       = $fileUrl;
            $options['productTypeKey'] = '';
            if ($action == 'sub')
                $options['title'] = "Confirmation Mail : Subscriber_$bulkID";
            else
                $options['title'] = "Confirmation Mail : User_$bulkID";
            $options['subject']     = $resEmailContent['emailSubject'];
            $options['from_name']   = $resEmailContent['emailFromName'];
            $options['from_email']  = $resEmailContent['emailFromEmail'];
            $options['reply_email'] = $resEmailContent['emailFromEmail'];
            $options['content']     = $body;
            if ($settings['campaign'] == '' || $settings['campaign'] == 'mail_chimp') {
                $mail_settings                  = $this->getSettingValue('mail_settings');
                $mail_settings['smtp_password'] = $this->encryptDecrypt("decrypt", $mail_settings['smtp_password']);
                $ObjMail                        = new Mail($mail_settings);
                $ObjMail->IsHTML();
                foreach ($emails as $emailId) {
                    $ObjMail->AddBCC($emailId);
                }
                $ObjMail->sendMail(array(
                    $options['from_email'],
                    $options['from_name']
                ), '', $options['subject'], $options['content'], '', $options['from_email']);
                if ($ObjMail->Send()) {
                }
                $ObjAffiliate->updateBulkIDStatus($bulkID, $campaignDate);
                $this->setMessage("language.msgNewsletterSent", "success");
            } else {
                $ObjThirdPartyMail  = new ThirdPartyMailModel();
                $options['list_id'] = array(
                    $campaignListID
                );
                //IF $settings['campaign'] == 'constant_contact'
                if ($settings['campaign'] == 'constant_contact') {
                    $options['from_email']    = $this->getSettingValue('third_paty_mail_settings', 'campaign_verified_email');
                    $options['from_email_id'] = $this->getSettingValue('third_paty_mail_settings', 'campaign_verified_email_id');
                } //$settings['campaign'] == 'constant_contact'
                $response = $ObjThirdPartyMail->scheduleMailList($campaignListID, $emailList, $options, $settings);
                if ($response['status'] == 'success') {
                    $ObjAffiliate->updateBulkIDStatus($bulkID, $campaignDate);
                    $this->setMessage("language.lblScheduleSuccess", "success");
                } else {
                    $this->setMessage("language.lblScheduleError", "error");
                }
            }
        } //$bulkID && $campaignDate && $campaignDate && in_array($action, $actionArray)
    }
    //AXAJ ACTION FOR LIST GLOBAL COMMISSION SETTINGS
    public function ajaxGlobalSettingsAction() {
        $val                                    = $_POST['globalVal'];
        $affiliateEnableSalesCommission         = '';
        $firstPurchaseCommissionType            = '';
        $firstPurchaseCommisionValue            = '';
        $recurringPurchaseCommissionType        = '';
        $recurringPurchaseCommissionValue       = '';
        $affiliateTierCommissionLevel           = '';
        $affiliateTierCommissionEnable          = '';
        $affiliateTierCommissionType            = '';
        $affiliateTierCommissionValue           = '';
        $affiliateSubscriptionCommission        = '';
        $affiliateSubscriptionCommissionAmount  = '';
        $affiliateRegisterationCommission       = '';
        $affiliateRegisterationCommissionAmount = '';
        $affiliateBulkSubscriberImport          = '';
        $affiliateBulkSubscImportCommission     = '';
        $affiliateBulkUserImport                = '';
        $affiliateBulkUserImportCommission      = '';
        if ($val == 1) {
            $affiliateEnableSalesCommission         = $this->getSettingValue('affiliate_settings', 'affiliate_enable_sales_commission');
            $firstPurchaseCommissionType            = $this->getSettingValue('affiliate_settings', 'affiliate_first_purchase_commission_type');
            $firstPurchaseCommisionValue            = $this->getSettingValue('affiliate_settings', 'affiliate_first_purchase_commission_value');
            $recurringPurchaseCommissionType        = $this->getSettingValue('affiliate_settings', 'affiliate_recurring_purchase_commission_type');
            $recurringPurchaseCommissionValue       = $this->getSettingValue('affiliate_settings', 'affiliate_recurring_purchase_commission_value');
            $affiliateTierCommissionLevel           = $this->getSettingValue('affiliate_settings', 'affiliate_tier_commission_level');
            $affiliateTierCommissionEnable          = $this->getSettingValue('affiliate_settings', 'affiliate_enable_tier_commission');
            $affiliateTierCommissionType            = $this->getSettingValue('affiliate_settings', 'affiliate_tier_commission_type');
            $affiliateTierCommissionValue           = $this->getSettingValue('affiliate_settings', 'affiliate_tier_commission_value');
            $affiliateSubscriptionCommission        = $this->getSettingValue('affiliate_settings', 'affiliate_subscription_commission');
            $affiliateSubscriptionCommissionAmount  = $this->getSettingValue('affiliate_settings', 'affiliate_subscription_commission_amount');
            $affiliateRegisterationCommission       = $this->getSettingValue('affiliate_settings', 'affiliate_registeration_commission');
            $affiliateRegisterationCommissionAmount = $this->getSettingValue('affiliate_settings', 'affiliate_registeration_commission_amount');
            $affiliateBulkSubscriberImport          = $this->getSettingValue('affiliate_settings', 'affiliate_bulk_subscriber_import');
            $affiliateBulkSubscImportCommission     = $this->getSettingValue('affiliate_settings', 'affiliate_bulk_subsc_import_commission');
            $affiliateBulkUserImport                = $this->getSettingValue('affiliate_settings', 'affiliate_bulk_user_import');
            $affiliateBulkUserImportCommission      = $this->getSettingValue('affiliate_settings', 'affiliate_bulk_user_import_commission');
        } else {
            $ObjAffiliate    = new AffiliateModel();
            $affiliateUserID = $_POST['id'];
            if ($affiliateUserID) {
                $resCommissionSettings                  = $ObjAffiliate->getAffCommissionSettings($affiliateUserID);
                $affiliateEnableSalesCommission         = $resCommissionSettings['enableSalesCommission'];
                $firstPurchaseCommissionType            = $resCommissionSettings['firstPurchaseCommissionType'];
                $firstPurchaseCommisionValue            = $resCommissionSettings['firstPurchaseCommissionValue'];
                $recurringPurchaseCommissionType        = $resCommissionSettings['recurringPurchaseCommissionType'];
                $recurringPurchaseCommissionValue       = $resCommissionSettings['recurringPurchaseCommissionValue'];
                $affiliateTierCommissionLevel           = $resCommissionSettings['tierCommissionLevel'];
                $affiliateTierCommissionEnable          = $resCommissionSettings['enableTierCommission'];
                $affiliateTierCommissionType            = $resCommissionSettings['tierCommissionType'];
                $affiliateTierCommissionValue           = $resCommissionSettings['tierCommissionValue'];
                $affiliateSubscriptionCommission        = $resCommissionSettings['subscriptionCommission'];
                $affiliateSubscriptionCommissionAmount  = $resCommissionSettings['subscriptionCommissionAmount'];
                $affiliateRegisterationCommission       = $resCommissionSettings['registrationCommission'];
                $affiliateRegisterationCommissionAmount = $resCommissionSettings['registrationCommissionAmount'];
                $affiliateBulkSubscriberImport          = $resCommissionSettings['bulkSubscriberImport'];
                $affiliateBulkSubscImportCommission     = $resCommissionSettings['bulkSubscriberImportCommission'];
                $affiliateBulkUserImport                = $resCommissionSettings['bulkUserImport'];
                $affiliateBulkUserImportCommission      = $resCommissionSettings['bulkUserImportCommission'];
            }
        }
        $this->ObjView->assign('affiliateEnableSalesCommission', $affiliateEnableSalesCommission);
        $this->ObjView->assign('firstPurchaseCommissionType', $firstPurchaseCommissionType);
        $this->ObjView->assign('firstPurchaseCommisionValue', $firstPurchaseCommisionValue);
        $this->ObjView->assign('recurringPurchaseCommissionType', $recurringPurchaseCommissionType);
        $this->ObjView->assign('recurringPurchaseCommissionValue', $recurringPurchaseCommissionValue);
        $this->ObjView->assign('affiliateTierCommissionLevel', $affiliateTierCommissionLevel);
        $this->ObjView->assign('affiliateTierCommissionEnable', $affiliateTierCommissionEnable);
        $this->ObjView->assign('affiliateTierCommissionType', $affiliateTierCommissionType);
        $this->ObjView->assign('affiliateTierCommissionValue', $affiliateTierCommissionValue);
        $this->ObjView->assign('affiliateSubscriptionCommission', $affiliateSubscriptionCommission);
        $this->ObjView->assign('affiliateSubscriptionCommissionAmount', $affiliateSubscriptionCommissionAmount);
        $this->ObjView->assign('affiliateRegisterationCommission', $affiliateRegisterationCommission);
        $this->ObjView->assign('affiliateRegisterationCommissionAmount', $affiliateRegisterationCommissionAmount);
        $this->ObjView->assign('affiliateBulkSubscriberImport', $affiliateBulkSubscriberImport);
        $this->ObjView->assign('affiliateBulkSubscImportCommission', $affiliateBulkSubscImportCommission);
        $this->ObjView->assign('affiliateBulkUserImport', $affiliateBulkUserImport);
        $this->ObjView->assign('affiliateBulkUserImportCommission', $affiliateBulkUserImportCommission);
        $this->ObjView->display('AjaxAffiliateGlobalSettings.tpl');
    }
    //Approve Affiliate Request
    public function approveAffiliateRequestAction() {
        $affiliateReqID = $this->getRequestValue('rid');
        $from           = $this->getRequestValue('from');
        if ($from == "list") {
            $this->ObjView->assign("fromSection", "list");
        }
        $this->ObjView->assign("showPrivilege", $this->ObjCommon->hasPrivilege('affiliaterequest/show/'));
        $this->editAction($affiliateReqID);
    }
    //Delete Affiliate
    public function destroyAction() {
        $ObjAffiliate    = new AffiliateModel();
        $affiliateUserID = $this->getRequestValue('id');
        if ($affiliateUserID > 0) {
            $POST['changeStatus'] = "Deleted";
            $changestatus         = $ObjAffiliate->changeAffiliateStatus($POST, $affiliateUserID, $this->ObjCommon->hasPrivilege('affiliate/destroy/'));
            if ($changestatus) {
                $this->setMessage("language.msgAffiliateDelete", "success");
                $this->setRedirect('affiliate/index/');
            }
        }
    }
      public function testNewAction() {
        
       
        echo "done";exit;
        
        $mainarr['224']['Name'] = 'Vacuum Cleaners|223';
        $mainarr['225']['Name'] = 'Irons|223';
        
        $mainarr['227']['Name'] = 'Refrigerators & Freezers|226';
        $mainarr['228']['Name'] = 'Air Conditioners & Coolers|226';
        $mainarr['232']['Name'] = 'Water Coolers & Dispensers|226';
        $mainarr['233']['Name'] = 'Washing Machines|226';
        
        $mainarr['240']['Name'] = 'Perfumes & Fragrances|239';
        $mainarr['241']['Name'] = 'Hair Styling Electronics|239';
        $mainarr['242']['Name'] = 'Skin Care|239';
        $mainarr['243']['Name'] = 'Hair Care|239';
        
        
        
       
        
        
        
        $ObjProductCategory            = new ProductCategoryModel();
        $languageIDs                   = $this->ObjView->languageIDs;
        $suffix                        = $this->getSettingValue('seo_settings', 'category_url_suffix');
        foreach($mainarr as $key=>$rec) { 
            $sp = explode("|",$rec['Name']);
            $_POST['productCategoryName'] = $sp[0];
            $_POST['productCategoryKey']  = $this->ObjCommon->generateKey("catalog", $_POST['productCategoryName'], 0, "unique");
            $urlKey                           = ($_POST['productCategoryKey']) ? $_POST['productCategoryKey'] : $this->ObjCommon->generateKey("catalog", $_POST['productCategoryName'], 0, "unique");
            $_POST['layoutActiveFrom']        = '';
            $_POST['layoutActiveTo']          = '';
            $_POST['pageDefaultView']         = 'products_only';
            $_POST['productGridListLayoutID'] = '';
            $_POST['productDetailsLayoutID']  = '';
            $_POST['numberOfProductCount'] = 'NULL';
            $_POST['productCategoryParent'] = $sp[1];
            $_POST['productCategoryEID']    = $key;
            $_POST['productCategoryStatus'] = !empty($sp[2])?'Inactive':'Active';
            $_POST['productCategoryImage']  = '';
            $_POST['productCategoryIcon']   = '';
            $_POST['productThumbWidth']     = 250;
            $_POST['productThumbHeight']    = 250;
            
            $_POST['productCategoryDescription'] = $_POST['productCategoryName'];
            $_POST['productCategoryMetaTitle']   = $_POST['productCategoryName'];
            $_POST['productCategoryMetaKeywords']= $_POST['productCategoryName'];
            $_POST['productCategoryMetaDescription']= $_POST['productCategoryName'];
            $_POST['productCategoryFooterText']    = '';
            
            $categoryKeyExists = $ObjProductCategory->isProductCatKeyExists($urlKey,0);
            
            if ($categoryKeyExists) {
                $det = $ObjProductCategory->getCategoryInfo($languageIDs,$_POST['productCategoryParent']);
                $urlKey = $det['productCategoryKey']."-".$urlKey;                
            }            
            $rsProductCategory = $ObjProductCategory->submitProductCategory($languageIDs, '', $urlKey);
            if ($rsProductCategory == "ae") {
                $this->setMessage("language.msgDuplicateProductCategoryKey", "error");
                exit;
            } else {
                
                //URL Rewite
                $ObjSef               = new SefModel();
                $ObjSef->_refreshCategoryRewrites($languageIDs['AllList'], $rsProductCategory, $suffix, '', false, $_POST['productCategoryParent'], "insert");
                //END
                
                
            }
            
        }
        echo "done";
        exit;
    }
}