<?php



/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: 			*/



// +----------------------------------------------------------------------+



// | PHP version 4/5                                                      |



// +----------------------------------------------------------------------+



// | Copyright (c) 2004-2010 ARMIA INC                                    |



// +----------------------------------------------------------------------+



// | This source file is a part of iScripts VistaCart                     |



// +----------------------------------------------------------------------+



// | Authors: Jipson<jipson.thomas@armiasystems.com>             		  |



// +----------------------------------------------------------------------+



App::import('Sanitize');



class NewslettersController extends AppController



{



    var $name = "Newsletter";



    var $helpers = array('Html', 'Form','Pagination','Javascript','Fck');   



	var $components = array ('Pagination','Catmenu','Streamsend'); // Added



	var $uses = array('Newsletter','Newsletteruser','SentNewsletter','Currency','Cart','Category','User','Cart');



	var $paginate = array('limit' => 25,'order' => array('Newsletter.title' => 'asc'));



    function index()



    {


$cnfg 				=	Configure::read('Neutrino');
        $style				=	$cnfg["style"];
        $this->set('style', "admin/".$style);
      $this->__validateLoginStatus();



		$admsess	=	$this->Session->read('Admin');



		if($admsess["newsletter"] <> 1){



		 	$this->redirect(array('controller' => 'admins', 'action' => 'index')); 



			exit();



		}



	   $cmbSearchType	=	"";



		$txtSearch		=	"";



		if(isset($_GET["cmbSearchType"]) && isset($_GET["txtSearch"])){



			$cmbSearchType	=	$_GET["cmbSearchType"];



			$txtSearch		=	$_GET["txtSearch"];



			if($cmbSearchType == "title"){



				$data = $this->paginate('Newsletter', array('Newsletter.title LIKE ' => "%".addslashes($txtSearch)."%"));



			}elseif($cmbSearchType == "content"){



				$data = $this->paginate('Newsletter', array('Newsletter.content LIKE ' => "%".addslashes($txtSearch)."%"));



			}else{



				$data = $this->paginate('Newsletter');



			}



		}else{



			$data = $this->paginate('Newsletter');



		}



		$this->set('cmbSearchType', $cmbSearchType);



		$this->set('txtSearch', $txtSearch);



		$this->set('newsletter', $data);



		$this->passedArgs['limit']=$this->paginate["limit"];



		$this->set('passedarg',$this->passedArgs);



		$this->layout = 'adm';



    } 



	



	function beforeFilter()



    {



        if (isset($this->Setting) && !empty($this->Setting->table))  



        {  



             $this->Setting->load();  



        } 



		global $sitefolder; 



		global $meta_description;



		global $meta_keywords;



		global $page_title;



		global $currency;



		$cnfg 				=	Configure::read('Neutrino');



		$sitefolder			=	$cnfg["sitebasefolder"];



		$currency			=	$cnfg["currency"];



		$meta_description	=	$cnfg["meta_description"];



		$meta_keywords		=	$cnfg["meta_keywords"];



		$page_title			=	$cnfg["page_title"];



		global $style; 



		$style				=	$cnfg["style"];



		$this->set('style', $style);



		$this->set('meta_description', $meta_description);



		$this->set('meta_keywords', $meta_keywords);



		$this->set('page_title_for_layout', $page_title);



		$this->pageTitle = $page_title	; 



		$this->set('cnfg',$cnfg);		



		$curr_action=$this->params['action'];



		if($curr_action=='index')



		$this->paginate["limit"]=$cnfg["items_perpage"]; //Setting pagination limit per page.//get cart count

                 //get cart count
                $sus = $this->Session->read();
                if ($this->Session->check('Userlog') === true) {
                   $userid = $sus["Userlog"]["id"];
                    $cartCount = $this->Cart->getCartCount($userid,'user');
                }else {
                  $sessid = $this->Session->id();
                    $cartCount = $this->Cart->getCartCount($sessid,'G');
                }
                $this->set('cartcount',$cartCount);




    }



	function beforeRender()



