<?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 CategoriesController extends AppController {



    var $name = "Category";



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



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



	var $uses = array('Product','Category','Customfield','Customfieldvalue','Currency','Cmspage','Cart');



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



    function index() {



        $this->__validateLoginStatus();

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

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



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



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



            exit();



        }



        $criteria="Category.id <> 1";



        $cmbSearchType	=	"";



        $txtSearch		=	"";



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

            $cmbSearchType	=	$_GET["cmbSearchType"];

            $txtSearch		=	$_GET["txtSearch"];

            if($cmbSearchType == "name") {

                $data = $this->paginate('Category', array('Category.cname  LIKE ' => "%".addslashes($txtSearch)."%",'Category.id <>'=>1));

            }else {

                $data = $this->paginate('Category', array('Category.id <>'=>1));

            }

        }

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

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

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

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

            if($cmbSearchType == "name") {

                $data = $this->paginate('Category', array('Category.cname  LIKE ' => "%".addslashes($txtSearch)."%",'Category.id <>'=>1));

            }else {

                $data = $this->paginate('Category', array('Category.id <>'=>1));

            }

        }else {

            $data = $this->paginate('Category', array('Category.id <>'=>1));

        }







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



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

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

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



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



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



        else if($curr_action='show_cat')



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



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

        $httpHost	=	$_SERVER['HTTP_HOST'];

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




		$this->paginate["limit"]=12; //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() {



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


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



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



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



            exit();



        }



        $cstfldvlstbl=$this->Category->getFulltablename("customfieldvalues");



        // $pcat	=	$this->Category->find('list',array('fields'=>array('Category.id', 'Category.cname')));

        //newly added for category tree listing

        $pcat = $this->Category->find('threaded', array('order' => array('Category.cname' => 'ASC')));

        $this->set('categoriesList', $pcat);

        //newly added



        $cfields = $this->Customfield->find('list', array('fields'=>array('Customfield.id', 'Customfield.custom_name'),'joins' =>



                array(



                        array('table' =>  $cstfldvlstbl,'alias' => 'Customfieldvalue', 'type' => 'inner','conditions'=>



                                array('Customfield.id = Customfieldvalue.customfield_id')))));











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



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



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



            //checking for duplicates starts here...



            $dups=$this->Category->checkAddDups(trim(addslashes($this->data["Category"]["cname"])),$this->data["Category"]["parent_id"]);



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



                $this->Session->setFlash(__('Category Value Already exists Under this Parent Category.', '/categories'));



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



                exit();



            }



            //checking for duplicates ends here...

        

            $this->Category->save($this->data);



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



            $this->redirect('index');



        }



        $this->layout = 'adm';



    }





