<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
// +----------------------------------------------------------------------+
// | admin control panel page                                       |
// | File name : search.php                                                  |
// | PHP version >= 5.2                                                   |
// +----------------------------------------------------------------------+
// | Author: Meena Susan Joseph <meena.s@armiasystems.com>              |
// +----------------------------------------------------------------------+
// | Copyrights Armia Systems ? 2010                                      |
// | All rights reserved                                                  |
// +------------------------------------------------------

class ControllerSearch extends BaseController
{
	/*
	Initializing the models
	*/
        public function init()
        {
            parent::init();
		$this->_common	 		= new ModelCommon;
        $this->_session = new LibSession();
        // get Site Settings ***************************************
        $settings = $this->_common->selectResult('settings','*');

        foreach($settings as $field ) {
            $setting[$field->settingfield]= $field->value;
        } // End Foreach

        $this->view->setting = $setting;
        // get Site Settings end ***************************************
        // Social Plugins **********************************************
        $_SESSION['facebookKey'] = array('enableFb' =>$setting['enableFb'], 'facebookAppId' => $setting['facebookAppId'], 'facebookSecret' => $setting['facebookSecret']);
        $_SESSION['twitterKey'] = array('enableTwitter' => $setting['enableTwitter'], 'twitterConsumerKey' => $setting['twitterConsumerKey'], 'twitterConsumerSecret' => $setting['twitterConsumerSecret']);
        // Social Plugins End ******************************************
        /*------------- Categories End -------------------*/
        $categroy_flag = true;
        $categories = $this->_common->getAllData('nCategoryId, vCategoryDesc', 'category','WHERE nParentId = 0');
        if($categories) {
            foreach($categories as $cat_val) {
                $products = $this->_common->selectResult('product','nBusId, nCatid, Title', "nCatid = {$cat_val->nCategoryId} LIMIT 0, 10");
                $category[$cat_val->nCategoryId] = array();
                if($products) {
                    foreach($products as $prd_val) {
                        $category[$cat_val->nCategoryId][$prd_val->nBusId] = $prd_val->Title;
                    }
                }
                unset($products);

                $category_title[$cat_val->nCategoryId] = $cat_val->vCategoryDesc;
            }
        }
        else {
            $categroy_flag = false;
        }
        $this->view->category_flag      = $categroy_flag;
        $this->view->category           = $category;
        $this->view->category_title     = $category_title;
        /*------------- Categories End -------------------*/

        // Search Fields **********************************************
        $txtsearch = '';
        //$listingFields = $this->_common->selectResult("productdesc","vFldname, vFlddesc","nStatus='1' AND vFldSearch='1'");
        $listingFields = $this->_common->selectResult("productdesc","vFldname, vFlddesc","nStatus='1' AND vFldname IN('Title','Description')");
        // Search Fields End ******************************************
        $fieldList = array();

        if(!empty($listingFields)) {
            foreach($listingFields as $fields) {
                $fieldList[$fields->vFldname] = $fields->vFlddesc;
            } // End Foreach
        }// End Listing Fields
        $this->view->listingFields      = $fieldList;
        $this->view->txtsearch        = $txtsearch;

        }
    