    {



			 global $currency;



		   //Code Added By shyam for Category Menu Listing starts here..



		// $lst	=	$this->Category->findAll();
                 $lst	=	$this->Category->findAll(null, NULL, 'Category.cname ASC', null, null);


		 foreach($lst as $det)



		 $menu_array[$det["Category"]["id"]] = array('name' => $det["Category"]["cname"],'parent' => $det["Category"]["parent_id"]);



		 $this->set('menu_array', $menu_array);		



		//Code Added By shyam for Category Menu Listing ends here..



		 //Code for Fetching Cart items Count starts here..



					 $sus		=	$this->Session->read();		



			 if($this->Session->check('Userlog') === true){



				$userid=$sus["Userlog"]["id"];



				$sessid	=	$this->Session->id();



				$cupdate	=	$this->Cart->updatesessuser($sessid,$userid);



				$citem	=	$this->Cart->findAllByUserId($userid);				



				$tot_price	=	0;



				$tot_qty	=	0;



				foreach($citem as $val)



				{



											



							if($val["Cart"]["discount_type"]=='per')



							 {			 



								if($val["Cart"]["discount"] > 0 && $val["Cart"]["discount"] <> '')



								{



								   $combined_price=$val["Cart"]["product_price"]+$val["Cart"]["extra_price"];



								   $discounted_price=($combined_price-(($combined_price * $val["Cart"]["discount"])/100));



								   $tot_price += ($discounted_price)*$val["Cart"]["quantity"];	



								   $tot_qty	 +=  $val["Cart"]["quantity"];	  



								}



							 }



							 else if($val["Cart"]["discount_type"]=='amnt')



							 {



								if($val["Cart"]["discount"] > 0 && $val["Cart"]["discount"] <> '')



								{



								   $tot_price += ($val["Cart"]["extra_price"]+$val["Cart"]["discount"])*$val["Cart"]["quantity"];			



								   $tot_qty	 +=  $val["Cart"]["quantity"];	     



								}



							 }



							else



							{



							   $tot_price	+=	($val["Cart"]["product_price"]+$val["Cart"]["extra_price"])*$val["Cart"]["quantity"];



							    $tot_qty	 +=  $val["Cart"]["quantity"];	  



							} 	



					 



				}	



			  $this->set('tot_price', $tot_price); 



			 // print_r($citem);exit();



			  $this->set('cartitems_cnt',$tot_qty);



			   $curr		=	$this->Currency->findByCode($currency);



		      $this->set('curlogo',utf8_encode($curr["Currency"]["logo"]));   				



			}



			else{



				$sessid	=	$this->Session->id();



				$citem	=	$this->Cart->findAllBySessId($sessid);				



				$this->set('cartitems_cnt', count($citem));



						$tot_price	=	0;



						$tot_qty	=	0;



				foreach($citem as $val)



				{



											



							if($val["Cart"]["discount_type"]=='per')



							 {			 



								if($val["Cart"]["discount"] > 0 && $val["Cart"]["discount"] <> '')



								{



								   $combined_price=$val["Cart"]["product_price"]+$val["Cart"]["extra_price"];



								   $discounted_price=($combined_price-(($combined_price * $val["Cart"]["discount"])/100));



								   $tot_price += ($discounted_price)*$val["Cart"]["quantity"];		



								    $tot_qty	 +=  $val["Cart"]["quantity"];	  	   



								}



							 }



							 else if($val["Cart"]["discount_type"]=='amnt')



							 {



								if($val["Cart"]["discount"] > 0 && $val["Cart"]["discount"] <> '')



								{



								   $tot_price += ($val["Cart"]["extra_price"]+$val["Cart"]["discount"])*$val["Cart"]["quantity"];			



								    $tot_qty	 +=  $val["Cart"]["quantity"];	     



								}



							 }



							else



							{



							   $tot_price	+=	($val["Cart"]["product_price"]+$val["Cart"]["extra_price"])*$val["Cart"]["quantity"];



							    $tot_qty	 +=  $val["Cart"]["quantity"];	  



							} 	



					 



				}	



			  $this->set('tot_price', $tot_price); 



			  $this->set('cartitems_cnt',$tot_qty);



			  $curr		=	$this->Currency->findByCode($currency);



		      $this->set('curlogo',utf8_encode($curr["Currency"]["logo"]));  



			}  



		//Code for Fetching Cart items Count ends here..		







    }



	function subscribe()



	{



	      if (!empty($this->data)) {



		    $this->data["Newsletter"]["sub_date"]=date('Y-m-d h:i:s');



		    if ($this->Newsletter->save($this->data)) {



					$this->Session->setFlash(__('Thanks for Subscribing!', true));



					$this->redirect(array('controller' => 'newsletters', 'action' => 'subscribe')); 			



					exit;



				}



		}



		  $this->layout = 'user_log'; 



	}



	