################## Ajax Function to List the Product Attributes starts here(Added by Shyam) ######################
    function checkcategory($id='') {
        Configure::write('debug', 0);
        $this->layout = null;
        $pval	=	$this->Product->findByCategoryId($id);
        $this->set('pval', $pval);
    }

    function checksubcat($id='') {
        Configure::write('debug', 0);
        $this->layout = null;
        $cval	=	$this->Category->find('all', array('conditions' => array('Category.parent_id ='.$id)));
        $this->set('cval', $cval);
    }


    ################## Ajax Function to List the Product Attributes	Ends here(Added by Shyam) ######################





    ################## Ajax Function to List the Product Attributes starts here(Added by Shyam) ######################



    function showattributes($id) {



        $this->layout = null;



        $cfield	=	$this->Customfield->findById($id);



        $cfieldname	=	$cfield["Customfield"]["custom_name"];



        $cfvalues	=	$this->Customfieldvalue->find('list',array('fields'=>array('Customfieldvalue.id', 'Customfieldvalue.custom_value'),



                'conditions' =>'Customfieldvalue.customfield_id IN ('.$id.')'));



        $this->set('cfieldid', $id);



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



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



    }



    ################## Ajax Function to List the Product Attributes	Ends here(Added by Shyam) ######################











    function edit($id=0) {

        if($id == 0) {

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



            exit();



        }



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


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



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



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



            exit();



        }



        $this->Category->id = $id;



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



        $catname	=	$cat["Category"]["cname"];



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



            //checking for duplicates starts here...



            $dups=$this->Category->checkEditDups(addslashes($this->data["Category"]["cname"]),$this->data["Category"]["parent_id"],$id);



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



                $this->Session->setFlash(__('Category Value Already exists Under this Parent Category.', '/categories'));



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



                exit();



            }



            //checking for duplicates ends here...



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



                $this->Session->setFlash(__('Category '.$catname.' has been Edited Successfully.', '/categories'));



                $this->redirect('index');



            }



        }else {



            global $categ;



            global $ind;



            $categ		=	array();



            $ind		=	0;



            $arr		=	$this->Category->getchilds($id);



            $narr		=	array();



            $narr		=	$id;



            $i			=	1;



            foreach($arr as $ne) {



                $narr	=	$narr.",".$ne["id"];



            }



            //$pcat		=	$this->Category->find('list',array('fields'=>array('Category.id', 'Category.cname'),'conditions' =>'Category.id NOT IN ('.$narr.')'));



            //$this->set('pcat', $pcat);

            //newly added for category tree listing

            $pcat = $this->Category->find('threaded', array('order' => array('Category.cname' => 'ASC')));

            $this->set('categoriesList', $pcat);

            //newly added



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



            $this->set('categorydet', $this->data);
            $this->set('editid', $id);



        }







        ####### Code for fetching data to be displayed on Edit Category Page starts here(Added By shyam) ############



        $cstfldvlstbl=$this->Category->getFulltablename("customfieldvalues");



        $cfields = $this->Customfield->find('list', array('fields'=>array('Customfield.id', 'Customfield.custom_name'),'joins' =>



                array(



                        array('table' => $cstfldvlstbl,'alias' => 'Customfieldvalue', 'type' => 'inner','conditions'=>



                                array('Customfield.id = Customfieldvalue.customfield_id')))));















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



        if($combinations['Category']['custom_combination']!='') {



            $combination=$combinations['Category']['custom_combination'];



            $split_combination=explode(',',$combination);



            foreach($split_combination as $combn) {



                $cparent=$this->Customfieldvalue->findById($combn);



                $cparents[$combn]=$cparent['Customfieldvalue']['customfield_id'];



            }



            $selected_cfields=array_unique(array_values($cparents));



            $selected_cvalues=array_keys($cparents);











            foreach($selected_cfields as $fieldid) {



                $temp_array= $this->Customfield->findById($fieldid);



                $selected_cfieldnames[]=$temp_array['Customfield']['custom_name'];



            }



            unset($temp_array);
            unset($fieldid);



            foreach($selected_cfields as $fieldid) {



                $temp_array= $this->Customfieldvalue->find('list',array('fields'=>array('Customfieldvalue.id', 'Customfieldvalue.custom_value'),'conditions' =>'Customfieldvalue.customfield_id  IN ('.$fieldid.')'));



                $selected_cfieldvalues[$fieldid]=$temp_array;



            }







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



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



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



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



        }







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



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







        ####### Code for fetching data to be displayed on Edit Category Page Ends here(Added By shyam) ############



        $this->layout = 'adm';



    }











    function delete($id) {



        $this->__validateLoginStatus();



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



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



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



            exit();



        }



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

        $catname	=	$cat["Category"]["cname"];



        if(sizeof($cat["Childcategory"]) > 0) {
            $this->Session->setFlash(__(' Category '.$catname.' has subcategories . Please remove subcategories.', '/categories'));
        }
        elseif(sizeof($cat["Product"]) > 0) {
            //$this->Session->setFlash(__(' Category '.$catname.' has products under it . Please remove products.', '/categories'));
            $del_status=0;
            foreach($cat["Product"] as $val) {
                if($val["status"] <> 'D')
                    $del_status=1;
            }
            if($del_status==1)
                $this->Session->setFlash(__(' Category '.$catname.' has products under it . Please remove products.', '/categories'));
            else {
                $this->Category->del($id,true);
                $this->Session->setFlash(__(' Category '.$catname.' has been deleted Successfully.', '/categories'));
            }
        }
        else {
            $this->Category->del($id,true);
            $this->Session->setFlash(__(' Category '.$catname.' has been deleted Successfully.', '/categories'));
        }
        $this->redirect('index');
    }











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



    function show_cat($name='',$catid=0) {

        

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



            $this->Setting->load();



        }



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



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



        global $page_title;



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


        $page_title			=	$name;
        if($cnfg["page_title"] <> '')
            $page_title.=' - '.$cnfg["page_title"];



        $this->pageTitle = $page_title	;



        global $currency;



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



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







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



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

        $footer_links = $this->Cmspage->find('list',array('conditions' => array('Cmspage.type' => 'content','Cmspage.status' => 'Y')));
        $this->set('footerlinks', $footer_links);

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







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



        $cdet = $this->Category->find('first', array('conditions' => array('Category.id' => $catid,'Category.id' => $catid)));







        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);







            //$data = $this->paginate('Product', array('Product.category_id =' => $id,'Product.Status = '=> 'A','Product.Stock > '=> 0 ));



            //$pdct	=	$data;











           //echo $criteria="Product.category_id='".$id."' AND Product.status = 'A' AND Product.stock > 0";

             $criteria="Product.category_id='".$id."' AND Product.status = 'A'";



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



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

//print_r($data);exit;

            $pdct	=	$data;







            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_img"] == "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'));



        }



    }



}



?>