<?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: ReferralsController.php, v 1.0 2011/06/14 20:52:11
//
class ReferralsController extends Controller {
    //Referrals
    public function indexAction() {
        $ObjAffiliate           = new AffiliateModel();
        $affiliateUserID        = $this->ObjSession->getSession("AFFILIATE_USER_ID");
        $resAffiliate           = $ObjAffiliate->getAffDetailsReferral($affiliateUserID);
        $settingsEnableReferral = $this->getSettingValue('referral_settings', 'aff_referral_enable');
        $affReferralDetailCount = $ObjAffiliate->getSourceBasedDetails($affiliateUserID, 'Active', 'Referral', 'count');
        if ($affReferralDetailCount == 0 && $settingsEnableReferral != 'Yes') {
            $this->setRedirect("index/");
            exit;
        }
        $settingsEnableFacebook   = $this->getSettingValue('referral_settings', 'aff_facebook_referral_enable');
        $settingsEnableTwitter    = $this->getSettingValue('referral_settings', 'aff_twitter_referral_enable');
        $settingsEnableGooglePlus = $this->getSettingValue('referral_settings', 'aff_googleplus_referral_enable');
        $settingsEnablePinterest  = $this->getSettingValue('referral_settings', 'aff_pinterest_referral_enable');
        $referralFacebookMessage  = $this->getSettingValue('social_media_settings', 'facebook_aff_referral_message');
        $referralTweetMessage     = $this->getSettingValue('social_media_settings', 'twitter_aff_referral_message');
        $referralPinterestMessage = $this->getSettingValue('social_media_settings', 'pinterest_aff_referral_message');
        $settingsCompanyLogo      = $this->getSettingValue('company_information', 'company_logo');
        $settingsPinterestImage   = $this->getSettingValue('social_media_settings', 'pinterest_aff_share_image');
        $siteUrl                  = rtrim($this->getSettingValue('site_settings', 'global_http_url'), "/");
        $referralLink             = $siteUrl . '/referral/affiliate/' . $resAffiliate['affiliateID'] . "/";
        $sortby                   = $this->escape($this->getRequestValue('sortby'));
        $orderby                  = $this->escape($this->getRequestValue('orderby'));
        $export                   = $this->escape($this->getRequestValue('export'));
        $emailAction              = $this->getRequestValue(1);
        if ($emailAction == 'email') {
            $ObjEmailtemplate = new EmailtemplateModel();
            $languageIDs      = $this->ObjView->languageIDs;
            $senderName       = $this->ObjSession->getSession("AFFILIATE_NAME");
            $this->ObjView->assign('fromName', $senderName);
            $this->ObjView->assign('fromEmail', $resAffiliate['affiliateEmail']);
            //email body
            $emailbody = $ObjEmailtemplate->getEmailTemlateDetails($languageIDs, '', 'affiliate-refer-friend');
            $from      = $emailbody['emailFromName'] . "<" . $emailbody['emailFromEmail'] . ">";
            $subject   = $emailbody['emailSubject'];
            if (isset($_POST['sendEmail'])) {
                if ($this->ObjForm->isValid('formReferaFriend', 'sendEmail')) {
                    // sent mail to user
                    $from        = array(
                        $resAffiliate['affiliateEmail'],
                        $senderName
                    );
                    $subject     = stripslashes($_POST['subject']);
                    $emailbody   = $ObjEmailtemplate->getEmailTemlateDetails($languageIDs, '', 'affiliate-refer-friend');
                    $bodytag     = str_replace('{$referredTo}', '', $emailbody['emailHtml']);
                    $bodytag     = str_replace('{$referredBy}', $senderName, $bodytag);
                    $bodytag     = str_replace('{$referralLink}', $referralLink, $bodytag);
                    $mailContent = $this->getLanguageValue('lblHelo') . ',<br><br>' . $this->getLanguageValue('lblApersonal') . $senderName . '<br><br>';
                    $mailContent .= str_replace(chr(13), "<br>", stripslashes($_POST['emailContent'])) . '<br><br>' . $bodytag;
                    $mailContent = html_entity_decode($mailContent);
                    $this->ObjView->assign('emailbody', $mailContent);
                    $this->ObjView->assign('userName', (isset($userName)) ? $userName : '');
                    $emailID                        = stripslashes($_POST['recipientEmail']);
                    $toemailID                      = explode(",", $emailID);
                    $body                           = $this->ObjCommon->fetch($this->ObjView, "email_templates/Layout.tpl");
                    $mail_settings                  = $this->getSettingValue('mail_settings');
                    $mail_settings['smtp_password'] = $this->encryptDecrypt("decrypt", $mail_settings['smtp_password']);
                    $ObjMail                        = new Mail($mail_settings);
                    $ObjMail->IsHTML();
                    $send = $ObjMail->sendMail(array(
                        $resAffiliate['affiliateEmail'],
                        $senderName
                    ), $toemailID, $subject, $body);
                    if ($ObjMail->Send()) {
                        $this->setMessage("language.msgInvitation", "message_success");
                        echo '<script type="text/javascript">parent.location.reload();parent.$.fn.colorbox.close();
					  </script>';
                        exit;
                    } else {
                        $this->setMessage("language.errSendingMail", "message_error");
                    }
                    //$ObjUser->updateUserLastAccess($userID);
                }
            }
            $this->ObjView->assign('subject', $subject);
            $this->ObjView->assign('referralLink', $referralLink);
            $this->ObjView->display('ReferralEmail.tpl');
            exit;
        }
        list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page', $rows = 10);
        //To set llimit parameters
        if (($sortby == "date") && ($orderby == "asc")) {
            $sortkey = "desc";
        }
        if (($sortby == "date") && ($orderby == "desc")) {
            $sortkey = "asc";
        }
        if (($sortby == "subscription") && ($orderby == "asc")) {
            $sortkey1 = "desc";
        }
        if (($sortby == "subscription") && ($orderby == "desc")) {
            $sortkey1 = "asc";
        }
        if (($sortby == "registration") && ($orderby == "asc")) {
            $sortkey2 = "desc";
        }
        if (($sortby == "registration") && ($orderby == "desc")) {
            $sortkey2 = "asc";
        }
        if (($sortby == "orders") && ($orderby == "asc")) {
            $sortkey3 = "desc";
        }
        if (($sortby == "orders") && ($orderby == "desc")) {
            $sortkey3 = "asc";
        }
        if (($sortby == "revenue") && ($orderby == "asc")) {
            $sortkey4 = "desc";
        }
        if (($sortby == "revenue") && ($orderby == "desc")) {
            $sortkey4 = "asc";
        }
        if ($export == 1) {
            $resReferralsListExport = $ObjAffiliate->getReferralDetails(0, '', $affiliateUserID, $sortby, $orderby);
            $MAX                    = 5; // maximum number of elements
            $header                 = array(
                $this->getLanguageValue('lbldate'),
                $this->getLanguageValue('lblSubscriptions'),
                $this->getLanguageValue('lblRegistrations'),
                $this->getLanguageValue('lblOrders'),
                $this->getLanguageValue('lblRevenue')
            );
            foreach ($resReferralsListExport as &$element) {
                $element = array_slice($element, 0, $MAX);
            }
            $ObjCsv = new Csv();
            if (!empty($resReferralsListExport)) {
                $dateTime = "Referral_Details_" . date('d_m_Y_H_i_s');
                $data     = $ObjCsv->output($dateTime . '.csv', $resReferralsListExport, $header);
            }
        }
        $resReferrals  = $ObjAffiliate->getReferralDetails($limitFrom, $limitTo, $affiliateUserID, $sortby, $orderby);
        //to fetch the details of Referral Details.
        $resPagesCount = $this->setPagesCount($key = 'page');
        //to set page count;
        $this->ObjView->assign('siteUrl', $siteUrl);
        $this->ObjView->assign("referralLink", $referralLink);
        $this->ObjView->assign("settingsEnableFacebook", $settingsEnableFacebook);
        $this->ObjView->assign("settingsEnableTwitter", $settingsEnableTwitter);
        $this->ObjView->assign("settingsEnableGooglePlus", $settingsEnableGooglePlus);
        $this->ObjView->assign("settingsEnablePinterest", $settingsEnablePinterest);
        $this->ObjView->assign("referralFacebookMessage", $referralFacebookMessage);
        $this->ObjView->assign('referralTweetMessage', preg_replace('/\s+/', ' ', str_replace("<br />", '\n', nl2br($referralTweetMessage))));
        $this->ObjView->assign('referralPinterestMessage', preg_replace('/\s+/', ' ', str_replace("<br />", '\n', nl2br($referralPinterestMessage))));
        $this->ObjView->assign('settingsCompanyLogo', $siteUrl . "/" . __DIR_PUBLIC . "/uploads/settings/" . $settingsCompanyLogo);
        $this->ObjView->assign('settingsPinterestImage', $siteUrl . "/" . __DIR_PUBLIC . "/uploads/settings/" . $settingsPinterestImage);
        $this->ObjView->assign('resReferrals', $resReferrals);
        $this->ObjView->assign('sortkey', (isset($sortkey)) ? $sortkey : '');
        $this->ObjView->assign('sortkey1', (isset($sortkey1)) ? $sortkey1 : '');
        $this->ObjView->assign('sortkey2', (isset($sortkey2)) ? $sortkey2 : '');
        $this->ObjView->assign('sortkey3', (isset($sortkey3)) ? $sortkey3 : '');
        $this->ObjView->assign('sortkey4', (isset($sortkey4)) ? $sortkey4 : '');
        $this->ObjView->display('Referrals.tpl');
    }
}