	 function __validateLoginStatus()



    {



            if($this->Session->check('Admin') == false)



            {



                 $this->redirect(array('controller' => 'admins', 'action' => 'login')); 



                $this->Session->setFlash(__('The URL you\'ve followed requires you login.'));



            }



    }  



	



	function add() {

		$this->__validateLoginStatus();
                $cnfg 				=	Configure::read('Neutrino');
        $style				=	$cnfg["style"];
        $this->set('style', "admin/".$style);

		$admsess	=	$this->Session->read('Admin');

		if($admsess["newsletter"] <> 1){



		 	$this->redirect(array('controller' => 'admins', 'action' => 'index')); 



			exit();



		}



		if (!empty($this->data)) {



		        $this->data["Newsletter"]["news_date"]= date('Y-m-d h:i:s');                       

				if ($this->Newsletter->save($this->data)) {



					$this->Session->setFlash(__('Newsletter has been saved successfully!', true));



			        $this->redirect(array('controller' => 'newsletters','action'=>'index'));



					exit;



				}



		}



		$this->layout = 'adm';



	}



	



	



	function edit($id='') {

$cnfg 				=	Configure::read('Neutrino');
        $style				=	$cnfg["style"];
        $this->set('style', "admin/".$style);

		if(!isset($id) || $id == ''){



			$this->redirect(array('controller' => 'newsletters','action'=>'index'));



			exit();



		}



		$this->__validateLoginStatus();



		$admsess	=	$this->Session->read('Admin');



		if($admsess["newsletter"] <> 1){



		 	$this->redirect(array('controller' => 'admins', 'action' => 'index')); 



			exit();



		}



		$this->Newsletter->id = $id; 



		if (!empty($this->data)) {



			$this->data["Newsletter"]["news_date"]= date('Y-m-d h:i:s');



				if($this->Newsletter->save($this->data)) {



					$this->Session->setFlash(__('Newsletter has been updated successfully!', true));



			        $this->redirect(array('controller' => 'newsletters','action'=>'index'));



					exit;



				}



		}else{



			$this->data = $this->Newsletter->read();			



		}



		$this->layout = 'adm';



	} 



		



