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

{

    var $name = "Giftcard";

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

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

	var $uses = array('Giftcard','Setting','Category','Product','Currency','Cart','Cmspage');

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

	function index()

    {

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

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

		if($admsess["giftcards"] <> 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 == "code"){

				//$criteria="Giftcard.gift_code  LIKE '%".addslashes($txtSearch)."%'";

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

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

				//$criteria="Giftcard.gift_amnt  LIKE '%".addslashes($txtSearch)."%'";

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

			}else{

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

			}

			

		}else{

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

		}

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

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

		$this->set('giftcards', $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->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';
            $footer_links = $this->Cmspage->find('list',array('conditions' => array('Cmspage.type' => 'content','Cmspage.status' => 'Y')));
        $this->set('footerlinks', $footer_links);

    }

   

	function add() {

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

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


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

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

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

			exit();

		}

		

		    $gftbl=$this->Giftcard->getTableName("giftcards");

		    $res=	$this->Giftcard->query("select max(id) as maxval from ".$gftbl."");

			if(isset($res[0][0]["maxval"]) && $res[0][0]["maxval"] <> '')

			$maxid= ($res[0][0]["maxval"]) + 1;

			else

			$maxid=1; 

			

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

			//checking for duplicates starts here...

			 $dups=$this->Giftcard->findByGiftCode($this->data["Giftcard"]["gift_code"]); 

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

		     {

		         $this->Session->setFlash(__('Gift Card Already exists.', '/giftcards'));

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

		         exit();

		      } 

			 //checking for duplicates ends here...		

			 /*		

			$this->data["Giftcard"]["from"]   	 =	$this->data["Giftcard"]["From"];

			$this->data["Giftcard"]["to"]		 =	$this->data["Giftcard"]["To"];

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

			*/

			

			

			  //Uplaoding image for Gift card

					$err = false;			

					if(!empty($this->data['Giftcard']['gift_img']['tmp_name'])) {

						$giftfile = $this->Product->generateUniqueFilename($this->data['Giftcard']['gift_img']['name']);

						$error = $this->Product->handleFileUpload($this->data['Giftcard']['gift_img'], $giftfile);

					}

					if(empty($error))

					{

				

							if(!empty($giftfile))

								$this->data['Giftcard']['gift_img'] = $giftfile;

							else

								unset($this->data['Giftcard']['gift_img']);

					}

					 //Uplaoding image for  Gift card

					 

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

				$this->Session->setFlash(__('Your Gift Card has been saved.', '/giftcards'));

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

			}

		}

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

		$this->layout = 'adm';

	} 

	

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

		$this->__validateLoginStatus();

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

                 //****************** currency************
                global $currency;
		$curr		=	$this->Currency->findByCode($currency);
		$this->set('curlogo',$curr["Currency"]["logo"]);
              //****************** currency ends************
		if($admsess["giftcards"] <> 1){

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

			exit();

		}

		if($id == 0){

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

			exit();

		}

		$this->Giftcard->id					=	$id;

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

		    //checking for duplicates starts here...

			

		     $dups=$this->Giftcard->find('count', array('conditions' => array('Giftcard.gift_code' => $this->data["Giftcard"]["gift_code"] , 'id <>' =>  $id)));			

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

		     {

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

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

		         exit();

		      } 			

		    //checking for duplicates ends here...

			

			

			  //Uplaoding image for Gift card

					$err = false;			

					if(!empty($this->data['Giftcard']['gift_img']['tmp_name'])) {

						$giftfile = $this->Product->generateUniqueFilename($this->data['Giftcard']['gift_img']['name']);

						$error = $this->Product->handleFileUpload($this->data['Giftcard']['gift_img'], $giftfile);

					}

					if(empty($error))

					{

				

							if(!empty($giftfile))

								$this->data['Giftcard']['gift_img'] = $giftfile;

							else

								unset($this->data['Giftcard']['gift_img']);

					}

					 //Uplaoding image for  Gift card

					 /*

					$this->data["Giftcard"]["from"]	=	$this->data["Giftcard"]["From"];

					$this->data["Giftcard"]["to"]		=	$this->data["Giftcard"]["To"];

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

					*/

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

				$this->Session->setFlash(__('Gift Card has been edited Successfully.', '/giftcards'));

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

			}

		}

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

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

		$this->layout = 'adm';

		

	} 

	function delete($id){

		$this->__validateLoginStatus();

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

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

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

			exit();

		}

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

		$this->Session->setFlash(__('Gift Card has been deleted Successfully.', '/giftcards'));

		$this->redirect('index');

	}

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

	function show()

	{		

		$this->__validateLoginStatus('U');

		//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..

		global $currency;

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

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

		$criteria="Giftcard.stock > 0";

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

        $gdet = $this->Giftcard->findAll($criteria, NULL, 'Giftcard.id DESC', $limit, $page); // Extra parameters added 

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

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

	}

	

	

	function showgiftcard($id='')

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

		 $lst	=	$this->Category->findAll();			 

		 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..

		 global $currency;

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

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

		 $gdet	=	$this->Giftcard->findById($id);		

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

	}

	
	function gcardcsv()
	{	
	  $data	=	$this->Giftcard->findAll();		
	  $this->set('data', $data);				
      $this->layout = 'csvexp';
	}
	
	function gcardxls()
	{	
	  $data	=	$this->Giftcard->findAll();		
	  $this->set('data', $data);				
      $this->layout = 'csvexp';
	}
	

	function __validateLoginStatus($typ='A')

    {

           if($typ == 'A'){

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

				{

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

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

				}

			}else{

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

				{

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

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

				}

			}

    } 

}

?>