        public function index($page=1)
	{           
            //Index / Login
            //$this->view->setLayout('common');
            // if the user session exist , redirect to users page           
           
           

            $status = $selectFields = $searchElement = '';
            
            if($page=="" || $page==0)
            {
               $page 			= $this->get('page');
                if(!is_numeric($page))
                  $page = 1;
                if(isset($page) && $page <=0 ){
                  $this->redirect('index/listing');
                }
            }


	    if($this->isPost())
            { 
//                SELECT nBusId, nCatid, Title,dPostDate,Image,alias, Description FROM EasyIndex_product WHERE Title LIKE 'rmi'  and nStatus='1' 
//                UNION ALL
//                SELECT nBusId, nCatid, Title,dPostDate,Image,alias, Description FROM EasyIndex_product WHERE Description LIKE 'rmi'  and nStatus='1'
//                UNION ALL 
//                SELECT nBusId, nCatid, Title,dPostDate,Image,alias, Description FROM EasyIndex_product WHERE Title LIKE 'rmi%' AND Title  NOT LIKE 'rmi'  and nStatus='1' 
//                UNION ALL
//                SELECT nBusId, nCatid, Title,dPostDate,Image,alias, Description FROM EasyIndex_product WHERE Description LIKE 'rmi%' AND Description  NOT LIKE 'rmi' and nStatus='1'
//                UNION ALL 
//                SELECT nBusId, nCatid, Title,dPostDate,Image,alias, Description FROM EasyIndex_product WHERE Title LIKE '%rmi%'  AND Title  NOT LIKE 'rmi,rmi%' OR Description LIKE '%rmi%' AND Description  NOT LIKE 'rmi,rmi%' and nStatus='1' 
                
                $txtsearch = addslashes(($this->post('txtsearch')!='') ? $this->post('txtsearch') :$this->get('txtsearch'));
                //$txtsearchField = addslashes($_POST['txtsearchField']);
//                $this->

//                LibSession::set('user_pass',md5('kamal'),'business');
                //$searchElement .=$txtsearchField." LIKE '%".$txtsearch."%' and nStatus='1'";
                //$searchElement .="Title LIKE '%".$txtsearch."%' OR Description LIKE '%".$txtsearch."%' and nStatus='1'";
                $searchElement .="Title LIKE '%".$txtsearch."%' and nStatus='1'";
                $searchElement2 .="Description LIKE '%".$txtsearch."%' and nStatus='1'";
                
                $this->_session->set('searchval',$searchElement);
                $this->_session->set('searchval2',$searchElement2);
                $this->_session->set('txtsearch',$txtsearch);
                $selectFields .= 'nBusId, nCatid, Title,dPostDate,Image,alias';
                //Description field exists
                $activeFields = $this->_common->selectResult("productdesc","vFldname, vFlddesc","nStatus='1' AND LOWER(vFldname)='".strtolower('Description')."'");
                if(!empty($activeFields)) {
                    $selectFields .= ', '.$activeFields[0]->vFldname;
                }
                
                //$searchResults = $this->_common->selectResult("product", $selectFields, $searchElement);
                $searchResults = $this->_common->selectResultUnion("product", $selectFields, $searchElement,$searchElement2);                
                //  print_r($searchResults);
                //--------------------------
                    //$cntComments                = (integer)$this->_common->checkExists('product',"nBusId","$searchElement");
                    $cntComments                = count($searchResults);
                    $this->view->pageCount      =  ceil($cntComments / PAGE_LIST_COUNT);
                    //$order  = "nFeatured DESC,dPostDate DESC";
                    //$searchResults    =  $this->_common->getDatas($selectFields,"product","","","$searchElement","","$order","",$page);
                    $searchResults    =  $this->_common->getDatasUnion($selectFields,"product","","","$searchElement","$searchElement2","","$order","",$page);
                    $this->view->page           =  ($page) >  0 ? $page : 1;

                //--------------------------
                //  print_r($this->view->resProducts);


                 foreach($searchResults as $key =>$val)
                 { 
                   $table  = 'productrating';
                   $field  = 'round( COALESCE(SUM( `nRate` ) / COUNT( `nId` ),0) ) AS RATE';
                   $order  = "";
                   $where  = "nProductId = '".$val->nBusId."'";
                   $this->view->productRating[$val->nBusId] = $this->_common->selectRow($table,$field,$where);
                 }

                

            }
            elseif($this->_session->get('searchval')!="")
            {
                $searchElement = $this->_session->get('searchval');
                $searchElement2 = $this->_session->get('searchval2');
                $txtsearch      = $this->_session->get('txtsearch');
                $selectFields .= 'nBusId, nCatid, Title,dPostDate,Image,alias';
                //Description field exists
                $activeFields = $this->_common->selectResult("productdesc","vFldname, vFlddesc","nStatus='1' AND LOWER(vFldname)='".strtolower('Description')."'");
                if(!empty($activeFields)) {
                    $selectFields .= ', '.$activeFields[0]->vFldname.',dPostDate';
                }

                //$searchResults = $this->_common->selectResult("product", $selectFields, $searchElement);
                  $searchResults = $this->_common->selectResultUnion("product", $selectFields, $searchElement,$searchElement2);
//                print_r($searchResults);
                //--------------------------
                    //$cntComments                = (integer)$this->_common->checkExists('product',"nBusId","$searchElement");
                     $cntComments                = count($searchResults);
                    $this->view->pageCount      =  ceil($cntComments / PAGE_LIST_COUNT);
                   // $order  = "nFeatured DESC,dPostDate DESC";
                    //$searchResults    =  $this->_common->getDatas($selectFields,"product","","","$searchElement","","$order","",$page);
                    $searchResults    =  $this->_common->getDatasUnion($selectFields,"product","","","$searchElement","$searchElement2","","$order","",$page);
                    $this->view->page           =  ($page) >  0 ? $page : 1;

                //--------------------------
//                print_r($this->view->resProducts);


                 foreach($searchResults as $key =>$val)
                 {
                   $table  = 'productrating';
                   $field  = 'round( COALESCE(SUM( `nRate` ) / COUNT( `nId` ),0) ) AS RATE';
                   $order  = "";
                   $where  = "nProductId = '".$val->nBusId."'";
                   $this->view->productRating[$val->nBusId] = $this->_common->selectRow($table,$field,$where);
                 }
            }


            //$this->view->listingFields      = $fieldList;
            //echopre1($searchField);
            $this->view->searchField        = $searchField;
            $this->view->searchResults      = $searchResults;
            $this->view->txtsearch        = $txtsearch;
            
                
	} // End Function
    