	function sendNewsletter($id=''){            
            $cnfg 		= Configure::read('Neutrino');
            if(trim($_SERVER['HTTP_HOST']) == 'localhost'){ 
                include_once("../phpmailer/class.phpmailer.php");
            }else{
                include_once($_SERVER["DOCUMENT_ROOT"].$cnfg["sitebasefolder"]."/app/phpmailer/class.phpmailer.php");
            }

            if(!isset($id) || $id == ''){
                $this->redirect(array('controller' => 'newsletters','action'=>'index'));
                exit();
            }
            $this->__validateLoginStatus();

            $admsess	= $this->Session->read('Admin');
            
            if($admsess["newsletter"] <> 1){
                $this->redirect(array('controller' => 'admins', 'action' => 'index')); 
                exit();
            }



		



		           //Setting the Newsletter Contents..



				    $cnfg 			=	Configure::read('Neutrino');



					$subject 		= "Newsletter";



					$headers 		= "From: ".$cnfg["site_name"]."<".$cnfg["admin_email"].">\r\n";



					$headers 		.= "MIME-Version: 1.0\r\n";



					$headers 		.= "Content-type: text/html; charset=iso-8859-1\r\n";



					$news 			= 	$this->Newsletter->findById($id);



					$path			=	"SiteLogo_disp.gif";






				   



				   



				    $subscribers	= $this->Newsletteruser->find('all', array('conditions' => array('Newsletteruser.status = "Y"')));					

					

					foreach($subscribers as $recepients)



					{


					$mailcontent			=	"<table width='90%'  border='0' cellspacing='2' cellpadding='2' align='center'>



		            <tr><td><a href='".FULL_BASE_URL. $cnfg["sitebasefolder"]."' target='_blank'><img src='".FULL_BASE_URL. $cnfg["sitebasefolder"]."/app/webroot/".IMAGES_URL.$path."' border='0'></a></td></tr></table>";



					//$cnfg["site_name"]	=	"<a href='".FULL_BASE_URL. $cnfg["sitebasefolder"]."' target='_blank'>".$cnfg["site_name"]."</a>";



					$logurl			=	"<a href='".FULL_BASE_URL. $cnfg["sitebasefolder"]."/users/login' target='_blank'>Click here to login</a>";

$mailcontent	=	$mailcontent."Hello [VARIABLEUSERNAME] ,<br>";

					$mailcontent	=	$mailcontent.$news["Newsletter"]["title"]."<br>";



					$mailcontent	=	$mailcontent.$news["Newsletter"]["content"];
                                        $mailcontent	=	$mailcontent."<p>&nbsp;</p>
                                                                Thanks and Regards,<br>
                                                                Administrator [SITE_NAME]";



				   //Setting the Newsletter Contents..
$mailcontent = str_replace("[VARIABLEUSERNAME]",$recepients["Newsletteruser"]["uname"],$mailcontent);
$mailcontent = str_replace("[SITE_NAME]",$cnfg["site_name"],$mailcontent);
						 //$mailsent 		= mail($recepients["Newsletteruser"]["email"],$subject,$mailcontent,$headers);	

                /*#################################### EMAIL SEGMENT ###############################*/
                    $site_name      = "";
                    $admin_email    = "";
                    if(trim($cnfg["site_name"]) <> ""){
                        $site_name  = trim($cnfg["site_name"]);                            
                    }else{
                        $site_name = $cnfg["smtp_user"];                            
                    }  
                    if(trim($cnfg["admin_email"]) <> ""){
                        $admin_email = trim($cnfg["admin_email"]);
                    }else{
                        $admin_email = $cnfg["smtp_user"];
                    }
                    /******************************* MAIL TO THE USER ****************************/
                    $mail             = new PHPMailer(true);                
                    $body             = trim($mailcontent);
                    //$body           = eregi_replace("[\]",'',$body);
                    $mail->IsSMTP(); 
                    $mail->SMTPSecure = 'tls';
                    //$mail->SMTPDebug  = 2;                    
                    $mail->SMTPAuth   = true;  
                    
                    $mail->Host       = $cnfg["smtp_host"]; 
                    $mail->Port       = $cnfg["smtp_port"];   
                    $mail->Username   = $cnfg["smtp_user"];
                    $mail->Password   = $cnfg["smtp_password"];      
                    $mail->SetFrom($admin_email,$site_name);
                    //$mail->AddReplyTo($admin_email,$site_name);
                    $mail->Subject    = $subject;
                    $mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
                    $mail->MsgHTML($body);                    
                    $mail->AddAddress($recepients["Newsletteruser"]["email"], ""); 
                    $mail->Send();
                    /******************************* MAIL TO THE USER ****************************/ 

                /*#################################### EMAIL SEGMENT ###############################*/



					     $this->SentNewsletter->create($send = array());		

						 	

						 $send["newsletter_id"]	=	$id;



			             $send["user_id"]		=	$recepients["Newsletteruser"]["id"];



						 $send["send_date"]		=    date('Y-m-d h:i:s');                       



					     $this->SentNewsletter->save($send)	;



						 unset($send);



				    }  



					$this->Session->setFlash(__('Newsletter has been sent successfully!', true));



			        $this->redirect(array('controller' => 'newsletters','action'=>'index'));







	}



	


