<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
// +----------------------------------------------------------------------+
// | This page is for user section management. Login checking , new user registration, user listing etc.                                      |
// | File name : index.php                                                  |
// | PHP version >= 5.2                                                   |
// | Created On	: 	Nov 17 2011                                               |
// +----------------------------------------------------------------------+
 // +----------------------------------------------------------------------+
// | Copyrights Armia Systems ? 2010                                      |
// | All rights reserved                                                  |
// +------------------------------------------------------

class ControllerIndex extends BaseController
{


    public $comment='';
    public $id='';
    public $email='';
    public $name='';
    public $siteSettings;
    public $color='';
    protected $_session;

	/*
		construction function. we can initialize the models here
	*/
     public function init()
     {

    
       
        parent::init();
        $this->_common	= new ModelCommon;
        $this->_postads = new ModelPostads;
        $this->_libEmailSend = new LibEmailsend();
        $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;
        $this->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','','ASC','vRoute');
        if($categories) {
            foreach($categories as $cat_val) {
                $products = $this->_common->selectResult('product','nBusId, nCatid, Title', "nCatid = {$cat_val->nCategoryId} AND nStatus ='1' 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 -------------------*/
//-----------------------Twitter login-----------------
/*  COMMENT TWITTER LOGIN SECTION- PHP 5.4 FIX*/
       /* include 'apps/twitter-oauth/lib/EpiCurl.php';
        include 'apps/twitter-oauth/lib/EpiOAuth.php';
        include 'apps/twitter-oauth/lib/EpiTwitter.php';

        $consumer_key = $_SESSION['twitterKey']['twitterConsumerKey'];
        $consumer_secret = $_SESSION['twitterKey']['twitterConsumerSecret'];

        $twitterObj = new EpiTwitter($consumer_key, $consumer_secret);

        $this->view->url = $twitterObj->getAuthorizationUrl();*//*  COMMENT TWITTER LOGIN SECTION- PHP 5.4 FIX*/

         //-----------------------Twitter login-----------------

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


      }

    /*
    function to load the index template
    */
    public function index($autoRegister='')
    {

       // display_errors(1); die("G");
        if($_SESSION['SITELISTINGMODE']!='product')
            {
        setcookie('errorLogin', '',time()-10);
            }
        //-------Twitter Login-----------------------
            /*  COMMENT TWITTER LOGIN SECTION- PHP 5.4 FIX*/
      /* require_once('apps/twitteroauth/twitteroauth.php');
        //require_once('apps/twitteroauth/config.php');


        if (isset($_REQUEST['oauth_token']) && $_SESSION['oauth_token'] !== $_REQUEST['oauth_token']) {
              $_SESSION['oauth_status'] = 'oldtoken';
              session_start();
              session_destroy();
              //header('Location: ./clearsessions.php');
        }
        $consumer_key = $_SESSION['twitterKey']['twitterConsumerKey'];
        $consumer_secret = $_SESSION['twitterKey']['twitterConsumerSecret'];
         $connection = new TwitterOAuth($consumer_key, $consumer_secret, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);

         //$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);

        $token = $connection->getAccessToken($_REQUEST['oauth_verifier']);*/
       /*  COMMENT TWITTER LOGIN SECTION- PHP 5.4 FIX*/

        //$consumer_key = $_SESSION['twitterKey']['twitterConsumerKey'];
        //$consumer_secret = $_SESSION['twitterKey']['twitterConsumerSecret'];
        //$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
        
        $oauth_token = $_GET['oauth_token'];
        if($oauth_token != '')
        {
            require_once('apps/twitter-oauth/twitteroauth-master/autoload.php');
            $oauth_token=$_SESSION['oauth_token'];unset($_SESSION['oauth_token']);
            $consumer_key = $_SESSION['twitterKey']['twitterConsumerKey'];
            $consumer_secret = $_SESSION['twitterKey']['twitterConsumerSecret'];
            $connection = new Abraham\TwitterOAuth\TwitterOAuth($consumer_key, $consumer_secret);
            //necessary to get access token other wise u will not have permision to get user info
            $params=array("oauth_verifier" => $_GET['oauth_verifier'],"oauth_token"=>$_GET['oauth_token']);
            $access_token = $connection->oauth("oauth/access_token", $params);
            //now again create new instance using updated return oauth_token and oauth_token_secret because old one expired if u dont u this u will also get token expired error
            $connection = new Abraham\TwitterOAuth\TwitterOAuth($consumer_key, $consumer_secret, $access_token['oauth_token'],$access_token['oauth_token_secret']);
            $content = $connection->get("account/verify_credentials");        
            $token['screen_name'] = $content->screen_name;
            $token['user_id'] = $content->id;
            //$twitterObj->setToken($_GET['oauth_token']);
            //$token = $twitterObj->getAccessToken();
            //$twitterObj->setToken($token->oauth_token, $token->oauth_token_secret);

             if($token['screen_name']!='') {
                // Validate Userlogin
                $userLogin = $this->_common->selectRecord("users","nUserId,vLoginName,vEmail,vFirstName,vLastName,vStatus,nSocialUserId","nSocialUserId ='".$token['user_id']."'");
                    if(sizeof($userLogin) > 0){
                       if($userLogin->vStatus == 1){
                            $_SESSION['user'] =  array("userID" => $userLogin->nUserId,
                                                        "userName" =>$userLogin->vLoginName,
                                                         "userEmail" =>$userLogin->vEmail,
                                                         "userFirstName" =>$userLogin->vFirstName,
                                                         "userLastName" =>$userLogin->vLastName);
                            $_SESSION['loggedin'] = 1;  // For forum
                            $_SESSION['fbLogout'] = 0;
                            $_SESSION['forum_user'] = $userLogin->vLoginName; // For forum

                            unset($_SESSION['errorLogin']);

                            $this->_session->set('user_id',$userLogin->nUserId,'business');

                            $status = 1; // Logged In
                            //$this->redirect('business/index/dashboard');
                            header('location:'.BASE_URL.'/business/index/dashboard');
                        } else {
                            $status = 0; // Your account is no longer active!?>
                            <script>
                                //window.location.href="<?php echo ConfigUrl::base();?>";
                                alert("Not active");
                            </script>
                            <?php
                        }
                     } else { // Register

                         $arrUser = array();
                         $arrUser['vLoginName'] = $token['screen_name'];
                         $arrUser['vFirstName'] = $token['screen_name'];
                         $arrUser['dDateReg'] = 'NOW()';
                         $arrUser['vStatus'] = '1';
                         $arrUser['vAlertStatus'] = 'Y';
                         $arrUser['vNLStatus'] = 'N';
                         $arrUser['nSocialUserId'] = $token['user_id'];

                         $newUser = $this->_common->addFields("users", $arrUser);
                         $query="INSERT INTO `users`
                                 (`username`,`fname`,`reggedOn`, `nSocialUserId`)
                                 VALUES
                                 (
                                 '".$arrUser['vLoginName']."',
                                 '".$arrUser['vFirstName']."',
                                 '".time()."',
                                 '".$arrUser['nSocialUserId']."'
                                 )";

                         $this->_common->execute($query);

                         $userLogin = $this->_common->selectRecord("users","nUserId,vLoginName,vEmail,vFirstName,vLastName,vStatus,nSocialUserId","nUserId ='".$newUser."'");

                         $_SESSION['user'] =  array("userID" => $userLogin->nUserId,
                                                        "userName" =>$userLogin->vLoginName,

                                                         "userFirstName" =>$userLogin->vFirstName,
                                                         );
                         $_SESSION['fbLogout'] = 0;
                         $_SESSION['loggedin'] = 1;  // For forum
                         $_SESSION['forum_user'] = $userLogin->vLoginName;  // For forum
                         unset($_SESSION['errorLogin']);
                         $this->_session->set('user_id',$userLogin->nUserId,'business');
                         $status = 1; // Logged In
                         //$this->redirect('business/index/dashboard/1');
                         header('location:'.BASE_URL.'/business/index/dashboard/1');
                     }

            } // End IsPost
        }
        //-------Twitter Login-----------------------

        //>>>>>>>>>>>>>>    UPDATE VISTOR STAT FOR THE MONTH  <<<<<<<<<<<<<<<<<<<<<

                     if(!isset($_COOKIE['monthly_tracking_coockie']))
                     {

                           $currentMonth     = date ( 'm' ,time()  );

                           $entryExists      =  (integer)$this->_common->checkExists('statistics',"nId"," MONTH(dTrackingDate)= '$currentMonth'");

                           $entryExists      =  ($entryExists>0) ? true : false;

                           if($entryExists)  // A ENTRY OF THIS MONTH EXISTS IN DB. JUST INCREMENT THE COUNTER.
                           {

                                $table            = 'statistics';
                                $field            = 'nCount';
                                $order            = "";
                                $where            = "MONTH(dTrackingDate)='".$currentMonth."'";

                                $existingCount    = $this->_common->selectRow($table,$field,$where);

                                $arrUpdate       = array('nCount'=>($existingCount+1));
                                $this->_common->updateFields("statistics",$arrUpdate,"MONTH(dTrackingDate)='".$currentMonth."'");
                           }
                           else  //   IF THERE IS NO ENTRY OF THIS MONTH IN DB.THEN CREATE A ENTRY.
                           {
                                $table            = 'statistics';
                                $field            = 'NOW()';
                                $order            = "";
                                $where            = "";
                                $timeStamp        = $this->_common->selectRow($table,$field,$where);

                                $arr         =   array("nCount"=>1,"dTrackingDate"=>$timeStamp);
                                $this->_common->addFields("statistics",$arr);
                           }


                           setcookie('monthly_tracking_coockie',time(),(time()+3600*24*30));

                     }
                     else if(trim($_COOKIE['monthly_tracking_coockie'])!='') // A COOKIE EXISTS. CHECK FOR THE NEW MONTH.
                     {


                         $currentMonth     = date ( 'm' ,$_COOKIE['monthly_tracking_coockie']  );  // 06 OR 12

                         $entryExists      =  (integer)$this->_common->checkExists('statistics',"nId"," MONTH(dTrackingDate)= '$currentMonth'");

                         $entryExists      =  ($entryExists>0) ? true : false;

                         if($entryExists==false)
                         {
                             $table            = 'statistics';
                             $field            = 'NOW()';
                             $order            = "";
                             $where            = "";
                             $timeStamp        = $this->_common->selectRow($table,$field,$where);

                             $arr         =   array("nCount"=>1,"dTrackingDate"=>$timeStamp);
                             $this->_common->addFields("statistics",$arr);

                             setcookie('monthly_tracking_coockie',time(),(time()+3600*24*30));  // RESET USER COOCKIE FOR THE NEXT MONTH.

                         }
                     }

        //>>>>>>>>>>>>>>    UPDATE VISTOR STAT FOR THE MONTH  <<<<<<<<<<<<<<<<<<<<<






        //fetch latest wishes


        $this->view->metaTitle           =  'Header';
        $this->view->leftMenu =  'left_main';
        $this->view->setLayout('home');

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

        if(SITE_MODE=="product")
        {
            $this->redirect('index/viewlisting');
        }


        $table      = 'admin';
        $selFields  = 'CAT.vCategoryDesc,CAT.nCategoryId,CAT.nParentId';
        $table1     = 'category CAT';
        $table2     = 'product PDT';
        $join       = 'LEFT JOIN';
        $on      = 'PDT.nCatid = CAT.nCategoryId';
        $pagination = -1;
        $limit      = '0,13';
        $orderby    = 'COUNT(PDT.nCatid) DESC ';
        $groupby    = 'PDT.nCatid';
        $where      =  '';
//        $where  = "vAdminUsername ='".$userName."' AND vAdminPassword  ='".md5($userPass)."'";
        $this->view->popularclassifieds = $this->_common->getDatas($selFields,$table1,$table2,$join,$where, $groupby,$orderby,$limit,$pagination,$on);
//        $table      = 'product';

        $selFields  = 'Title,nBusId,nCatid,alias';
        $table1     = 'product';
        $table2     = '';
        $join       = '';
        $on         = '';
        $pagination = -1;
        $limit      = '0,13';
        $orderby    = 'maxSearches DESC';
        $groupby    = '';
        $this->view->popularsearches = $this->_common->getDatas($selFields,$table1,$table2,$join,$where, $groupby,$orderby,$limit,$pagination,$on);
//         $this->view->setLayout("home");
        //----------------Category and subcategory listing--------------
        $categories = $this->_common->getAllData('nCategoryId, vCategoryDesc', 'category','','WHERE nParentId = 0','','ASC','vRoute');
        if($categories) {
            foreach($categories as $cat_val) {
                $sub_categories = $this->_common->getAllData('nCategoryId, vCategoryDesc', 'category','','WHERE nParentId = '.$cat_val->nCategoryId,'','ASC','vRoute');
                //$sub_categories = $this->_common->selectResult('product','nBusId, nCatid, Title', "nCatid = {$cat_val->nCategoryId} AND nStatus ='1' LIMIT 0, 10");
                $category[$cat_val->nCategoryId] = array();
                //echo"<pre>";print_r($sub_categories);echo"</pre>";
                if($sub_categories) {
                    //echo "if";
                    foreach($sub_categories as $sub_val) {
                        $category[$cat_val->nCategoryId][$sub_val->nCategoryId] = array('title'=> $sub_val->vCategoryDesc,'type'=> '1');
                       // $category[$cat_val->nCategoryId]['type']='1';
                    }
                     //$category['product_listing_flag']=0;
                }
                else{
                   // echo"else";
                    $sub_categories = $this->_common->selectResult('product','nBusId, nCatid, Title,alias', "nParentCatId = {$cat_val->nCategoryId} AND nCatid =0 AND nStatus ='1'  ORDER BY nFeatured DESC LIMIT 0, 10 ");
                    //echo"<pre>";print_r($sub_categories);echo"</pre>";
                    if($sub_categories) {
                    //echo "if";
                    foreach($sub_categories as $sub_val) {
                        //echo"<pre>";print_r($sub_categories);echo"</pre>";
                        $category[$cat_val->nCategoryId][$sub_val->alias] = array('title' => $sub_val->Title, 'type' => '2');
                     //  $category[$cat_val->nCategoryId][$sub_val->nBusId]['type']='2';
                    }
                    //$category[0]['product_listing_flag']=1;
                }
                }
                unset($sub_categories);
                //echo"<pre>";print_r($category);echo"</pre>";

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


    }

    /*
    Function to logout the user
    */
    public function twitterlogin()
    {        
        require_once('apps/twitter-oauth/twitteroauth-master/autoload.php');
        //require_once('apps/twitteroauth/config.php');
     /* Build TwitterOAuth object with client credentials. */
        $consumer_key = $_SESSION['twitterKey']['twitterConsumerKey'];
        $consumer_secret = $_SESSION['twitterKey']['twitterConsumerSecret'];

        $connection = new Abraham\TwitterOAuth\TwitterOAuth($consumer_key, $consumer_secret);
        $oauth_callback = (($_SERVER['SERVER_PORT'] == 80)?'http://':'https://').$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
        $oauth_callback = str_replace('/index.php/twitterlogin', '', $oauth_callback);
        $temporary_credentials = $connection->oauth('oauth/request_token', array("oauth_callback" => $oauth_callback)); 

        $_SESSION['oauth_token']=$temporary_credentials['oauth_token'];       
        $_SESSION['oauth_token_secret']=$temporary_credentials['oauth_token_secret'];
        $url = $connection->url("oauth/authorize", array("oauth_token" => $temporary_credentials['oauth_token']));
        /* If last connection failed don't display authorization link. */
        header('Location: ' . $url); 
    }


    public function clearsessions()
    {
        session_start();
        session_destroy();

    }
    /*
    Function to logout the user
    */
    public function logout()
    {
	//echopre($_SESSION);
            session_destroy();
			session_unset($_SESSION['user']);

			 //echopre1($_SESSION);
       header("location:".ConfigUrl::base());
	    $this->view->disableView();
 	   exit();
    }

    /*
     * Function to load business module
     */

    /*
    public function login()
   {
//       echo "am here";
       LibSession::set('user_login','rajath','business');
       LibSession::set('user_pass',md5('kamal'),'business');
       LibSession::set('user_id',1,'business');
//       echo LibSession::get('user_login','business'); die;
       $this->switchmodule(ConfigUrl::root().'business/index/dashboard');
       die;
   }
     */

   public function listing($catId=0,$subCatId=0,$page=0)
   {
       setcookie('errorLogin', '',time()-10);
       	if($page=="")
       	$page 			= $this->get('page');
        if(!is_numeric($page))
	  	$page = 1;
        if(isset($page) && $page <=0 ){
          $this->redirect('index/listing');
        }


        $listFields  = array();
        $table  = 'productdesc';
        $field  = 'vFldname';
        $order  = " ORDER BY id ASC";
        $where  = "nStatus = '1'";
        $listFieldString='';
        $listFields   = $this->_common->getListFields($table,$field,$order,$where);
        if(sizeof($listFields)>0)
        {
            foreach ($listFields as $lRecord)
            {
                $listFieldString.=$lRecord->vFldname.',';
            }
            $listFieldString.=$listFieldString.'nBusId,';
        }



//        $listFieldString=substr($listFieldString,0,strlen($listFieldString)-1);
        $listArray   = array();
        $table  = 'product';

        // conditional check for cat and subcat listing
        if($subCatId != '' && $subCatId != 0 && $subCatId != 'all')
        	$where  = "nCatid = '$subCatId' AND nStatus = '1'";
        elseif($catId != '' && $catId != 0 && $catId != 'all')
        	$where  = "nParentCatId = '$catId' AND nStatus = '1'";



        $field  = substr($listFieldString,0,strlen($listFieldString)-1).',alias';
        $order  = " ORDER BY dPostDate DESC";
        $listArray   = $this->_common->getTopList($table,$field,$order,$where);
        if(sizeof($listArray)>0)
        {
            $this->view->listFields = explode(',',$field);
            $this->view->listArray  = $listArray;
            $cntComments                =  (integer)$this->_common->checkExists('product',"nBusId","$where");
            $this->view->pageCount      =  ceil($cntComments / PAGE_LIST_COUNT);
            $order  = "nFeatured DESC,dPostDate DESC";
            $this->view->resProducts    =  $this->_common->getDatas($field,$table,"","","$where","","$order","",$page);
            $this->view->page           =  ($page) >  0 ? $page : 1;
            $this->view->productId      = $catId;
            $this->view->page           = $page;
        }


        if($catId == '' || $catId == 0)
        	$this->view->catId = 'all';
        else {
        	$this->view->catId = $catId;
         	$this->view->catName = $this->_common->selectRow('category','vCategoryDesc','nCategoryId='.$catId);
                PageContext::$customTitle = $this->view->catName.' - '.META_TITLE;
        }


     	if($subCatId == '' || $subCatId == 0)
        	$this->view->subCatId = 'all';
        else {
        	$this->view->subCatId = $subCatId;
         	$this->view->subCatName = $this->_common->selectRow('category','vCategoryDesc','nCategoryId='.$subCatId);
        }


         /*
        $this->view->catId              = ($catId == '' || $catId == 0)?'all':$catId;
        $this->view->subCatId           = ($subCatId == '' || $subCatId == 0)?'all':$subCatId;
        */
   }

//   public function pagelisting($listId,$productId=0,$page=1)
//   {
//
//       //echopre($_COOKIE);
//       setcookie('errorLogin', '',time()-10);
//         //echopre($_COOKIE);
//        $this->view->userId = LibSession::get('user_id','business');
//
//
//
//        if($productId>0)
//       {
//            $table  = 'product';
//            $field  = '*';
//            $order  = "";
//            $where  = "nBusId = '$productId'";
//            $listFieldString='';
//            $listFields   = $this->_common->getListFields($table,$field,$order,$where);
//            //echopre($listFields);
//            $this->view->listData   = $listFields;
//
//            $zipcode = $this->view->listData[0]->Zipcode;
//            $this->view->isValidZip = (integer)$this->_common->checkExists('tbl_zipcode',"*","zipcode='$zipcode'");
//
//            /* Get the product rate */
//
//            $table  = 'productrating';
//            $field  = 'round( COALESCE(SUM( `nRate` ) / COUNT( `nId` ),0) ) AS RATE';
//            $order  = "";
//            $where  = "nProductId = '$productId'";
//            $this->view->productRating = $this->_common->selectRow($table,$field,$where);
//
//            /* To show the comments */
//            $page 			= $this->get('page');
//            if(!is_numeric($page))
//              $page = 1;
//            if(isset($page) && $page <=0 ){
//              $this->redirect('index/pagelisting');
//            }
//            $field                      = 'vComment,vName,vEmail,dDate,nStatus';
//            $table                      = 'productcomment';
//            $where                      = "nStatus='1' AND nProductId='$productId'";
//            $cntComments                =  (integer)$this->_common->checkExists('productcomment',"nId","nProductId='$productId'");
//            $this->view->pageCount      =  ceil($cntComments / PAGE_LIST_COUNT);
//            $this->view->productComment =  $this->_common->getDatas($field,$table,"","","$where","","","",$page);
//            $this->view->page           =  ($page) >  0 ? $page : 1;
//            $this->view->catid          =  $listId;
//            $this->view->productid      =  $productId;
//
//
//       }
//       else {
//                $productId=$listId;
//                $table  = 'product';
//            $field  = '*';
//            $order  = "";
//            $where  = "nBusId = '$productId'";
//            $listFieldString='';
//            $listFields   = $this->_common->getListFields($table,$field,$order,$where);
//            $this->view->listData   = $listFields;
//            //echopre($listFields);
//
//            $zipcode = $this->view->listData[0]->Zipcode;
//            $this->view->isValidZip = (integer)$this->_common->checkExists('tbl_zipcode',"*","zipcode='$zipcode'");
//
//
//            /* Get the product rate */
//
//            $table  = 'productrating';
//            $field  = 'round( COALESCE(SUM( `nRate` ) / COUNT( `nId` ),0) ) AS RATE';
//            $order  = "";
//            $where  = "nProductId = '$productId'";
//            $this->view->productRating = $this->_common->selectRow($table,$field,$where);
//
//            /* To show the comments */
//            $page 			= $this->get('page');
//            if(!is_numeric($page))
//              $page = 1;
//            if(isset($page) && $page <=0 ){
//              $this->redirect('index/pagelisting');
//            }
//            $field                      = 'vComment,vName,vEmail,dDate,nStatus';
//            $table                      = 'productcomment';
//            $where                      = "nStatus='1' AND nProductId='$productId'";
//            $cntComments                =  (integer)$this->_common->checkExists('productcomment',"nId","nProductId='$productId'");
//            $this->view->pageCount      =  ceil($cntComments / PAGE_LIST_COUNT);
//            $this->view->productComment =  $this->_common->getDatas($field,$table,"","","$where","","","",$page);
//            $this->view->page           =  ($page) >  0 ? $page : 1;
//            $this->view->catid          =  $listId;
//            $this->view->productid      =  $productId;
//       }
//            $table  = 'productdesc';
//            $field  = 'vFldname,vInType';
//            $order  = "";
//            $where  = "";
////            $this->view->fieldVal       = $this->_common->getListFields($table,$field,$order,$where);
//
//            $table  = 'productdesc';
//            $field  = 'vFldname,vInType';
//            $order  = "";
//            $where  = "";
//            $this->view->fieldVal       = $this->_common->getListFields($table,$field,$order,$where);
//
//         $listingFields = $this->_common->selectResult("productdesc","vFldname, vFlddesc,vlink","nStatus='1'");
//         //echopre($listingFields);
//        // Search Fields End ******************************************
//        $fieldList = array();
//        $tablist   = array();
//        $fieldtype  =array();
//        $i         = 0;
//        if(!empty($listingFields)) {
//            foreach($listingFields as $fields) {
//                $fieldList[$fields->vFldname] = $fields->vFlddesc;
//                $tablist[$i]                  =$fields->vFldname;
//                $fieldtype[$fields->vFldname]                  =$fields->vlink;
//                $i++;
//            } // End Foreach
//        }// End Listing Fields
//        //echopre($fieldtype);
//        $this->view->listingFields      = $fieldList;
//        $this->view->tablist            = $tablist;
//         $this->view->fieldtype            = $fieldtype;
//
//
//
//
//
//        $table  = 'productrating';
//        $field  = 'round( COALESCE(SUM( `nRate` ) / COUNT( `nId` ),0) ) AS RATE';
//        $order  = "";
//        $where  = "nProductId = '$productId'";
//        $this->view->productRating = $this->_common->selectRow($table,$field,$where);
//
//
//        if(LibSession::get('tmp_rate_flag_'.$productId,'default'))
//        {
//           $this->view->tmp_rate_flag   = 'set';
//           $this->view->tmp_rate_count = LibSession::get('tmp_rate_count_'.$productId,'default');
//        }
//
//
//        // code starts for breadcrumb
//        $this->view->catName 	= $this->_common->selectRow('category','vCategoryDesc','nCategoryId='.$listFields[0]->nParentCatId);
//      	$this->view->subCatName = $this->_common->selectRow('category','vCategoryDesc','nCategoryId='.$listFields[0]->nCatid);
//        // code ends for breadcrumb
//
//        $this->view->catId  	= $listFields[0]->nParentCatId;
// 		$this->view->subCatId  	= $listFields[0]->nCatid;
//
//        $table  = 'productdesc';
//        $field  = 'vFldname,vInType';
//        $order  = '';
//        $where  = '';
//
//
//   }

    public function pagelisting($alias='',$page=1)
   {

       //echopre($_COOKIE);
       setcookie('errorLogin', '',time()-10);
         //echopre($_COOKIE);
        $this->view->userId = $this->_session->get('user_id','business');



        if($alias!='')
       {
            $table  = 'product';
            $field  = '*';
            $order  = "";
            //$where  = "nBusId = '$productId'";
            $where  = "alias = '$alias'";
            $listFieldString='';
            $listFields   = $this->_common->getListFields($table,$field,$order,$where);
            //print_r($listFields);
            $productId    =   $this->_common->selectRow($table,'nBusId',$where);
          //  echo pre($product_row);
            //$productId = $product_row['nBusId'];



            if($productId >0){
                $this->view->flagProductFound='1';
                $this->view->listData   = $listFields;
                $zipcode = $this->view->listData[0]->Zipcode;
                $this->view->isValidZip = (integer)$this->_common->checkExists('tbl_zipcode',"*","zipcode='$zipcode'");

                /* Get the product rate */

                $table  = 'productrating';
                $field  = 'round( COALESCE(SUM( `nRate` ) / COUNT( `nId` ),0) ) AS RATE';
                $order  = "";
                $where  = "nProductId = '$productId'";

                $this->view->productRating = $this->_common->selectRow($table,$field,$where);

                /* To show the comments */
                //echo $page 			= $this->get('page');
                if(!is_numeric($page))
                  $page = 1;
                if(isset($page) && $page <=0 ){
                  $this->redirect('index/pagelisting');
                }
                $field                      = 'vComment,vName,vEmail,dDate,nStatus';
                $table                      = 'productcomment';
                $where                      = "nStatus='1' AND nProductId='$productId'";
                //$where                      = "nStatus='1' AND alias='$alias'";
                $cntComments                =  (integer)$this->_common->checkExists('productcomment',"nId","nProductId='$productId'");
                $this->view->pageCount      =  ceil($cntComments / PAGE_LIST_COUNT);
                $this->view->productComment =  $this->_common->getDatas($field,$table,"","","$where","","","",$page);
                $this->view->page           =  ($page) >  0 ? $page : 1;
                //$this->view->catid          =  $listId;
                //$this->view->productid      =  $productId;
                             $this->view->alias      =  $alias;



           //}
           /*else {

                //$productId=$listId;
                $table  = 'product';
                $field  = '*';
                $order  = "";
                //$where  = "nBusId = '$productId'";
                $where  = "alias = '$alias'";
                $listFieldString='';
                $listFields   = $this->_common->getListFields($table,$field,$order,$where);
                $productId    =   $this->_common->selectRow($table,'nBusId',$where);
                //$productId  = $listFields['nBusId'];
                $this->view->listData   = $listFields;
                //echopre($listFields);

                $zipcode = $this->view->listData[0]->Zipcode;
                $this->view->isValidZip = (integer)$this->_common->checkExists('tbl_zipcode',"*","zipcode='$zipcode'");


                //* Get the product rate

                $table  = 'productrating';
                $field  = 'round( COALESCE(SUM( `nRate` ) / COUNT( `nId` ),0) ) AS RATE';
                $order  = "";
                $where  = "nProductId = '$productId'";
                $this->view->productRating = $this->_common->selectRow($table,$field,$where);

                //* To show the comments
                $page 			= $this->get('page');
                if(!is_numeric($page))
                  $page = 1;
                if(isset($page) && $page <=0 ){
                  $this->redirect('index/pagelisting');
                }
                $field                      = 'vComment,vName,vEmail,dDate,nStatus';
                $table                      = 'productcomment';
                $where                      = "nStatus='1' AND nProductId='$productId'";
                $cntComments                =  (integer)$this->_common->checkExists('productcomment',"nId","nProductId='$productId'");
                $this->view->pageCount      =  ceil($cntComments / PAGE_LIST_COUNT);
                $this->view->productComment =  $this->_common->getDatas($field,$table,"","","$where","","","",$page);
                $this->view->page           =  ($page) >  0 ? $page : 1;
                //$this->view->catid          =  $listId;
                //$this->view->productid      =  $productId;
                            $this->view->alias      =  $alias;
           }*/
                $table  = 'productdesc';
                $field  = 'vFldname,vInType';
                $order  = "";
                $where  = "";
    //            $this->view->fieldVal       = $this->_common->getListFields($table,$field,$order,$where);

                $table  = 'productdesc';
                $field  = 'vFldname,vInType';
                $order  = "";
                $where  = "";
                $this->view->fieldVal       = $this->_common->getListFields($table,$field,$order,$where);

             $listingFields = $this->_common->selectResult("productdesc","vFldname, vFlddesc,vlink","nStatus='1'");
             //echopre($listingFields);
            // Search Fields End ******************************************
            $fieldList = array();
            $tablist   = array();
            $fieldtype  =array();
            $i         = 0;
            if(!empty($listingFields)) {
                foreach($listingFields as $fields) {
                    $fieldList[$fields->vFldname] = $fields->vFlddesc;
                    $tablist[$i]                  =$fields->vFldname;
                    $fieldtype[$fields->vFldname]                  =$fields->vlink;
                    $i++;
                } // End Foreach
            }// End Listing Fields
            //echopre($fieldtype);
            $this->view->listingFields      = $fieldList;
            $this->view->tablist            = $tablist;
             $this->view->fieldtype            = $fieldtype;





            $table  = 'productrating';
            $field  = 'round( COALESCE(SUM( `nRate` ) / COUNT( `nId` ),0) ) AS RATE';
            $order  = "";
            $where  = "nProductId = '$productId'";
            $this->view->productRating = $this->_common->selectRow($table,$field,$where);


            if($this->_session->get('tmp_rate_flag_'.$productId,'default'))
            {
               $this->view->tmp_rate_flag   = 'set';
               $this->view->tmp_rate_count = $this->_session->get('tmp_rate_count_'.$productId,'default');
            }


            // code starts for breadcrumb
            $this->view->catName 	= $this->_common->selectRow('category','vCategoryDesc','nCategoryId='.$listFields[0]->nParentCatId);
            $this->view->subCatName = $this->_common->selectRow('category','vCategoryDesc','nCategoryId='.$listFields[0]->nCatid);
            // code ends for breadcrumb

            $this->view->catId  	= $listFields[0]->nParentCatId;
                    $this->view->subCatId  	= $listFields[0]->nCatid;

            $table  = 'productdesc';
            $field  = 'vFldname,vInType';
            $order  = '';
            $where  = '';
        }
        else{
            $this->view->flagProductFound='0';

        }
     }
     PageContext::$customTitle = $listFields[0]->Title.' - '.META_TITLE;

   }

      public function viewlisting($catId=0,$page=0)
   {
       setcookie('errorLogin', '',time()-10);
       if($page=="")
       $page 			= $this->get('page');
        if(!is_numeric($page))
	  $page = 1;
        if(isset($page) && $page <=0 ){
          $this->redirect('index/listing');
        }
        $listFields  = array();
        $table  = 'productdesc';
        $field  = 'vFldname';
        $order  = " ORDER BY id ASC";
        $where  = "nStatus = '1'";
        $listFieldString='';
        $listFields   = $this->_common->getListFields($table,$field,$order,$where);
        if(sizeof($listFields)>0)
        {
            foreach ($listFields as $lRecord)
            {
                $listFieldString.=$lRecord->vFldname.',nBusId,';
            }
        }
//        $listFieldString=substr($listFieldString,0,strlen($listFieldString)-1);
        $listArray   = array();
        $table  = 'product';
        $where  = "nStatus = '1'";
        $field  = substr($listFieldString,0,strlen($listFieldString)-1).',alias';
        $order  = " ORDER BY dPostDate DESC";
        $listArray   = $this->_common->getTopList($table,$field,$order,$where);
        if(sizeof($listArray)>0)
        {
            $this->view->listFields = explode(',',$field);
            $this->view->listArray  = $listArray;
            $where  = "nStatus = '1'";
            $cntComments                =  (integer)$this->_common->checkExists('product',"nBusId","$where");
            $this->view->pageCount      =  ceil($cntComments / PAGE_LIST_COUNT);
            $order  = "nFeatured DESC,dPostDate DESC";
            $this->view->resProducts    =  $this->_common->getDatas($field,$table,"","","$where","","$order","",$page);
            $this->view->page           =  ($page) >  0 ? $page : 1;
            $this->view->productId      = $catId;
            $this->view->page           = $page;
        }
		 $this->view->setLayout('productlistinghome');
   }



   public function loadComments($id)
    {


        $this->view->disableLayout();

        $resComments    =    $this->_common->getDatas("*","product","","","nBusId=".$id,"","","","");

        $this->view->resComments    =   $resComments[0];


}

public function loadInquiry($id)
    {


        $this->view->disableLayout();

        $resComments    =    $this->_common->getDatas("*","product","","","nBusId=".$id,"","","","");


         $this->view->resComments    =   $resComments[0];


}




public function insertComments()
{
        $this->view->disableLayout();
        $this->view->disableView();

        $this->view->comment  = $this->comment  = $this->post('comment');
        $this->view->email  =$this->email  = $this->post('email');
        $this->view->name  = $this->name  = $this->post('name');
        $this->view->id  = $this->id  = $this->post('id');

        if($this->view->id!="" && $this->view->comment!="")
        {
            $arr  =   array("vComment"=>addslashes(trim($this->comment)),
                                  "vEmail"=>addslashes(trim($this->email)),
                                  "vName"=>addslashes(trim($this->name)),
                                  "nStatus"=>0,
                                  "dDate"=>date('Y-m-d',time()),
                                  "nProductId"=>$this->id
                                 );

             $this->_common->addFields("productcomment",$arr);
             echo "1";
             exit;
        }
        else
        {
            echo "2";
            exit;
        }
        echo "3";
}

public function insertInquiry()
{


        $this->view->disableLayout();
        $this->view->disableView();

        $this->view->comment  =$comment= $_POST['comment'];//  = $this->post('comment');
        $this->view->email  =$email= $_POST['email'];//  = $this->post('email');
        $this->view->name  =$name= $_POST['name'];//  = $this->post('name');
        $this->view->id  =$id= $_POST['id']; // = $this->post('id');


        $titleAry =  $this->_common->selectRecord('product',"Title","nBusId=".$_POST['id']);



        if($this->view->id!="" && $this->view->comment!="")
        {
            $arr  =   array("vDescription"=>addslashes(trim($comment)),
                                  "vEmail"=>addslashes(trim($email)),
                                  "vTitle"=>addslashes($titleAry->Title),
                                  "vPostedBy"=>addslashes(trim($name)),
                                  "nStatus"=>0,
                                  "dDate"=>date('Y-m-d',time()),
                                  "nProductId"=>$id
                                 );

             $this->_common->addFields("enquiry",$arr);
             echo "1";
             exit;
        }
        else
        {
            echo "2";
            exit;
        }
        echo "3";
}


public function saverate()
{
    $this->view->disableLayout();
    $this->view->disableView();

     $arr  =   array("nProductId"=>addslashes($this->post('listid')),
                                  "nRate"=>addslashes($this->post('rate')),
                                  "dDate"=>date('Y-m-d',time()),
                                  "nStatus"=>0
                                 );

    $this->_common->addFields("productrating",$arr);


    $this->_session->set('tmp_rate_flag_'.$this->post('listid'),'set','default');
    $this->_session->set('tmp_rate_count_'.$this->post('listid'),$this->post('rate'),'default');

    echo 1;




}
public function creditcard()
	{



            // User Information

          // $this->userName = LibSession::get('user_login');

          // $this->userPass = LibSession::get('user_pass');

           $this->userId   = $this->_session->get('user_id');


            //$listId = LibSession::get('temp_listing_id');


           $this->listId   =   $this->_common->selectRow("product","max(`nBusId`)","nUserId=".$_SESSION['nUserid']);
           $listId=$this->listId;


           $this->Libauthorize_class  = new  LibAuthorize_class();

           $authorizeEnable      =   $this->_common->selectRow("settings","value","settingfield='authorize_enable'");

           $authorizeLoginId     =   $this->_common->selectRow("settings","value","settingfield='authorize_loginid'");

           $authorizeTransKey    =   $this->_common->selectRow("settings","value","settingfield='authorize_transkey'");

           $authorizeEmail       =   $this->_common->selectRow("settings","value","settingfield='authorize_email'");

           $authorizeTestMode    =   $this->_common->selectRow("settings","value","settingfield='authorize_test_mode'");

           $paymentAmount        =   $this->_common->selectRow("plans","vPlanAmount","nPlanId='".$_SESSION['planid']."'");

           $listName             =   $this->_common->selectRow("product","Title","nBusId='".$listId."'");


           $adminCurrency        =   $this->_common->selectRow("settings","value","settingfield='admin_currency'");







           $authorizeInfo =array();

           $authorizeInfo['desc'] = $listName;
           $authorizeInfo['x_login'] = $authorizeLoginId;
           $authorizeInfo['x_tran_key'] = $authorizeTransKey;
           $authorizeInfo['email'] = $authorizeEmail;
           $authorizeInfo['testMode'] = $authorizeTestMode;
           $authorizeInfo['currency_code'] =$adminCurrency;

           $authorizeInfo['amount'] = $paymentAmount;

           $authorizeInfo['expMonth']=$this->post('expM');
           $authorizeInfo['expYear']=$this->post('expY');

           $authorizeInfo['cvv']=$this->post('cvv');
           $authorizeInfo['ccno']=$this->post('ccno');
           $authorizeInfo['fName'] = $this->post('fname');
           $authorizeInfo['lName'] = $this->post('lname');
           $authorizeInfo['add1'] = $this->post('add1');
           $authorizeInfo['city'] = $this->post('city');
           $authorizeInfo['state']= $this->post('state');
           $authorizeInfo['country']= $this->post('country');
           $authorizeInfo['zip']= $this->post('zip');





          $return =  $this->Libauthorize_class->submit_authorize_post($authorizeInfo);




         $details = $return[0];

          $transaction_id = $return[1];

           switch ($details) {
        case "1": // Credit Card Successfully Charged
            $paymentsuccessful = true;

            $transactionid = $return[6];
            break;
        case "2":
            $paymentsuccessful = false;
            $paymenterror = "The card has been declined";
            $paymenterror .= "<br>" . $return[3];
            break;
        case "4":
            $paymentsuccessful = false;
            $paymenterror = "The card has been held for review";
            $paymenterror .= "<br>" . $return[3];
            break;
        default: // Credit Card Not Successfully Charged
            $paymentsuccessful = false;
            $paymenterror = "Error";
            $paymenterror .= "<br>" . $return[3];
            break;
    }

       if($paymentsuccessful)
          {
      $this->view->msg = 'Payment is Successful';
        $flag=1;
          }
      else{

      $this->view->errorMsg = 'Payment  failed';
        $flag=2;
      }


       if($transaction_id!='' && $paymentsuccessful)
       {

           $arrProfile =   array("nListId"=>$listId,
                                 "vUserFirstName"=>$this->post('fname'),
                                 "vUserLastName"=>$this->post('lname'),
                                 "vAmount"=>$authorizeInfo['amount'],
                                 "vProductName"=>$listName,
                                 "vPaymentStatus"=>"C",
                                 "vTransactionId"=>$transaction_id
                                 );


           $paymentId =   $this->_common->addFields("payments",$arrProfile);



           $arrProfile         =   array("nPaymentStatus"=>P);

           $this->_common->updateFields("product",$arrProfile,"nBusId='".$listId."'");


//           $arrProfile         =   array("vStatus "=>P);
//
//           $this->_common->updateFields("userplans",$arrProfile,"nProductId='".$listId."'");

            $payUpdate  =   array("vPaymentType"=>'L');

            $this->_common->updateFields("payments",$payUpdate,"nListId='".$listId."'");



            $this->redirect('index/creditsuccess/'.$flag);
            exit;



        }





        //$this->view->txtUserFirstName       = $txtUserFirstName;





	}
           public function creditsuccess($flags){



        if($flags==1){
            $this->operationMode = $this->_common->selectResult("settings","settingfield,value","settingfield='operationMode'");
            if($_SESSION['autoregister'] == '1'){
                if($this->operationMode[0]->value == "paid") {
                    $this->_postads->sendUserEmail($_SESSION['nUserid'],$this->setting['userApproval'],$this->setting['adminEmail']);
                }
               // $this->view->msg = 'Payment is successfull.Posting has been saved and is in pending status. Please activate your account through the activation e-mail. Thank You!';
            } else {
                //$this->view->msg = 'Payment is successfull.Your posting has been saved ,waiting for the admin to approve!';
            }

            if($this->setting['userApproval']=='email' && $_SESSION['autoregister']=='1'){
                        $this->view->msg = 'Posting has been saved waiting for the admin approval. Please activate your account through the activation e-mail. Thank You';


                     }
                     elseif($this->setting['userApproval']=='admin' && $_SESSION['autoregister']=='1'){
                        $this->view->msg = 'Payment is successfull,Posting has been saved, waiting for the admin  approval';

                     }elseif($this->setting['userApproval']=='automatic' && $_SESSION['autoregister']=='1'){
                         $this->view->msg = 'Payment is successfull,Posting has been saved, You can Sign in to your account,Please check the mail for login credentials';

                     }elseif($this->setting['userApproval']=='email' && $_SESSION['autoregister']!='1'){
                        $this->view->msg = 'Payment is successfull,Posting has been saved, waiting for the admin approval.Thank You';


                     }elseif($this->setting['userApproval']=='admin' && $_SESSION['autoregister']!='1'){
                        $this->view->msg = 'Payment is successfull,Posting has been saved, waiting for the admin approval';

                     }elseif($this->setting['userApproval']=='automatic' && $_SESSION['autoregister']!='1'){
                         $this->view->msg = 'Payment is successfull, Your Posting has been submited';

                     }



            if($this->operationMode[0]->value == "paid") {
                 $this->_postads->sendPostNotificationToAdmin($this->setting['adminEmail']);
            }

         }
         else  if($flags==2){
              $this->view->msg = 'Payment failure';
         }

     }

public function forgotpwd()
{
             if($this->isPost('SendEmail')){
              $email= $this->post('email');
              $checkemail=$this->_common->selectRecord('users',"vEmail,vLoginName","vEmail='".$email."'");
              $settings = $this->_common->selectResult('settings','*');
              foreach($settings as $field ){
              $setting[$field->settingfield]= $field->value;
                                           }
              $this->siteSettings = $setting;
              $setting[$field->settingfield];
              $this->siteSettings['adminEmail'];


              if($checkemail->vEmail==null)
              {
                    $this->view->message= "The email id you entered does not exist";
                    $this->view->color="red";
              }
              else
              {
               $newpassword=$this->generatePassword();
               $arrUpdate= array("vPassword"=>md5($newpassword));
               $this->_common->updateFields("users",$arrUpdate,"vEmail='".$email."'");
               $subject = "Password reset at ".$this->siteSettings['siteName']."";
               $message = "<p><img src=".BASE_URL."/public/images/default/mainlogo_disp.png /></p>";
               $message.="<p>Dear  ".$checkemail->vLoginName.",</p>Your EasyIndex password has been reset on request.
               <p>The following are your new login details.</p>
               <p>User Name:      ".$checkemail->vLoginName."</p>
               <p>Password:       ".$newpassword." </p>
               If you have any issues please contact us at ".$this->siteSettings['adminEmail']."";
       //echo $message;exit;
               $userNotif = array();
               $userNotif['from']=$this->siteSettings['adminEmail'];
               $userNotif['subject']=$subject;
               $userNotif['message']=$message;
               $userNotif['to']=$email;

               $this->_libEmailSend->email_senderNow($userNotif);
               $this->view->message= "Your password has been reset please check the mail";
               $this->view->color="green";
               }

}
}

public function error_404(){

}

public function contactus(){

}

public function termsofuse(){

}

public function privacypolicy(){

}

public function cmscontents($nContentId){
    $this->view->content =  $this->_common->selectRecord("cms","nContentId,vTitle,vDescription","nContentId='$nContentId'");
}
public function renderRate($productId,$starNo) {
        $this->view->disableLayout();
        $this->view->disableView();

        //echo $starNo;exit;
        //print_r($_POST);
        $starNo = $_GET['starNo'];
        $productId = $_GET['product_id'];
        //echo $starNo;exit;
        $arr  =   array("nProductId"=>addslashes($productId),
                "nRate"=>addslashes($starNo),
                "dDate"=>date('Y-m-d',time()),
                "nStatus"=>0
        );
        $this->_common->addFields("productrating",$arr);
        $table  = 'productrating';
        $field  = 'round( COALESCE(SUM( `nRate` ) / COUNT( `nId` ),0) ) AS RATE';
        $order  = "";
        $where  = "nProductId = '$productId'";
        $this->view->productRating = $this->_common->selectRow($table,$field,$where);

        $this->_session->set('hit_'.$productId,'Y','default');
        //LibSession::set('tmp_rate_count_'.$productId,$starNo,'business');
        //echo "success".$this->view->productRating;
        echo $this->view->productRating;

        exit;

    }

    public function getSubCategories($catId){
        $categories = $this->_common->getAllData('nCategoryId, vCategoryDesc', 'category','','WHERE nParentId = 0','','ASC','vRoute');
        if($categories) {
            foreach($categories as $cat_val) {
                $products = $this->_common->selectResult('product','nBusId, nCatid, Title', "nCatid = {$cat_val->nCategoryId} AND nStatus ='1' 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;
            }
        }
        return $category_title;
    }

    public function feed(){
        $this->view->products = $this->_common->getAllData('*','product','' ,'WHERE nStatus="1"', '','DESC','dPostDate');
        $this->disableLayout();
        //echopre($products);
         //('nCategoryId, vCategoryDesc', 'category','','WHERE nParentId = 0','','ASC','vRoute');
    }
}
?>