<?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: SubscribeController.php, v 1.0 2011/06/14 20:52:11
//
class SubscribeController extends Controller {
    public function indexAction() {
        $this->setRedirect('/');
    }
    public function ajaxPopupAction() {
        $ObjUser     = new UserModel();
        $languageIDs = $this->ObjView->languageIDs;
        //Validate Email
        $this->validateSubscriberEmail($_POST['subscEmailID']);
        $_POST['subscEmailID'] = trim($_POST['subscEmailID']);
        $email_label           = $this->getLanguageValue("errEmailID");
        $_POST['contactPhone'] = isset($_POST['contactPhone']) ? $_POST['contactPhone'] : '';
        $lblEnterContactNumber = $this->getLanguageValue("lblEnterContactNumber");
        $_POST['contactPhone'] = ($_POST['contactPhone'] == $lblEnterContactNumber) ? '' : $_POST['contactPhone'];
        if ($this->ObjForm->isValid('formCityEmailSubscription', 'submitCityEmail') || $_POST['subscEmailID']!='') {            
            $userDefaultLanguage = $this->ObjSession->getSession("REGISTERED_USER_LANG_ID");
            if ($userDefaultLanguage > 0) {
                $languageIDs['Current'] = $userDefaultLanguage;
            }
            $_POST['languageID'] = $languageIDs['Current'];
            $checkSubscribe      = $ObjUser->isSubscriberEmailExists($_POST['subscEmailID']);
            list($subscribe, $userID) = $ObjUser->saveCitySubscribers($_POST);
            if ($checkSubscribe > 0) {
                //$ObjUser->updateCitySubscribers($_POST);
                $this->setMessage("language.errSubscribeExists", $div_class = "message_error", $section = 'Subscribe', $div_id = 'common_message');
                $this->setRedirect('/');
            } else {
                if ($subscribe) {
                    // Update newsltter status
                    if ($userID) {
                        $ObjUser->updateNewsletterSubscribeStatus($userID, "Yes");
                    }
                    if (__ANALYTICS_MODULE) {
                        //FOR TRACKING VISITOR'S SUBSCRIPTION DETAILS
                        $this->subcribeTracking();
                    }
                    //FOR TRACKING VISITOR'S SUBSCRIPTION DETAILS
                    //SAVE AFFILIATE SUBSCRIPTIION COMMISSION AMOUNT
                    if (__AFFILIATE_MODULE)
                        $this->saveAffiliateSubscribeCommission($subscribe, $_POST['subscEmailID']);
                    // EXTD MAIL START		
                    $email            = $_POST['subscEmailID'];
                    //send mail
                    $ObjEmailtemplate = new EmailtemplateModel();
                    // sent mail to user
                    $emailbody        = $ObjEmailtemplate->getEmailTemlateDetails($languageIDs, '', 'subscription-received-user');
                    $from             = array(
                        $emailbody['emailFromEmail'],
                        $emailbody['emailFromName']
                    );
                    $subject          = $emailbody['emailSubject'];
                    $siteName         = $this->getSettingValue('site_settings', 'site_name');
                    $siteUrl          = $this->getSettingValue('site_settings', 'global_http_url');
                    $companyLogo      = $this->getSettingValue('company_information', 'company_logo');
                    $userName         = $email;
                    $this->ObjView->assign('companyLogo', $companyLogo);
                    //email body
                    $bodytag = $emailbody['emailHtml'];
                    // $bodytag = str_replace('{$city}', $resProductCityKeyID['cityName'], $bodytag);
                    $bodytag = str_replace('{$userName}', $userName, $bodytag);
                    $this->ObjView->assign('emailbody', $bodytag);
                    $this->ObjView->assign('siteUrl', $siteUrl);
                    $this->ObjView->assign('siteName', $siteName);
                    $this->ObjView->assign('companyLogo', $companyLogo);
                    $emailID                        = $email;
                    $body                           = $this->ObjCommon->fetch("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();
                    $ObjMail->sendMail($from, $emailID, $subject, $body);
                    if ($ObjMail->Send()) {
                    }
					
					$emailbody        = $ObjEmailtemplate->getEmailTemlateDetails($languageIDs, '', 'subscription-received-admin');
                    $from             = array(
                        $emailbody['emailFromEmail'],
                        $emailbody['emailFromName']
                    );
                    $subject          = $emailbody['emailSubject'];
                    $siteName         = $this->getSettingValue('site_settings', 'site_name');
                    $siteUrl          = $this->getSettingValue('site_settings', 'global_http_url');
                    $companyLogo      = $this->getSettingValue('company_information', 'company_logo');
                    $userName         = $email;
					$emailID                           = $this->getSettingValue('product_cart_settings', 'subscription_notification_email');
                    
                    $this->ObjView->assign('companyLogo', $companyLogo);
                    //email body
                    $bodytag = $emailbody['emailHtml'];
                    // $bodytag = str_replace('{$city}', $resProductCityKeyID['cityName'], $bodytag);
                    $bodytag = str_replace('{$email}', $userName, $bodytag);
                    $this->ObjView->assign('emailbody', $bodytag);
                    $this->ObjView->assign('siteUrl', $siteUrl);
                    $this->ObjView->assign('siteName', $siteName);
                    $this->ObjView->assign('companyLogo', $companyLogo);
                    //$emailID                        = $email;
                    $body                           = $this->ObjCommon->fetch("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();
					//echo $body;exit;
                    $ObjMail->sendMail($from, $emailID, $subject, $body);
                    if ($ObjMail->Send()) {
                    }
                    if ($this->getSettingValue('third_paty_mail_settings', 'campaign_name') != '') {
                        $this->thirdPartySubscribe($email);
                    } //end of mail
                    $this->ObjCookie->setCookie('SUBSCRIBED_USER', $email, (72 * 3600), "/");
                }
            }
            $this->setMessage("language.msgThanks", $div_class = "success", $section = 'Subscribe', $div_id = 'common_message');
        } else {
            $this->setMessage("language.errEmailID", $div_class = "message_error", $section = 'Subscribe', $div_id = 'common_message');
        }
        $this->setRedirect('/');
    }
    public function ajaxEmailPopupAction() 
	{
               
                $ObjUser = new UserModel();
		$languageIDs = $this->ObjView->languageIDs;
		//Validate Email
                
                $this->validateSubscriberEmail($_POST['subscPopEmailID']);
		$_POST['subscEmailID']=trim($_POST['subscPopEmailID']);
		$email_label=$this->getLanguageValue("lblSubsEmail");
		$_POST['contactPhone']	= isset($_POST['contactPhone'])?$_POST['contactPhone']:'';
		$lblEnterContactNumber=$this->getLanguageValue("lblEnterContactNumber");
		$_POST['contactPhone']	=($_POST['contactPhone']==$lblEnterContactNumber)?'':$_POST['contactPhone'];
                $_POST['submitPopEmail']=isset($_POST['submitPopEmail'])?$_POST['submitPopEmail']:'';
                
        if ($_POST['subscPopEmailID']!='') {
                
		$userDefaultLanguage                 = 	$this->ObjSession->getSession("REGISTERED_USER_LANG_ID");
		if($userDefaultLanguage>0)
		{
			$languageIDs['Current'] = $userDefaultLanguage;
		}
		$_POST['languageID']    =   $languageIDs['Current'];
		$checkSubscribe	= $ObjUser->isSubscriberEmailExists($_POST['subscPopEmailID']);
                list($subscribe,$userID) = $ObjUser->saveCitySubscribers($_POST);
		if($checkSubscribe>0){
			//$ObjUser->updateCitySubscribers($_POST);
    		$this->setMessage("language.errSubscribeExists", $div_class = "message_error", $section = 'Subscribe', $div_id = 'common_message');
            $this->setRedirect('/');
    	}else {
			
            if ($subscribe) {
                // Update newsltter status
				if($userID){
                 $ObjUser->updateNewsletterSubscribeStatus($userID, "Yes");
				}
				if(__ANALYTICS_MODULE){
				//FOR TRACKING VISITOR'S SUBSCRIPTION DETAILS
				$this->subcribeTracking();
				}
				//FOR TRACKING VISITOR'S SUBSCRIPTION DETAILS
				//SAVE AFFILIATE SUBSCRIPTIION COMMISSION AMOUNT
				if(__AFFILIATE_MODULE)
                	$this->saveAffiliateSubscribeCommission($subscribe,$_POST['subscEmailID']);	
 				// EXTD MAIL START		
                $email = $_POST['subscEmailID'];
                //send mail
                $ObjEmailtemplate = new EmailtemplateModel();
                // sent mail to user
                $emailbody = $ObjEmailtemplate->getEmailTemlateDetails($languageIDs, '', 'deal-subscription-received');
                $from = array($emailbody['emailFromEmail'],$emailbody['emailFromName']);
                $subject = $emailbody['emailSubject'];
                $siteName = $this->getSettingValue('site_settings', 'site_name');
                $siteUrl = $this->getSettingValue('site_settings', 'global_http_url');
                $companyLogo = $this->getSettingValue('company_information', 'company_logo');
                $userName = $email;
                $this->ObjView->assign('companyLogo', $companyLogo);
                //email body
                $bodytag = $emailbody['emailHtml'];
               // $bodytag = str_replace('{$city}', $resDealCityKeyID['cityName'], $bodytag);
                $bodytag = str_replace('{$userName}', $userName, $bodytag);
                $this->ObjView->assign('emailbody', $bodytag);
                $this->ObjView->assign('siteUrl', $siteUrl);
                $this->ObjView->assign('siteName', $siteName);
                $this->ObjView->assign('companyLogo', $companyLogo);
                $emailID = $email;
                $body = $this->ObjCommon->fetch("email_templates/Layout.tpl");
                $mail_settings = $this->getSettingValue('mail_settings');
                $ObjMail = new Mail($mail_settings);
                $ObjMail->IsHTML();
                $ObjMail->sendMail($from, $emailID, $subject, $body);
                if ($ObjMail->Send()) {
                }
			if($this->getSettingValue('third_paty_mail_settings', 'campaign_name')!=''){
                
				$this->thirdPartySubscribe($email);
			}    //end of mail
                $this->ObjCookie->setCookie('SUBSCRIBED_USER', $email,(72*3600),"/");
            }
		}	
		$this->setMessage("language.msgThanks", $div_class = "success", $section = 'Subscribe', $div_id ='common_message');
	   }else{ //echo "<pre>";print_r($this->ObjForm->ObjValidate->ValidateResult);exit;
			 $this->setMessage("language.errEmailID", $div_class = "message_error", $section = 'Subscribe', $div_id = 'common_message');
		}
		$this->setRedirect('/'); 
    }
   
    //Function to third party subscribe
    private function thirdPartySubscribe($email) {
        $ObjMail = new ThirdPartyMailModel();
        $res     = $ObjMail->thirdPartySubscribe($email);
    }
    public function mailChipWebhookAction() {
        $ObjUser     = new UserModel();
        $my_key      = 'Ph3RwB8qRKGYTE5q';
        $request_key = $this->getRequestValue('key');
        if ($my_key = $request_key) {
            switch ($_POST['type']) {
                case 'subscribe':
                    break;
                case 'unsubscribe':
                    $email   = $_POST['data']['email'];
                    $list_id = $_POST['data']['list_id'];
                    $ObjUser->webhookTriggeredUnsubscribe($email, $list_id);
                    break;
                case 'cleaned':
                    break;
                case 'upemail':
                    break;
                case 'profile':
                    break;
            }
        }
    }
    /**
     * function campaignMonitorWebhookAction
     * created  : 13/4/2012 : 11:56 AM
     * @author  : Sijo
     * Update unsubscribed user to database from Campaign monitor Webhook POST 
     * This url is set through  API as webhook url for each list in Campaign monitor
     * Sampl webhook url : http://example.com/subscribe/campaignmonitorwebhook/key/Ph3RwB8qRKGYTE5q/
     * Sample JSON POST varibles
     {
     "Events": [
     {
     "CustomFields": [
     {
     "Key": "website", 
     "Value": "http:\/\/example.org"
     }
     ],
     "Date": "2010-12-14 11:32:00",
     "EmailAddress": "test@example.org",
     "Name": "Test Subscriber",
     "Type": "Deactivate",
     "State": "Unsubscribed"
     }
     ],
     "ListID": "96c0bbdaa54760c8d9e62a2b7ffa2e13"
     }
     */
    public function campaignMonitorWebhookAction() {
        $ObjUser     = new UserModel();
        $my_key      = 'Ph3RwB8qRKGYTE5q';
        $request_key = $this->getRequestValue('key');
        if ($my_key = $request_key) {
            $data = json_decode(file_get_contents("php://input"), true);
            foreach ($data['Events'] as $data1) {
                if ($data['ListID'] && $data1['EmailAddress'] && $data1['Type'] == 'Deactivate')
                    $ObjUser->webhookTriggeredUnsubscribe($data1['EmailAddress'], $data['ListID']);
            }
        }
    }
    public function subcribeTracking() {
        $ObjLog            = new AnalyticsModel();
        $visitorID         = $this->ObjCookie->getCookie("GT_VISITORID");
        $visitorDetailsArr = $ObjLog->getDetails($visitorID);
        $visitorSubStatus  = $visitorDetailsArr['doneSubscribe'];
        if (!$visitorSubStatus || $visitorSubStatus == '0') {
            $ObjLog->updateVisitorActions($visitorID, 'subscribe');
        }
    }
    public function saveAffiliateSubscribeCommission($subscribe, $email) {
        $ObjAffiliate       = new AffiliateModel();
        $resSubscriberExist = $ObjAffiliate->affiliateSubscriberExist($email);
        if ($resSubscriberExist == 0 && __AFFILIATE_ENABLE) {
            $visitorID            = $this->ObjCookie->getCookie("GT_VISITORID");
            $affiliateUserID      = $this->ObjCookie->getCookie("affiliateUserID");
            $subscribe_enable     = $this->getSettingValue('affiliate_settings', 'affiliate_subscription_commission');
            $individualCommission = $ObjAffiliate->getAffCommissionSettings($affiliateUserID, 'subscription');
            $affiliate_active     = $ObjAffiliate->getAffiliateStatus($affiliateUserID);
            $resVisitorID         = $ObjAffiliate->getAffVisitorID($visitorID);
            $affVisitorID         = $resVisitorID['affVisitorID'];
            if (($affiliate_active['affiliateStatus'] == 'Active') && ($subscribe_enable == 'Yes') && ($individualCommission['subscriptionCommission'] == 'Yes') && ($individualCommission['subscriptionCommissionAmount'] > 0)) {
                $subscribeAmount        = $individualCommission['subscriptionCommissionAmount'];
                $resAffiliateCommission = $ObjAffiliate->saveCommissionDetails($affVisitorID, $affiliateUserID, $subscribeAmount, 'Subscription', $subscribe);
            }
            //save Aff Performance
            $ObjAffiliate->saveAffiliatePerformance($visitorID, $subscribe, 'Subscription');
        }
    }
    public function validateSubscriberEmail($email) {
        if ($this->getSettingValue('security_settings', 'verify_email_using') != "disabled" && $email != '') {
            $sender            = $this->getSettingValue('site_settings', 'global_notification_email');
            $security_settings = $this->getSettingValue('security_settings');
            $validateEmail     = new Validateemail($security_settings);
            $valid             = $validateEmail->validate($email, $sender);
            if (!$valid) {
                $this->setMessage("language.errValidEmail", $div_class = "error", $section = 'Subscribe', $div_id = 'invalid_email');
                $this->setRedirect("/");
                exit;
            }
        }
    }
}