	function sendRetail($id='')
	{	  
            
            $cnfg 		= Configure::read('Neutrino');
            if(trim($_SERVER['HTTP_HOST']) == 'localhost'){ 
                include_once("../phpmailer/class.phpmailer.php");
            }else{
                include_once($_SERVER["DOCUMENT_ROOT"].$cnfg["sitebasefolder"]."/app/phpmailer/class.phpmailer.php");
            }
            
        if(!isset($id) || $id == ''){
			$this->redirect(array('controller' => 'newsletters','action'=>'index'));
			exit();
		}

		$this->__validateLoginStatus();
		$admsess	=	$this->Session->read('Admin');
		if($admsess["newsletter"] <> 1){
		 	$this->redirect(array('controller' => 'admins', 'action' => 'index')); 
			exit();
		}


		           //Setting the Newsletter Contents..

				    $cnfg 			=	Configure::read('Neutrino');
					$subject 		= "Newsletter";
					$headers 		= "From: ".$cnfg["site_name"]."<".$cnfg["admin_email"].">\r\n";
					$headers 		.= "MIME-Version: 1.0\r\n";
					$headers 		.= "Content-type: text/html; charset=iso-8859-1\r\n";
					$news 			= 	$this->Newsletter->findById($id);
					$path			=	"SiteLogo_disp.gif";

					

				  //  $subscribers	= $this->Newsletteruser->find('all', array('conditions' => array('Newsletteruser.status = "Y"')));

				      $usrtbl=$this->User->getTableName("users");
								 $subscribers	= $this->Newsletteruser->find('all',array(
							           'conditions' => array('Newsletteruser.status' => 'Y', 'USR.usertype' => 'retail'),	
							           'fields' => array('id','email','uname'), //array of field names
							           'order' => '', //string or array defining order
							           'joins' => array(
									   array('table' => $usrtbl, 
											'alias' => 'USR', 
											'type' => 'LEFT',  
											'conditions'=> array('Newsletteruser.email = USR.email') 
								            )
								          ), // array of arrays defining join operations
							           'group' => ''));					
									   
									/*
									   echo "<pre>";
									   print_r($subscribers);
									   echo "</pre>";
									   exit();
									  */

					foreach($subscribers as $recepients)
					{	//print_r($recepients);exit;
                                            $mailcontent			=	"<table width='90%'  border='0' cellspacing='2' cellpadding='2' align='center'>
		            <tr><td><a href='".FULL_BASE_URL. $cnfg["sitebasefolder"]."' target='_blank'><img src='".FULL_BASE_URL. $cnfg["sitebasefolder"]."/app/webroot/".IMAGES_URL.$path."' border='0'></a></td></tr></table>";
					//$cnfg["site_name"]	=	"<a href='".FULL_BASE_URL. $cnfg["sitebasefolder"]."' target='_blank'>".$cnfg["site_name"]."</a>";
					$logurl			=	"<a href='".FULL_BASE_URL. $cnfg["sitebasefolder"]."/users/login' target='_blank'>Click here to login</a>";
					$mailcontent	=	$mailcontent."Hello [VARIABLEUSERNAME] ,<br>";
                                        $mailcontent	=	$mailcontent.$news["Newsletter"]["title"]."<br>";
					$mailcontent	=	$mailcontent.$news["Newsletter"]["content"];
                                        $mailcontent	=	$mailcontent."<p>&nbsp;</p>
                                                                Thanks and Regards,<br>
                                                                Administrator [SITE_NAME]";

				   //Setting the Newsletter Contents..


						$mailcontent = str_replace("[VARIABLEUSERNAME]",$recepients["Newsletteruser"]["uname"],$mailcontent);
                                                $mailcontent = str_replace("[SITE_NAME]",$cnfg["site_name"],$mailcontent);
                                            //$mailsent 		= mail($recepients["Newsletteruser"]["email"],$subject,$mailcontent,$headers);
                                                
                                            /*#################################### EMAIL SEGMENT ###############################*/
                                                $site_name      = "";
                                                $admin_email    = "";
                                                if(trim($cnfg["site_name"]) <> ""){
                                                    $site_name  = trim($cnfg["site_name"]);                            
                                                }else{
                                                    $site_name = $cnfg["smtp_user"];                            
                                                }  
                                                if(trim($cnfg["admin_email"]) <> ""){
                                                    $admin_email = trim($cnfg["admin_email"]);
                                                }else{
                                                    $admin_email = $cnfg["smtp_user"];
                                                }
                                                /******************************* MAIL TO THE USER ****************************/
                                                $mail             = new PHPMailer(true);                
                                                $body             = trim($mailcontent);
                                                //$body           = eregi_replace("[\]",'',$body);
                                                $mail->IsSMTP(); 
                                                $mail->SMTPSecure = 'tls';
                                                //$mail->SMTPDebug  = 2;                    
                                                $mail->SMTPAuth   = true;  
                    
                                                $mail->Host       = $cnfg["smtp_host"]; 
                    						$mail->Port       = $cnfg["smtp_port"];   
                    					$mail->Username   = $cnfg["smtp_user"];
                    				 $mail->Password   = $cnfg["smtp_password"];      
                                                $mail->SetFrom($admin_email,$site_name);
                                                //$mail->AddReplyTo($admin_email,$site_name);
                                                $mail->Subject    = $subject;
                                                $mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
                                                $mail->MsgHTML($body);                    
                                                $mail->AddAddress($recepients["Newsletteruser"]["email"], ""); 
                                                $mail->Send();
                                                /******************************* MAIL TO THE USER ****************************/ 
                                            /*#################################### EMAIL SEGMENT ###############################*/
                        
						 $this->SentNewsletter->create($send = array());		
					     $send["newsletter_id"]	=	$id;
			             $send["user_id"]		=	$recepients["Newsletteruser"]["id"];
						 $send["send_date"]		=    date('Y-m-d h:i:s');                       
					     $this->SentNewsletter->save($send)	;
						 unset($send);						
				    }
					$this->Session->setFlash(__('Newsletter has been sent successfully!', true));
			        $this->redirect(array('controller' => 'newsletters','action'=>'index'));
	}



	



	