        public function advanced($page="")
	{
            if($page=="" || $page==0)
            {
               $this->_session->set('searchval','');
               $page 			= $this->get('page');
                if(!is_numeric($page))
                  $page = 1;
                if(isset($page) && $page <=0 ){
                  $this->redirect('index/listing');
                }
            }
            if($this->isPost())
            {//echo "entered post";exit;
                $selectFields   = 'vFldname,vFlddesc';
                $where          = "vFldSearch='1' AND nStatus='1'";
                $this->view->searchFields = $this->_common->selectResult("productdesc", $selectFields, $where);
              
                foreach($this->view->searchFields as $post)
                {
                  ///echo $post->vFlddesc.'field value'. addslashes($_POST[$post->vFldname]); echo "<br>";
				  if($_POST[$post->vFldname]!=''){
                    $searchElement .=$post->vFldname." LIKE '%".addslashes($_POST[$post->vFldname])."%' AND ";
					}
                }
//                $searchElement=substr($searchElement,0,strlen($searchElement)-4);
                $searchElement .= " nStatus='1'";
            //echo $searchElement;exit;
                $selectFields1 .= 'nBusId, nCatid, Title,Image,alias';
                //Description field exists
                $activeFields = $this->_common->selectResult("productdesc","vFldname, vFlddesc","nStatus='1' AND LOWER(vFldname)='".strtolower('Description')."'");
                //echo "ff".$searchElement;exit;
                if(!empty($activeFields)) {
                    $selectFields1 .= ', '.$activeFields[0]->vFldname.',dPostDate';
                }
//echo "ff".$selectFields1;exit;
//                $searchResults = $this->_common->selectResult("product", $selectFields1, $searchElement);
//                //$this->view->listingFields      = $fieldList;
//                $this->view->searchField        = $searchField;
//                $this->view->searchResults      = $searchResults;
                
                
                //--------------------------
                    $this->_session->set('searchval',$searchElement);
         //echo "ff".$searchElement ;exit;
                    $cntComments                = (integer)$this->_common->checkExists('product',"nBusId","$searchElement");
                    $this->view->pageCount      =  ceil($cntComments / PAGE_LIST_COUNT);
                //echo   $this->view->pageCount;exit;
                    $order  = "nFeatured DESC,dPostDate DESC";
                    $searchResults    =  $this->_common->getDatas($selectFields1,"product","","","$searchElement","","$order","",$page);
                    $this->view->page           =  ($page) >  0 ? $page : 1;
                     $this->view->searchResults      = $searchResults;

                //--------------------------
                
                //echo"<pre>";print_r($searchResults);echo"</pre>";
                
                $this->view->setRender('search','advresult');
//                $this->view->setRender("index","offers");
//                $this->renderLayout('search','index');
//                die;

                foreach($searchResults as $key =>$val)
                 {
                   $table  = 'productrating';
                   $field  = 'round( COALESCE(SUM( `nRate` ) / COUNT( `nId` ),0) ) AS RATE';
                   $order  = "";
                   $where  = "nProductId = '".$val->nBusId."'";
                   $this->view->productRating[$val->nBusId] = $this->_common->selectRow($table,$field,$where);
                 }



            }
            elseif($this->_session->get('searchval')!="")
            {
                $searchElement = $this->_session->get('searchval');
                $selectFields .= 'nBusId, nCatid, Title,Image,alias';
                //Description field exists
                $activeFields = $this->_common->selectResult("productdesc","vFldname, vFlddesc","nStatus='1' AND LOWER(vFldname)='".strtolower('Description')."'");
                if(!empty($activeFields)) {
                    $selectFields .= ', '.$activeFields[0]->vFldname.',dPostDate';
                }

//                $searchResults = $this->_common->selectResult("product", $selectFields1, $searchElement);
//                //$this->view->listingFields      = $fieldList;
//                $this->view->searchField        = $searchField;
//                $this->view->searchResults      = $searchResults;

                //--------------------------
                $cntComments                = (integer)$this->_common->checkExists('product',"nBusId","$searchElement");
                $this->view->pageCount      =  ceil($cntComments / PAGE_LIST_COUNT);
                $order  = "nFeatured DESC,dPostDate DESC";
                $searchResults    =  $this->_common->getDatas($selectFields,"product","","","$searchElement","","$order","",$page);
				//echo"<pre>";print_r(searchResults);echo"</pre>";
                $this->view->searchField        = $searchField;
                $this->view->searchResults      = $searchResults;
                $this->view->page           =  ($page) >  0 ? $page : 1;

                //--------------------------


                $this->view->setRender('search','advresult');


                foreach($searchResults as $key =>$val)
                 {
                   $table  = 'productrating';
                   $field  = 'round( COALESCE(SUM( `nRate` ) / COUNT( `nId` ),0) ) AS RATE';
                   $order  = "";
                   $where  = "nProductId = '".$val->nBusId."'";
                   $this->view->productRating[$val->nBusId] = $this->_common->selectRow($table,$field,$where);
                 }
            }
            else
            {
                //The new
                $selectFields   = 'vFldname,vFlddesc';
                $where          = "vFldSearch='1' AND nStatus='1'";
                $this->view->searchFields = $this->_common->selectResult("productdesc", $selectFields, $where);
            }
            
        } // End Function


        public function advresult($dataSearch='')
	{



	} // End Function
       

}
?>