<?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 CouponsController extends AppController



{



    var $name = "Coupon";



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



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



	var $uses = array('Coupon','Setting','Currency','Cart');



    var $paginate = array('limit' => 25,'order' => array('Coupon.from_date' => 'desc'));



	function index()



    {



		 $this->__validateLoginStatus();


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



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



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



			exit();



		}
              //****************** currency************
                global $currency;
		$curr		=	$this->Currency->findByCode($currency);
		$this->set('curlogo',$curr["Currency"]["logo"]);
              //****************** currency ends************
		$cmbSearchType	=	"";



		$txtSearch		=	"";



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

			$cmbSearchType	=	$_GET["cmbSearchType"];

			$txtSearch		=	$_GET["txtSearch"];

			if($cmbSearchType == "code"){

				$criteria="Coupon.code  LIKE '%".addslashes($txtSearch)."%'";

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

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

				$criteria="Coupon.giftvalue  LIKE '%".addslashes($txtSearch)."%'";

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

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

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

			}else{

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

			}

		}

		else if(isset($this->passedArgs["cmbSearchType"]) && isset($this->passedArgs["txtSearch"]) && 

		 $this->passedArgs["txtSearch"] <> '')

		{

		    $cmbSearchType	=	$this->passedArgs["cmbSearchType"];

			$txtSearch		=	$this->passedArgs["txtSearch"];

			if($cmbSearchType == "code"){

				$criteria="Coupon.code  LIKE '%".addslashes($txtSearch)."%'";

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

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

				$criteria="Coupon.giftvalue  LIKE '%".addslashes($txtSearch)."%'";

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

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

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

			}else{

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

			}

		}		

		else{              

			

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



		}



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



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

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

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





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

		

		$this->layout = 'adm';



    } 



    function beforeFilter()



    {



        $this->__validateLoginStatus();



		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('siteurl', $sitefolder);



		$this->pageTitle = $page_title	; 



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



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

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

		$httpHost	=	$_SERVER['HTTP_HOST'];

		$this->set('sitebase','http://'.$httpHost);

                //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()



    {



       // $this->layout = 'adm';



    }



    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() {

            $cnfg 				=	Configure::read('Neutrino');
        $style				=	$cnfg["style"];
        $this->set('style', "admin/".$style);
                //*****************Currency Symbol ******************
                global $currency;
                $curr		=	$this->Currency->findByCode($currency);

                $this->set('curlogo',$curr["Currency"]["logo"]);
            //*****************Currency Symbol Ends******************
            
		 $this->__validateLoginStatus();



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

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



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



			exit();



		}

                

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

                    

			//checking for duplicates starts here...
                         
                         

			 $dups=$this->Coupon->findByCode($this->data["Coupon"]["code"]); 



			 if(isset($dups["Coupon"]["id"]) && $dups["Coupon"]["id"] <> '')



		     {



		         $this->Session->setFlash(__('Promocode Already exists.', '/coupons'));



		         $this->redirect('/coupons');



		         exit();



		      } 



			//checking for duplicates ends here...			

			$from_date=array();

			$to_date=array();

			$from_date=explode('-', $this->data["Coupon"]["From"]);

			$to_date=explode('-', $this->data["Coupon"]["To"]);			 

            if(isset($from_date[0]))

			$this->data["Coupon"]["from_date"]	=	$from_date[2].'-'.$from_date[0].'-'.$from_date[1];

            if(isset($to_date[0]))

			$this->data["Coupon"]["to_date"]		=	$to_date[2].'-'.$to_date[0].'-'.$to_date[1];

                        $today = date('Y-m-d',time());
            if($this->data["Coupon"]["from_date"] < $today)
                {

                        

		         $this->Session->setFlash(__('Start Date should be greater than today.', '/coupons'));



		         //$this->redirect(array('controller' => 'coupons', 'action' => 'add'));



		         //exit();



		      } else {


			unset($this->data["Coupon"]["From"],$this->data["Coupon"]["To"]);



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



				$this->Session->setFlash(__('Your Coupon has been saved.', '/coupons'));



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



			}
                      }



		}



		



	} 



	function edit($id=0) {



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


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

            //*****************Currency Symbol ******************
                global $currency;
                $curr		=	$this->Currency->findByCode($currency);

                $this->set('curlogo',$curr["Currency"]["logo"]);
            //*****************Currency Symbol Ends******************

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



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



			exit();



		}



		if($id == 0){



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



			exit();



		}



		$this->Coupon->id					=	$id;



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



		    //checking for duplicates starts here...



		     $dups=$this->Coupon->checkEditDups($this->data["Coupon"]["code"],$id);			



		     if(isset($dups) && $dups > 0)



		     {



		         $this->Session->setFlash(__('Promocode Already exists.', '/coupons'));



		         $this->redirect('/coupons');



		         exit();



		      } 



		    //checking for duplicates ends here...



			$from_date=array();

			$to_date=array();

			$from_date=explode('-', $this->data["Coupon"]["From"]);

			$to_date=explode('-', $this->data["Coupon"]["To"]);			 

            if(isset($from_date[0]))

			$this->data["Coupon"]["from_date"]	=	$from_date[2].'-'.$from_date[0].'-'.$from_date[1];

            if(isset($to_date[0]))

			$this->data["Coupon"]["to_date"]		=	$to_date[2].'-'.$to_date[0].'-'.$to_date[1];

            $today = date('Y-m-d',time());

            if($this->data["Coupon"]["from_date"] < $today)
                {



		         $this->Session->setFlash(__('Start Date should be greater than today.', '/coupons'));



		         $this->redirect(array('controller' => 'coupons', 'action' => 'edit/'.$this->Coupon->id));



		         exit();



		      }


			unset($this->data["Coupon"]["From"],$this->data["Coupon"]["To"]);



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



				$this->Session->setFlash(__('Promocode has been edited Successfully.', '/coupons'));



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



			}



		}



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



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



		$this->layout = 'adm';



		



	} 



	function delete($id){



		$this->__validateLoginStatus();



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



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



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



			exit();



		}



		$this->Coupon->del($id,true);



		$this->Session->setFlash(__('Promocode has been deleted Successfully.', '/coupons'));



		$this->redirect('index');



	}



	#### Function to show products and subcategories under a category



	function show_cat($name){



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



        {  



             $this->Setting->load();  



        } 



		global $page_title;



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



		$page_title			=	$name." - ".$cnfg["page_title"];



		$this->pageTitle = $page_title	; 



		$lst	=	$this->Catmenu->getCatList(1);



		$cdet	=	$this->Category->findByCname($name);



		if(isset($cdet["Category"]["id"])){



			$id		=	$cdet["Category"]["id"];



			$sub	=	$this->Catmenu->getCatList($id);



			$this->set('catmenu', $lst);



			$this->set('subcat', $sub);



			$ct		=	$this->Category->findById($id);



			$this->set('pcatdet', $ct);



			$criteria="Product.category_id =$id AND Product.Status = 'A' AND Product.Stock > 0";



			list($order,$limit,$page) = $this->Pagination->init($criteria); // Added



			$data = $this->Product->findAll($criteria, NULL, 'Product.id DESC', $limit, $page);



			$pdct	=	$this->Product->findAll("Product.category_id =$id AND Product.Status = 'A' AND Product.Stock > 0", NULL, 'Product.id DESC', $limit, $page);



			for($c=0; $c < sizeof($pdct); $c++){				



				if(isset($pdct[$c]["Productimages"][0]["imagename"])){



					$defimg	=	$pdct[$c]["Productimages"][0]["imagename"];



					for($m=0; $m < sizeof($pdct[$c]["Productimages"]); $m++){



						if($pdct[$c]["Productimages"][$m]["default"] == "Y"){



							$defimg	=	$pdct[$c]["Productimages"][$m]["imagename"];



						}



					}



					$pdct[$c]["Productimages"]	=	$defimg;



				}else{



					$pdct[$c]["Productimages"]	= '';



				}



			}



			$this->set('products', $pdct);



		}else{



			$this->redirect(array('controller' => 'pages','action'=>'display'));



		}



	}







  	function reports()

	{       

		

	     	$coupon_min_date=explode(" ",$this->Coupon->getDates_coupons("min"));	

	 		$coupon_max_date=explode(" ",$this->Coupon->getDates_coupons("max"));		

   		    $this->set('dflt_mindate', $coupon_min_date[0]); //Setting the max date for the calendar...

		    $this->set('dflt_maxdate', $coupon_max_date[0]); //Setting the max date for the calendar...

			

		if(isset($_POST["coupon_fdate"]) &&  isset($_POST["coupon_tdate"]) && $_POST["coupon_fdate"]<>'' && $_POST["coupon_tdate"]<>'')

		{	

			$frmdate=$_POST["coupon_fdate"];

            $todate=$_POST["coupon_tdate"];

	    }

		else if(isset($this->passedArgs["frmdate"]) && isset($this->passedArgs["todate"]) && 

		 $this->passedArgs["frmdate"] <> '' &&  $this->passedArgs["todate"] <> '')

		{

		    $frmdate=$this->passedArgs["frmdate"];

            $todate= $this->passedArgs["todate"];		

		}

		else

		{

		    $frmdate=$coupon_min_date[0];

            $todate=$coupon_max_date[0];		

		}		

			//$cttbl=$this->Report->getTableName("users");

		    $sdate=explode('-',$frmdate);

			$srch_fdate=$sdate[2].'-'.$sdate[0].'-'.$sdate[1];

			$tdate=explode('-',$todate);

			$srch_tdate=$tdate[2].'-'.$tdate[0].'-'.$tdate[1];

						

			$cttb2=$this->User->getTableName("user_addresses");		   		

			$this->paginate = array(	

			'conditions' => array("DATE_FORMAT(User.reg_date,'%Y-%m-%d') >= '".$srch_fdate."' AND  DATE_FORMAT(User.reg_date,'%Y-%m-%d') <= '".$srch_tdate."'"),		

		    'fields' => array("User.uname,User.email,DATE_FORMAT(User.reg_date,'%m-%d-%Y')as reg_date, uadd.addr_type, uadd.fname, uadd.lname, uadd.address, uadd.city, uadd.state, uadd.country, uadd.zip, uadd.phone, uadd.fax, uadd.mobile"),

			'order' => '',

			'limit' => $this->paginate["limit"],

            'joins' => array( 

								array( 

									'table' => $cttb2, 

									'alias' => 'uadd', 

									'type' => 'LEFT',  

									'conditions'=> array('User.id= uadd.id') 

								)

							),

			'group' => 'User.id',

			'passit' => $this->passedArgs

			);				

			$reportdet = $this->paginate('User');							

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

			

			//echo "<pre>";

			//print_r($reportdet);

			//echo "<pre>";

			//exit();

			

			

			 $this->set('mindate', $frmdate);

		     $this->set('maxdate', $todate);	

				

			$this->layout = 'adm'; 

	

	}


  function pcodecsv()
	{	
	  $data	=	$this->Coupon->findAll();		
	  $this->set('data', $data);			
      $this->layout = 'csvexp';
	}
	
	function pcodexls()
	{	
	  $data	=	$this->Coupon->findAll();		
	  $this->set('data', $data);				
      $this->layout = 'csvexp';
	}




}



?>