	function sendWholesale($id='')



	{	
            
            $cnfg 		= Configure::read('Neutrino');
            if(trim($_SERVER['HTTP_HOST']) == 'localhost'){ 
                include_once("../phpmailer/class.phpmailer.php");
            }else{
                include_once($_SERVER["DOCUMENT_ROOT"].$cnfg["sitebasefolder"]."/app/phpmailer/class.phpmailer.php");
            }



        if(!isset($id) || $id == ''){



			$this->redirect(array('controller' => 'newsletters','action'=>'index'));



			exit();



		}



		$this->__validateLoginStatus();



		$admsess	=	$this->Session->read('Admin');



		if($admsess["newsletter"] <> 1){



		 	$this->redirect(array('controller' => 'admins', 'action' => 'index')); 



			exit();



		}



		



		           //Setting the Newsletter Contents..



				    $cnfg 			=	Configure::read('Neutrino');



					$subject 		= "Newsletter";



					$headers 		= "From: ".$cnfg["site_name"]."<".$cnfg["admin_email"].">\r\n";



					$headers 		.= "MIME-Version: 1.0\r\n";



					$headers 		.= "Content-type: text/html; charset=iso-8859-1\r\n";



					$news 			= 	$this->Newsletter->findById($id);



					$path			=	"SiteLogo_disp.gif";



					



				   



				   



				  //  $subscribers	= $this->Newsletteruser->find('all', array('conditions' => array('Newsletteruser.status = "Y"')));



				      $usrtbl=$this->User->getTableName("users");



					  					



								 $subscribers	= $this->Newsletteruser->find('all',array(



							           'conditions' => array('Newsletteruser.status' => 'Y', 'USR.usertype' => 'wholesale'),					



							           'fields' => array('id','email','uname'), //array of field names



							           'order' => '', //string or array defining order



							           'joins' => array(



									   array( 



											'table' => $usrtbl, 



											'alias' => 'USR', 



											'type' => 'INNER',  



											'conditions'=> array('Newsletteruser.email = USR.email') 



								            )



								          ), // array of arrays defining join operations



							           'group' => ''));					



					

					

					



					foreach($subscribers as $recepients)



					{										
$mailcontent			=	"<table width='90%'  border='0' cellspacing='2' cellpadding='2' align='center'>



		            <tr><td><a href='".FULL_BASE_URL. $cnfg["sitebasefolder"]."' target='_blank'><img src='".FULL_BASE_URL. $cnfg["sitebasefolder"]."/app/webroot/".IMAGES_URL.$path."' border='0'></a></td></tr></table>";



					//$cnfg["site_name"]	=	"<a href='".FULL_BASE_URL. $cnfg["sitebasefolder"]."' target='_blank'>".$cnfg["site_name"]."</a>";



					$logurl			=	"<a href='".FULL_BASE_URL. $cnfg["sitebasefolder"]."/users/login' target='_blank'>Click here to login</a>";

$mailcontent	=	$mailcontent."Hello [VARIABLEUSERNAME] ,<br>";

					$mailcontent	=	$mailcontent.$news["Newsletter"]["title"]."<br>";



					$mailcontent	=	$mailcontent.$news["Newsletter"]["content"];
                                        $mailcontent	=	$mailcontent."<p>&nbsp;</p>
                                                                Thanks and Regards,<br>
                                                                Administrator [SITE_NAME]";



				   //Setting the Newsletter Contents..
$mailcontent = str_replace("[VARIABLEUSERNAME]",$recepients["Newsletteruser"]["uname"],$mailcontent);
$mailcontent = str_replace("[SITE_NAME]",$cnfg["site_name"],$mailcontent);

						 //$mailsent 		= mail($recepients["Newsletteruser"]["email"],$subject,$mailcontent,$headers);	

                    /*#################################### EMAIL SEGMENT ###############################*/
                       $site_name      = "";
                       $admin_email    = "";
                       if(trim($cnfg["site_name"]) <> ""){
                           $site_name  = trim($cnfg["site_name"]);                            
                       }else{
                           $site_name = $cnfg["smtp_user"];                            
                       }  
                       if(trim($cnfg["admin_email"]) <> ""){
                           $admin_email = trim($cnfg["admin_email"]);
                       }else{
                           $admin_email = $cnfg["smtp_user"];
                       }
                       /******************************* MAIL TO THE USER ****************************/
                       $mail             = new PHPMailer(true);                
                        $body             = trim($mailcontent);
                        //$body           = eregi_replace("[\]",'',$body);
                        $mail->IsSMTP(); 
                        $mail->SMTPSecure = 'tls';
                        //$mail->SMTPDebug  = 2;                    
                        $mail->SMTPAuth   = true;  
                    
                    $mail->Host       = $cnfg["smtp_host"]; 
                    $mail->Port       = $cnfg["smtp_port"];   
                    $mail->Username   = $cnfg["smtp_user"];
                    $mail->Password   = $cnfg["smtp_password"];       
                       $mail->SetFrom($admin_email,$site_name);
                       //$mail->AddReplyTo($admin_email,$site_name);
                       $mail->Subject    = $subject;
                       $mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
                       $mail->MsgHTML($body);                    
                       $mail->AddAddress($recepients["Newsletteruser"]["email"], ""); 
                       $mail->Send();
                       /******************************* MAIL TO THE USER ****************************/ 
                   /*#################################### EMAIL SEGMENT ###############################*/

						 

						  $this->SentNewsletter->create($send = array());									



					     $send["newsletter_id"]	=	$id;



			             $send["user_id"]		=	$recepients["Newsletteruser"]["id"];



						 $send["send_date"]		=    date('Y-m-d h:i:s');                       



					     $this->SentNewsletter->save($send)	;



						 unset($send);						



				    }



					$this->Session->setFlash(__('Newsletter has been sent successfully!', true));



			        $this->redirect(array('controller' => 'newsletters','action'=>'index'));



	}



	



	function delete($delid='')



	{



	  if($delid==''){



			$this->redirect(array('controller' => 'newsletters','action'=>'index'));



			exit();



		}



	  if($this->Newsletter->del($delid)){



			$this->Session->setFlash(__('Newsletter has been deleted Successfully.', true));



			$this->redirect(array('controller' => 'newsletters','action'=>'index'));



			exit;



		   }



	}	   

//***************** stream send start
function streamsend($id='')
	{
        if(!isset($id) || $id == ''){
			$this->redirect(array('controller' => 'newsletters','action'=>'index'));
			exit();
		}

		$this->__validateLoginStatus();
		$admsess	=	$this->Session->read('Admin');
		if($admsess["newsletter"] <> 1){
		 	$this->redirect(array('controller' => 'admins', 'action' => 'index'));
			exit();
		}
$cnfg 			=	Configure::read('Neutrino');
 if(isset($cnfg['streamsendLoginID']) && isset($cnfg['streamsendKey']) && isset($cnfg['streamsendListID']) && $cnfg['streamsendEnable'] == 'Y'  ){
		           //Setting the Newsletter Contents..

                                        
					$subject 		= "Newsletter";
					$headers 		= "From: ".$cnfg["site_name"]."<".$cnfg["admin_email"].">\r\n";
					$headers 		.= "MIME-Version: 1.0\r\n";
					$headers 		.= "Content-type: text/html; charset=iso-8859-1\r\n";
					$news 			= 	$this->Newsletter->findById($id);
					$path			=	"SiteLogo_disp.gif";



				  //  $subscribers	= $this->Newsletteruser->find('all', array('conditions' => array('Newsletteruser.status = "Y"')));

				      $usrtbl=$this->User->getTableName("users");
								 $subscribers	= $this->Newsletteruser->find('all',array(
							           'conditions' => array('Newsletteruser.status' => 'Y', 'USR.usertype' => 'retail'),
							           'fields' => array('id','email','uname'), //array of field names
							           'order' => '', //string or array defining order
							           'joins' => array(
									   array('table' => $usrtbl,
											'alias' => 'USR',
											'type' => 'LEFT',
											'conditions'=> array('Newsletteruser.email = USR.email')
								            )
								          ), // array of arrays defining join operations
							           'group' => ''));

									
					//foreach($subscribers as $recepients)
					//{	print_r($recepients);exit;
                                            $mailcontent			=	"<table width='90%'  border='0' cellspacing='2' cellpadding='2' align='center'>
		            <tr><td><a href='".FULL_BASE_URL. $cnfg["sitebasefolder"]."' target='_blank'><img src='".FULL_BASE_URL. $cnfg["sitebasefolder"]."/app/webroot/".IMAGES_URL.$path."' border='0'></a></td></tr></table>";
					//$cnfg["site_name"]	=	"<a href='".FULL_BASE_URL. $cnfg["sitebasefolder"]."' target='_blank'>".$cnfg["site_name"]."</a>";
					$logurl			=	"<a href='".FULL_BASE_URL. $cnfg["sitebasefolder"]."/users/login' target='_blank'>Click here to login</a>";
					$mailcontent	=	$mailcontent."Hello [VARIABLEUSERNAME] ,<br>";
                                        $mailcontent	=	$mailcontent.$news["Newsletter"]["title"]."<br>";
					$mailcontent	=	$mailcontent.$news["Newsletter"]["content"];
                                        $mailcontent	=	$mailcontent."<p>&nbsp;</p>
                                                                Thanks and Regards,<br>
                                                                Administrator [SITE_NAME]";


				   //Setting the Newsletter Contents..

                                  
						$mailcontent = str_replace("[VARIABLEUSERNAME]","",$mailcontent);
                                                $mailcontent = str_replace("[SITE_NAME]",$cnfg["site_name"],$mailcontent);

                                            //send mail using stream send
                                           
                                                    $this->Streamsend->loginID    = $cnfg['streamsendLoginID'];
                                                    $this->Streamsend->key        = $cnfg['streamsendKey'];
                                                    $this->Streamsend->listID     = $cnfg['streamsendListID'];
                                                   // $scheduledfor = "2012-11-20T3:00:00Z";
                                                    $scheduledfor = date("c");

                                                    $newsletter = array(
                                                        "frname" => $cnfg['site_name'],
                                                        "frmail" => $cnfg['admin_email'],
                                                        "subject" => $subject,
                                                        "mailtemp" => $mailcontent,
                                                        "scheduledfor" => $scheduledfor
                                                        );
                                                       
                                                    //activate from maile
                                                   //if($this->Streamsend->fromemailactivation($cnfg['admin_email'])){echo 'in';exit;
                                                       //send mail
                                                    $this->Streamsend->fromemailactivation($cnfg['admin_email']);
                                                    $newsletterxml = $this->Streamsend->getXMLSendEmail($newsletter);
                                                $mailStatus =    $this->Streamsend->sendstreamsendmail($newsletterxml);
                                                if($mailStatus == 'sucess'){
                                                      $this->Session->setFlash(__('Newsletter has been sent successfully!', true));
                                                      $this->redirect(array('controller' => 'newsletters','action'=>'index'));
                                                }else{
                                                   $this->Session->setFlash(__('Newsletter cannot be send, Streamsend error!', true));
                                                   $this->redirect(array('controller' => 'newsletters','action'=>'index'));
                                                }
                                                   // }
                                           


// $mailsent 		= mail($recepients["Newsletteruser"]["email"],$subject,$mailcontent,$headers);
						/* $this->SentNewsletter->create($send = array());
                                                 $send["newsletter_id"]	=	$id;
                                                 $send["user_id"]		=	$recepients["Newsletteruser"]["id"];
                                                 $send["send_date"]		=    date('Y-m-d h:i:s');
                                                 $this->SentNewsletter->save($send)	;*/
                                               //  unset($send);
                                                 // }
                                                 $this->Session->setFlash(__('Newsletter has been sent successfully!', true));
                                                 $this->redirect(array('controller' => 'newsletters','action'=>'index'));
	}else{
          $this->Session->setFlash(__('Newsletter cannot be send, Streamsend settings cannot found!', true));
          $this->redirect(array('controller' => 'newsletters','action'=>'index'));
        }

        }

//******************** stream send ends

	



}



?>