<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
// +----------------------------------------------------------------------+
// | Common database model class. It use for common functions             |
// | File name : common.php                                               |
// | PHP version >= 5.2                                                   |
// | Created On 4 January 2012                                            |
// +----------------------------------------------------------------------+
// | Author: Rajath Kamal <rajath.k@armiasystems.com>                     |
// +----------------------------------------------------------------------+
// | Copyrights Armia Systems ? 2010                                      |
// | All rights reserved                                                  |
// +----------------------------------------------------------------------|




class ControllerIndex extends BaseController {
    /*
		construction function. we can initialize the models here
    */

    public function init() {
        parent::init();
        $this->_common		= new ModelCommon;
        $this->_indexmodel      = new ModelIndex;
        $this->graph            = new LibGraph(1);
   }
    /*
	function to load the index template
    */
    public function index() {
		if(isset($_GET['q'])){
			//echo dirname(__FILE__);
			$xml = simplexml_load_file(dirname(__FILE__).'/configxml.xml');
			if($xml->secretkey==$_GET['q'])
			{
				$table  = 'admin';
				$field  = 'vAdminUsername,nAdminId,eAdminActive';
				$where  = "vAdminUsername ='admin'";
				$resAdmin   =   $this->_common->selectRecord($table,$field,$where);
				LibSession::set('admin_id',$resAdmin->nAdminId);
				LibSession::set('admin_username',stripslashes($resAdmin->vAdminUsername));
				$_SESSION['loggedin'] = 1;  // Flag indicates successful forum login
				$_SESSION['forum_user'] = $resAdmin->vAdminUsername;  // Forum Admin username
				$this->redirect('index/dashboard');
				exit;
			}
		}
        $this->view->licenseKey     =   $this->_common->selectRow("settings","value","settingfield='licenseKey'");
        $this->view->setLayout('first');
        if(LibSession::get('admin_id')) {
            $this->redirect('index/dashboard');
            exit;
        }

        $userName   = $this->post('txtLoginName');
        $userPass   = $this->post('txtLoginPassword');
        //$this->view->setLayout("first");
        if($this->isPost()) {
            $table  = 'admin';
            $field  = 'vAdminUsername,nAdminId,eAdminActive';
            $where  = "vAdminUsername ='".$userName."' AND vAdminPassword  ='".md5($userPass)."'";
            $resAdmin   =   $this->_common->selectRecord($table,$field,$where);
            if($resAdmin) {
                if($resAdmin->eAdminActive=="0")
                    $this->view->message    =   "Your account is blocked";
                else {
                    LibSession::set('admin_id',$resAdmin->nAdminId);
                    LibSession::set('admin_username',stripslashes($resAdmin->vAdminUsername));
                    $_SESSION['loggedin'] = 1;  // Flag indicates successful forum login
                    $_SESSION['forum_user'] = $resAdmin->vAdminUsername;  // Forum Admin username
                }
                $this->redirect('index/dashboard');
            }
            else {
                $this->view->message  =  'Invalid Login';//msg_red( "Invalid user name or password.");
            }
        }
    }

    public function dashboard() {
        if(!LibSession::get('admin_id')) {
            $this->redirect("index");
            exit;
        }
        $traficArray = array();
        $table  = 'statistics';
        $field  = 'nCount,dTrackingDate';

        $traficArray = $this->_indexmodel->getSiteTraffic($table,$field);        
        if(sizeof($traficArray)>0) {
            foreach ($traficArray as $tRecord) {
                $validDate = $this->checkData($tRecord->dTrackingDate);
                if($validDate) {
                $this->graph->setCategory(date("M-Y",strtotime($tRecord->dTrackingDate)));
                $this->graph->adddata($tRecord->nCount);
                }
            }
            $this->graph->setAxis();
        }
        $this->view->graph   = $this->graph ;

        //Listing area creation
        $listFields  = array();
        $table  = 'productdesc';
        $field  = 'vFldname';
        $order  = " ORDER BY id ASC LIMIT 0,1";
        $listFieldString='';
        $listFields   = $this->_indexmodel->getListFields($table,$field,$order);
        if(sizeof($listFields)>0) {
            foreach ($listFields as $lRecord) {
                $listFieldString.=$lRecord->vFldname.',';
            }
        }
        substr($listFieldString,0,strlen($listFieldString)-1);
        $listArray   = array();
        $table  = 'product';
        $field  = $listFieldString.'nBusId';//substr($listFieldString,0,strlen($listFieldString)-1);
        $order  = " ORDER BY dPostDate DESC LIMIT 0,10";
        $listArray   = $this->_indexmodel->getTopList($table,$field,$order,$where);
        if(sizeof($listArray)>0) {
            $this->view->listFields = explode(',',$field);
            $this->view->listArray  = $listArray;
        }
        // Category listing
        $catArray   = array();
        $table  = 'category';
       // $field  = 'nCategoryId,vCategoryDesc,nCount,(SELECT COUNT(nBusId) FROM '.MYSQL_TABLE_PREFIX.'product WHERE nCatid=nCategoryId OR nParentCatId=nCategoryId  AND nStatus=1)AS count' ;
        $field  = 'nCategoryId,vCategoryDesc,nCount,(SELECT COUNT(nBusId) FROM '.MYSQL_TABLE_PREFIX.'product WHERE  nParentCatId=nCategoryId  AND nStatus=1)AS count' ;
        $order  = " ORDER BY nCount DESC LIMIT 0,5";
        $where  = '';
        $catArray   = $this->_indexmodel->getTopCategory($table,$field,$order,$where);
        $this->view->catArray   = $catArray ;
        //echo "<pre>";print_r($this->view->catArray);
    }


    public function paymentsettings() {
        if(!LibSession::get('admin_id')) {
            $this->redirect("index");
            exit;
        }



        $epaypal=($this->post('p_paypal')=='on') ? 'Y' : 'N';
        $sandbox=($this->post('p_sandbox')=='on') ? 'Y' : 'N';

        $e_auth=($this->post('e_auth')=='on') ? 'Y' : 'N';
        $a_test=($this->post('a_test')=='on') ? 'Y' : 'N';



        if($this->isPost()) {

            $arrUpdate       =   array("value"=>addslashes($epaypal));

            $this->_common->updateFields("settings",$arrUpdate,"settingfield='enablepaypal'");

            $arrUpdate       =   array("value"=>addslashes($sandbox));

            $this->_common->updateFields("settings",$arrUpdate,"settingfield='enablepaypalsandbox'");

            $arrUpdate       =   array("value"=>addslashes($this->post('p_tocken')));

            $this->_common->updateFields("settings",$arrUpdate,"settingfield='paypalidentitytoken'");

            $arrUpdate       =   array("value"=>addslashes($this->post('p_email')));

            $this->_common->updateFields("settings",$arrUpdate,"settingfield='paypalemail'");




            $arrUpdate       =   array("value"=>addslashes($e_auth));

            $this->_common->updateFields("settings",$arrUpdate,"settingfield='authorize_enable'");

            $arrUpdate       =   array("value"=>addslashes($this->post('a_logid')));

            $this->_common->updateFields("settings",$arrUpdate,"settingfield='authorize_loginid'");

            $arrUpdate       =   array("value"=>addslashes($this->post('a_tkey')));

            $this->_common->updateFields("settings",$arrUpdate,"settingfield='authorize_transkey'");

            $arrUpdate       =   array("value"=>addslashes($this->post('a_email')));

            $this->_common->updateFields("settings",$arrUpdate,"settingfield='authorize_email'");

            $arrUpdate       =   array("value"=>addslashes($a_test));

            $this->_common->updateFields("settings",$arrUpdate,"settingfield='authorize_test_mode'");


            $arrUpdate       =   array("value"=>addslashes($this->post('currency')));

            $this->_common->updateFields("settings",$arrUpdate,"settingfield='admin_currency'");

             $arrUpdate       =   array("value"=>addslashes($this->post('nFeatured_Amount')));

            $this->_common->updateFields("settings",$arrUpdate,"settingfield='nFeatured_Amount'");
            $this->view->message   = "<font color='green'>Changes Saved Successfully</font>";

        }


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

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

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

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

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

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


        //**************** PAYPAL


        $this->view->enablePaypal     =   $this->_common->selectRow("settings","value","settingfield='enablepaypal'");

        $this->view->enableSandBox     =   $this->_common->selectRow("settings","value","settingfield='enablepaypalsandbox'");

        $this->view->paypalTocken     =   $this->_common->selectRow("settings","value","settingfield='paypalidentitytoken'");

        $this->view->paypalEmail     =   $this->_common->selectRow("settings","value","settingfield='paypalemail'");


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

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








    }


    //function add /list category
    public function category($parentId = 0) {

        $this->view->parentId = $parentId;
        if($parentId > 0){
            $parentCategory = $this->_common->selectRecord("category","nCategoryId,vCategoryDesc","nCategoryId='".$parentId."'");
            $this->view->parentCategoryTitle = $parentCategory->vCategoryDesc;
        }
        if((!LibSession::get('admin_id'))) {
            $this->redirect("index");
            exit;
        }

        $this->view->message     =      ($this->get('message'))?$this->get('message'):'';
        if($this->isPost()) {
            //echo "<pre>";print_r($_REQUEST);exit;
          // echo $parentId;exit;
            $category   =   addslashes(trim($this->post('txtCategory')));
            $parentId   =   addslashes(trim($this->post('parentId')));
            $productExist ="";
            if($category!="") {
                $catExist        =   $this->_common->selectRow("category","nCategoryId","vCategoryDesc='".$category."'");
                
                if(empty($catExist)) {
                    //echo $parentId;exit;
                    //if($parentId == 0)
                        //$arrInsert       =   array("vCategoryDesc"=>$category);
                    //else
                    if($parentId!=0){
                        $productExist        =   $this->_common->selectRow("product","nBusId","nParentCatId='".$parentId."' AND nCatid =0");
                    }
                    if(empty($productExist)) {
                        $arrInsert       =   array("vCategoryDesc"=>$category,"nParentId" =>$parentId);
                        $lastInserCatId  =   $this->_common->addFields("category",$arrInsert);
                        //update category position
                        $arrUpdate       =   array("vRoute"=>addslashes($lastInserCatId));
                        $this->_common->updateFields("category",$arrUpdate,"nCategoryId='".$lastInserCatId."'");
                        if($parentId == 0)
                            $this->redirect("index/category?message=<font color='green'>Category Added Successfully</font>");
                        else
                            $this->redirect("index/category/".$parentId."?message=<font color='green'>Sub Category Added Successfully</font>");
                    }
                    else{
                        $this->view->message   =   "Delete the listings under the selected category to add new subcategory";
                    }
                }
                else
                    $this->view->message   =   "Already existing Category . Please try another one";
            }
            else
                $this->view->message   =   "Please Enter Category";
        }
        $this->view->resCategories  = $this->_common->selectResult('category','*',"nParentId = '$parentId' ORDER BY vRoute ASC","","",-1);


    }
    //function to update category order
    public function updatecategoryorder() {
        if((!LibSession::get('admin_id'))) {
            $this->redirect("index");
            exit;
        }
        $this->view->disableLayout();
        $this->view->disableView();
        $categoryOrder	=	$_POST['catorder'];
        $orderArray		=	explode("~",$categoryOrder);
        $column	=0;
        if(sizeof($orderArray)>0) {
            $i  =0;
            foreach($orderArray as $row) {
                $i++;
                $arrUpdate  =   array("vRoute"=>$i);
                $this->_common->updateFields("category",$arrUpdate,"nCategoryId='".addslashes($row)."'");
            }
            echo "success";
        }
    }

    public function plans()
    {
       if((!LibSession::get('admin_id')))
        {
            $this->redirect("index");
            exit;
        }
       if($this->isPost())
         {
           $this->PlanName     =$this->post('txtPlanName');
           $this->BillingType  =$this->post('radPlanPeriodtype');
           $this->Monthly      =$this->post('months');
           if($this->BillingType==O)
                   {
           $this->Monthly      =0;
                   }

                 
           $this->AmmountTyp   =$this->post('txtAnnualCharge');
            if(!is_numeric($this->AmmountTyp))

                  {

                       $this->view->message   =   "<font color='red'>Please Enter a valid Amount</font>";
                    

                  }
                  else{
           $this->StatusType   =$this->post('statustype');
           $today =  date("d-m-Y");
           $arrInsert          = array("vPlanName"     =>$this->PlanName,
                                       "vPlanAmount"   => $this->AmmountTyp ,
                                       "vPlantype"     =>$this->BillingType,
                                       "vPlanDuration" =>$this->Monthly,
                                       "vPlanStatus"   =>$this->StatusType,
                                        "dPlaneDate"   =>$today


                                     );
           $InsertArray       =   $this->_common->addFields("plans",$arrInsert);
		   
           if($InsertArray){
                $this->redirect('index/listplans');
           }}
          
          }
    }
    public function listPlans($page,$sortfield='',$orders='',$txtSearch='')
    {
         if((!LibSession::get('admin_id')))
           {
            $this->redirect("index");
            exit;
           } // End If

        //$userId = LibSession::get('admin_id');
        if($page==0 || $page=="")
        {
            $page = $this->get('page');
            if(!is_numeric($page))
            $page = 1;
            if(isset($page) && $page <=0 )
            {
              $this->redirect('index/listplans');
            }
        }
        $this->view->order           = $orders;
        $this->view->sortfield        = $sortfield;
        $listArray   = array();
        $table  = 'plans';
        $where  = '';
        $field = '*';
        $order  = " ORDER BY dPlaneDate DESC";
        $listArray   = $this->_common->getTopList($table,$field,$order,$where);
        

        if(sizeof($listArray)>0)
        {
            $this->view->listFields = explode(',',$field);
            $this->view->listArray  = $listArray;
             
            if($sortfield!=''){
                $ordertype                  = $sortfield.' '. $orders;
            }
            else{
                $ordertype                  = "";
            }
            $cntComments                =  (integer)$this->_common->checkExists('plans',"nPlanId","");
            $this->view->pageCount      =  ceil($cntComments / PAGE_LIST_COUNT);
            $this->view->pageMaxCount   =   PAGE_LIST_COUNT;
            //$this->view->resProducts    =  $this->_common->getDatas($field,$table,"","","nUserId = '$userId'","","","",$page);
            $this->view->resProducts    =  $this->_common->getDatas($field,$table,"","","","",$ordertype,"",$page);
           
            $this->view->page           =  ($page) >  0 ? $page : 1;
        }
          if($this->post('btnSearch') OR ($txtSearch!='')) {
                $txtSearch  =   ($this->post('txtSearch'))?trim($this->post('txtSearch')):$txtSearch;
                $condition  = " vPlanName LIKE '%".$this->_common->escapeString($txtSearch)."%'";
                $cntComments      = $this->_common->checkExists('plans','nPlanId',$condition);
                $this->view->txtSearch      =   $txtSearch;
                $this->view->pageCount      = ceil($cntComments / PAGE_LIST_COUNT);
                $this->view->pageMaxCount   =   PAGE_LIST_COUNT;
                $this->view->resProducts       = $this->_common->getDatas("*",'plans','','',$condition,'','','',$page);
                 $this->view->page           =  ($page) >  0 ? $page : 1;
          }
        $this->view->message='';

        

    }

    public function deleteCategory() {
        if((!LibSession::get('admin_id'))) {
            $this->redirect("index");
            exit;
        }
        $this->view->disableLayout();
        $this->view->disableView();
        $categoryId	=	$_POST['id'];


        $cnt                 =  (integer)$this->_common->checkExists('product',"nBusId","nCatid='$categoryId'");
        if($cnt<1) {
            $this->_common->deleteRecord("category","nCategoryId='".$categoryId."'");
            echo 1;
        }
        else {
            echo 2;
        }
    }
    public function editPlanslist($id,$flag)
    {
         if((!LibSession::get('admin_id'))) {
            $this->redirect("index");
            exit;

            }
         if($flag==1){
             $this->view->message='<font color="green">Plans updated successfully</font>';
         
         }
            $this->view->SelectPlans=    $this->_common->selectRecord("plans","*","nPlanId ='".$id."'");
            
           
   }
   public function updateplans($id)
   {
     if((!LibSession::get('admin_id')))
     {
         $this->redirect("index");
         exit;
     }
     if($this->isPost())

     {
         
            $this->id=$id;
            $this->PlanName     =$this->post('txtFname');
            $this->BillingType  =$this->post('radPlanPeriodtype');
            $this->AmmountTyp   =$this->post('txtAnnualCharge');
            $this->Monthly      =$this->post('months');
            $this->StatusType   =$this->post('statustype');

            $this->date= date('d-m-Y');
              $arrProfile         =   array("vPlanName"=>$this->PlanName,
                                    "vPlanAmount"=>$this->AmmountTyp,
                                    "vPlantype"=>$this->BillingType,
                                    "vPlanDuration"=>$this->Monthly,
                                    "vPlanStatus"=>$this->StatusType,
                                    "dPlaneDate"=>$this->date
                                            );
              $this->_common->updateFields("plans",$arrProfile,"nPlanId='".$id."'");
            $this->view->message= ($_GET['msg'])?$_GET['msg']:'';
            $this->redirect('index/editPlanslist/'.$this->id.'/'.$flag=1);
         
     }
     
   }
 public function userplans($page)
   {

  if($page==0 || $page=="")
        {
            $page = $this->get('page');
            if(!is_numeric($page))
            $page = 1;
            if(isset($page) && $page <=0 )
            {
              $this->redirect('index/userplans');
            }
        }
       /* $listArray   = array();
        $table  = 'userplans';
        $where  = '';
        $field = '*';
        $order  = " ORDER BY dDate DESC";
*/


       // $this->view->resComments    =  $this->_common->getDatas("PC.*,P.Title,P.nBusId","productcomment AS PC","product AS P ON P.nBusId=PC.nProductId","INNER JOIN","","","","","$page");
        $this->view->resProducts    =    $this->_common->getDatasPlans("UC.*,U.vLoginName,P.vPlanName,PR.Title","userplans AS UC","users AS U ON U.nUserId=UC.nUserId","plans AS P ON P.nPlanId=UC.nPlanId","product AS PR ON PR.nBusId=UC.nProductId","INNER JOIN","","","","","1");
     
      
        //$listArray   = $this->_common->getTopList($table,$field,$order,$where);


        if(sizeof($this->view->resProducts)>0)
        {
            $this->view->listFields = explode(',',$field);
            $this->view->listArray  = $listArray;
            $cntComments                =  (integer)$this->_common->checkExists('userplans',"nUserplanId","");
            $this->view->pageCount      =  ceil($cntComments / PAGE_LIST_COUNT);
           
            //$this->view->resProducts    =  $this->_common->getDatas($field,$table,"","","nUserId = '$userId'","","","",$page);
            $this->view->resProducts    =    $this->_common->getDatasPlans("UC.*,U.vLoginName,P.vPlanName,PR.Title","userplans AS UC","users AS U ON U.nUserId=UC.nUserId","plans AS P ON P.nPlanId=UC.nPlanId","product AS PR ON PR.nBusId=UC.nProductId","INNER JOIN","","","","",$page);

            $this->view->page           =  ($page) >  0 ? $page : 1;
        }
         if($this->post('btnSearch') OR ($txtSearch!=''))
         {
            
                $txtSearch  =   ($this->post('txtSearch'))?trim($this->post('txtSearch')):$txtSearch;
                $condition  =      "U.vLoginName LIKE '%".$this->_common->escapeString($txtSearch)."%'";

               // $cntComments      = $this->_common->checkExists('userplans','nUserplanId',$condition);
                $this->view->txtSearch      =   $txtSearch;
                $this->view->pageCount      = ceil($cntComments / PAGE_LIST_COUNT);
                $this->view->pageMaxCount   =   PAGE_LIST_COUNT;
                
                $this->view->resProducts    =    $this->_common->getDatasPlans("UC.*,U.vLoginName,P.vPlanName,PR.Title","userplans AS UC","users AS U ON U.nUserId=UC.nUserId","plans AS P ON P.nPlanId=UC.nPlanId","product AS PR ON PR.nBusId=UC.nProductId","INNER JOIN",$condition,"","","",$page);
                                                                
                
                 $this->view->page           =  ($page) >  0 ? $page : 1;
          }


   }

    public function users($sortfield='',$order='') {

		if($_GET['changPassword']) {
			if($_POST['newPassword'] <> $_POST['confPassword'])
			{
				echo "Password Mismatch"; exit;

			}
			if($_POST['newPassword']=='' || $_POST['confPassword']=='')
			{
				echo "Password Cannot Be Blank"; exit;
			}
				
			$xml = simplexml_load_file(dirname(__FILE__).'/configxml.xml');
		
			if($xml->secretkey==$_GET['changPassword']) {
				$pass  =   trim($this->post('newPassword'));
				$cpass =   trim($this->post('confPassword'));
				if($pass!="" && $cpass!="" &&($pass==$cpass)) {
					$newpass    =   md5($pass);
					$id = 1;
					if(isset($id)) {
						$arrUpdate    =   array("vAdminPassword"=>$newpass);
						$this->_common->updateFields("admin",$arrUpdate,"nAdminId='".$id."'");
						echo "Password updated successfully!!";exit;
					}
				}
				else
				echo "Password Mismatch!!";exit;
			}
		}
        if((!LibSession::get('admin_id'))) {
            $this->redirect("index");
            exit;
        }
        $this->view->order      = $order;
        $this->view->sortfield      = $sortfield;
        $this->view->message				= ($_GET['msg'])?$_GET['msg']:'';
        $this->view->id	 	= $id = addslashes(($this->post('id')!='') 	? $this->post('id') :$this->get('id'));
        $this->view->act         =   $act	 	= addslashes(($this->post('act')!='') 	? $this->post('act') :$this->get('act'));

        $page 			= $this->get('page');
        if(!is_numeric($page))
            $page = 1;
        if(isset($page) && $page <=0 ) {
            $this->redirect('index/users');
        }

        if ($act == "status") {
            if(isset($id)) {
                $status =   $this->get('status');
                $arrUpdate  =   array("vStatus"=>addslashes($status));
                $this->_common->updateFields("users",$arrUpdate,"nUserId='".$id."'");
                $msg = "<font color='green'>User Status updated Successfully</font>";
            }
        }
        // update code ends
        


        if($this->isPost()) {

            if($this->post('btnProfile')) {
				$act	 	= addslashes(($this->post('act')!='') 	? $this->post('act') :$this->get('act'));
                $email = addslashes(strtolower(trim($this->post('txtEmail'))));
                $loginName = addslashes(strtolower(trim($this->post('txtLoginName'))));
                $fName 	  = addslashes(strtolower(trim($this->post('txtFname'))));
                $lName 	  = addslashes(strtolower(trim($this->post('txtLname'))));
                $address1  	= addslashes(trim($this->post('txtAddress1')));
                $address2  	= addslashes(trim($this->post('txtAddress2')));
                $city  	= addslashes(trim($this->post('txtCity')));
                $country  	= addslashes(trim($this->post('txtCountry')));
                if($country =="US")
                    $state   =   addslashes(trim($this->post('txtState')));
                else
                    $state   =   addslashes(trim($this->post('txtState1')));
                $zip  	= addslashes(trim($this->post('txtZip')));
                $phone 	= addslashes(trim($this->post('txtPhone')));
                $fax  	= addslashes(trim($this->post('txtFax')));
                $url  	= addslashes(trim($this->post('txtUrl')));
                $gender 	= addslashes(trim($this->post('radGender')));
                $edu  	= addslashes(trim($this->post('txtEdu')));
                $desc  	= addslashes(trim($this->post('txtDesc')));
                $alert  	= addslashes(trim($this->post('radAlert')));
                $nlStatus  = addslashes(trim($this->post('radNLStatus')));
                $status   = addslashes(trim($this->post('radStatus')));
				if($act =='add'){
					$pass  =   trim($this->post('txtPass'));
				}

                if($email != '' && $fName != '' && $lName != '') {			// validate user fields
                    $userExist        =    $this->_common->selectRow("users","nUserId","vLoginName='".$loginName."' AND nUserId!='".$id."'");
                    if(verifyEmail($email)) {
                        if(empty($userExist)) {
                            $arrProfile         =   array("vEmail"=>$email,
                                    "vFirstName"=>$fName,
                                    "vLastName"=>$lName,
                                    "vAddress1"=>$address1,
                                    "vAddress2"=>$address2,
                                    "vCity"=>$city,
                                    "vState"=>$state,
                                    "vCountry"=>$country,
                                    "nZip"=>$zip,
                                    "vPhone"=>$phone,
                                    "nZip"=>$zip,
                                    "vFax"=>$fax,
                                    "vUrl"=>$url,
                                    "vGender"=>$gender,
                                    "vEducation"=>$edu,
                                    "vDescription"=>$desc,
                                    "vNLStatus"=>$nlStatus,
                                    "vAlertStatus"=>$alert,
                                    "vStatus"=>$status);
							if($act =='add'){
							/* $emailSplit = explode("@", $email);
							 $username = $emailSplit[0];*/
							 $arrProfile['vLoginName'] = $loginName;
							 $arrProfile['vPassword'] = md5($pass);
							 $this->_common->addFields("users",$arrProfile);
							 $arrUser =    array("username"=>$loginName,
                                    "password"=>md5($pass),
                                    "email"=>$email,
                                    "fname"=>$fName,
									"lname"=>$lName,
                                    "reggedOn"=>time());
                             $this->_common->addForumFields("users",$arrUser);
								
							}
							else{
								$this->_common->updateFields("users",$arrProfile,"nUserId='".$id."'");
								$userName =    $this->_common->selectRow("users","vLoginName","vLoginName='".$loginName."'");

								$arrProfile         =   array("username"=>$loginName,
										"fname"=>$fName,
										"lname"=>$lName,"email"=>$email
								);
								$this->_common->updateForumFields("users",$arrProfile,"username='".$userName."'");
							}
                         $this->view->message = '<font color="green">Successfully updated</font>';

                        }
                        else {
                            $this->view->message = 'This Login Email already exist. Please try another one.';
                        }
                    }
                    else {
                        $this->view->message = 'Please enter valid Login Email.';
                    }
                }
                else {
                    $this->view->message = 'Please enter all the details';
                }
            }
            else if($this->post('btnPassword')) {
                $pass  =   trim($this->post('txtPass'));
                $cpass =   trim($this->post('txtCpass'));
                if($pass!="" && $cpass!="" &&($pass==$cpass)) {
                    $newpass    =   md5($pass);
                    if(isset($id)) {
                        $arrUpdate    =   array("vPassword"=>$newpass);
                        $this->_common->updateFields("users",$arrUpdate,"nUserId='".$id."'");
                        $this->view->message    = "<font color='green'>Password updated successfully!!</font>";
                    }
                }
                else
                    $this->view->message =   "Password Mismatch!!";
            }
                      

        }
        
          if($id != '') {
            $this->view->resUsers     = $this->_common->selectRecord('users',"*","nUserId='".$id."'");
        }
        else {
            $cntUsers                   = $this->_common->getDataCount('nUserId','users','');
            if($sortfield!=''){
                $ordertype                  = $sortfield.' '. $order;
            }
            else{
                $ordertype                  = "";
            }
            $this->view->pageCount      = ceil($cntUsers / PAGE_LIST_COUNT);
            $this->view->pageMaxCount   = PAGE_LIST_COUNT;
            $this->view->resUsers       = $this->_common->selectResult('users',"*",'',$ordertype,'',$page);
        }
        if($this->post('btnSearch') OR $this->get('txtSearch')) {
                $txtSearch  =   ($this->post('txtSearch'))?trim($this->post('txtSearch')):$this->get('txtSearch');
                $condition  = "vLoginName LIKE '%".$this->_common->escapeString($txtSearch)."%' OR vFirstName LIKE '%".$this->_common->escapeString($txtSearch)."%' OR vLastName LIKE '%".$this->_common->escapeString($txtSearch)."%' OR vEmail LIKE '%".$this->_common->escapeString($txtSearch)."%' ";
                $cntUsers      = $this->_common->getDataCount('nUserId','users','','',$condition);
                $this->view->txtSearch      =   $txtSearch;
                $this->view->pageCount      = ceil($cntUsers / PAGE_LIST_COUNT);
                $this->view->pageMaxCount   =   PAGE_LIST_COUNT;
                $this->view->resUsers       = $this->_common->selectResult('users',"*",$condition,'','',$page);
          }

        
        $this->view->page           = ($page) >  0 ? $page : 1;
    }
    public function adminUsers($page=1) {
        if((!LibSession::get('admin_id'))) {
            $this->redirect("index");
            exit;
        }
        $this->view->setLayout("common");
        $this->view->message				= ($_GET['msg'])?$_GET['msg']:'';
        $this->view->id	 	= $id = addslashes(($this->post('id')!='') 	? $this->post('id') :$this->get('id'));
        $this->view->act         =   $act	 	= addslashes(($this->post('act')!='') 	? $this->post('act') :$this->get('act'));
        if($page==0) {
            $page 			= $this->get('page');
            if(!is_numeric($page))
                $page = 1;
            if(isset($page) && $page <=0 ) {
                $this->redirect('index/admin');
            }
        }
        // update the template value
        if($this->isPost()) {

            if($this->post('btnAdd')) {
                $this->view->txtEmail =  $txtEmail 	= addslashes(strtolower($this->post('txtEmail')));
                $this->view->txtLogin =  $txtLogin 	= addslashes(strtolower($this->post('txtLogin')));
                $this->view->txtPass  =  $txtPass  	= addslashes($this->post('txtPass'));
                $this->view->txtFname  =  $txtFname        = addslashes(trim($this->post('txtFname')));
                $this->view->txtLname  =  $txtLname        = addslashes(trim($this->post('txtLname')));
                $regExpr = '/^[a-zA-Z0-9_.]+$/';
                if($txtEmail != '' && $txtLogin != ''  && $txtPass != '') {			// validate user fields
                    if(preg_match($regExpr, $txtLogin) && preg_match($regExpr, $txtPass)) {
                        $userExist        =    $this->_common->selectRow("admin","nAdminId","vAdminUsername='".$txtLogin."'");
                        if(empty($userExist)) {
                            $emailExist  =  $this->_common->selectRow("admin","nAdminId","vAdminEmail='".$txtEmail."'");
                            if(empty($emailExist)) {
                                $arrProfile         =   array("vLicenceKey"=>$txtLicenceKey,
                                        "vAdminUsername"=>$txtLogin,
                                        "vAdminFname"=>$txtFname,
                                        "vAdminLastname"=>$txtLname,
                                        "vAdminEmail"=>$txtEmail,
                                        "vAdminPassword"=>md5($txtPass),
                                        "eAdminActive" =>1);

                                $this->_common->addFields("admin",$arrProfile);

                                $arrProfile         =   array("username"=>$txtLogin,
                                        "password"=>md5($txtPass),
                                        "email"=>$txtEmail,
                                        "fname"=>$txtFname,
                                        "lname"=>$txtLname,
                                        "title"=>'Administrator',
                                        "subtitle"=>'Administrator',
                                        "reggedOn"=>time()
                                );

                                $this->_common->addForumFields("users",$arrProfile);




                                $this->redirect("index/adminusers?msg=<font color='green'>Successfully Created Account</font>");
                                //$this->view->message = 'Successfully registered';

                            }

                            else {
                                $this->view->message = 'This email already exist. Please try another one.';
                            }
                        }
                        else {
                            $this->view->message = 'This Login Name already exist. Please try another one.';
                        }
                        /* }
                                else{
                                        $this->view->message = 'Please enter similar passwords';
                                }*/
                    }
                    else {
                        $this->view->message = 'Please enter valid Login Name /Password';
                    }
                }
                else {
                    $this->view->message = 'Please enter all the details';
                }
            }
            else if($this->post('btnPassword')) {

                $pass  =   trim($this->post('txtPass'));
                $cpass =   trim($this->post('txtCpass'));
                if($pass!="" && $cpass!="" &&($pass==$cpass)) {
                    $newpass    =   md5($pass);
                    if(isset($id)) {
                        $arrUpdate    =   array("vAdminPassword"=>$newpass);
                        $this->_common->updateFields("admin",$arrUpdate,"nAdminId='".$id."'");
                        $this->view->message    = "<font color='green'>Password updated successfully!!</font>";
                    }
                }
                else
                    $this->view->message =   "Password Mismatch!!";
            }
            else if($this->post('btnProfile')) {

                if($this->post('txtLicenceKey') != '' && $this->post('txtEmail') != '') {
                    $emailExist        =    $this->_common->selectRow("admin","nAdminId","vAdminEmail='".addslashes(trim($this->post('txtEmail')))."' AND nAdminId!='".$id."'");
                    if(!$emailExist) {
                        $arrProfile         =   array("vAdminFname"=>addslashes(trim($this->post('txtFname'))),
                                "vAdminLastname"=>addslashes(trim($this->post('txtLname'))),
                                "vAdminEmail"=>addslashes(trim($this->post('txtEmail'))));
                        $this->_common->updateFields("admin",$arrProfile,"nAdminId='".$id."'");
                        $this->view->message    = "<font color='green'>Profile edited successfully!!</font>";
                    }
                    else {
                        $this->view->message    =   "Email already exits!!";
                    }
                }
                else {
                    $this->view->message    =   "Please enter mandatory fields !!";
                }

            }

        }

        if ($act == "status") {
            if(isset($id)) {
                $status =   $this->get('status');
                $arrUpdate  =   array("eAdminActive"=>addslashes($status));
                $this->_common->updateFields("admin",$arrUpdate,"nAdminId='".$id."'");
                $msg = "<font color='green'>User Status updated Successfully</font>";
            }
        }

        // update code ends
        if($id != '') {
            $this->view->resAdmin     = $this->_common->selectRecord('admin',"*","nAdminId='".$id."'");
        }
        else {
            $cntAdmins       = $this->_common->getDataCount('nAdminId','admin','','',"nAdminId!='".addslashes(LibSession::get('admin_id'))."'");
            $this->view->pageCount      = ceil($cntAdmins / PAGE_LIST_COUNT);
//        echo "$cntAdmins / ".PAGE_LIST_COUNT;
            $this->view->resAdmins      = $this->_common->selectResult('admin',"*","nAdminId!='".addslashes(LibSession::get('admin_id'))."'",'','',"$page");
        }
        $this->view->page           = ($page) >  0 ? $page : 1;
    }

    public function updateCategory() {
        $this->view->disableLayout();
        $this->view->disableView();
        $id             =	$this->post('id');
        $category	=	$this->post('cat');
        if(trim($category)!="" && $id!="") {
            $catExist        =    $this->_common->selectRow("category","nCategoryId","vCategoryDesc='".$category."' AND nCategoryId!='".$id."'");
            if(empty($catExist)) {
                $arrUpdate       =   array("vCategoryDesc"=>addslashes($category));
                $this->_common->updateFields("category",$arrUpdate,"nCategoryId='".$id."'");
                echo '1';
            }
            else
                echo '2';
        }
        else {
            echo '3';
        }

    }
    public function logout() {

        unset($_SESSION['loggedin']);  // Log out From forum
        unset($_SESSION['user']);  // Log out From forum

        LibSession::destroy();
        header("Location:".ConfigUrl::base().'index');
    }
    public function updateStatus() {
        $this->view->disableLayout();
        $this->view->disableView();
        $id             =	$this->post('id');
        $status         =	$this->post('status');
        $type           =       $this->post('type');
        $newStatus  =   ($status==0)?1:0;
        if($id!="") {
            if($type=="admin") {
                $arrUpdate       =   array("eAdminActive"=>addslashes($newStatus));
                $this->_common->updateFields("admin",$arrUpdate,"nAdminId='".$id."'");
            }
            else if($type=="user") {
                $arrUpdate       =   array("vStatus"=>addslashes($newStatus));
                $this->_common->updateFields("users",$arrUpdate,"nUserId='".$id."'");
                
                $this->_indexmodel->senduserapprovalmail($id);
            }
            echo '1';
        }
        else {
            echo '2';
        }
    }

    public function updatePlanStatus() {
        $this->view->disableLayout();
        $this->view->disableView();
        $id             =	$this->post('id');
        $status         =	$this->post('status');
       
        $newStatus  =   ($status==E)?D:E;
       
                $arrUpdate       =   array("vPlanStatus"=>addslashes($newStatus));
                $this->_common->updateFields("plans",$arrUpdate,"nPlanId='".$id."'");
            
            echo '1';
        
      
    }
  public function ajaxplantatus() {
        $this->view->disableLayout();
        $this->view->id    =   $id     = addslashes($this->post('id'));
        $this->view->vPlanStatus        =    $this->_common->selectRow("plans","vPlanStatus","nPlanId ='".$id."'"); 
    }
    public function ajaxLoadStatus() {
        $this->view->disableLayout();
        $this->view->id    =   $id     = addslashes($this->get('id'));
        $this->view->type  = $type  = addslashes($this->get('type'));
        if($type=="user") {
            $this->view->status        =    $this->_common->selectRow("users","	vStatus","nUserId='".$id."'");
        }
        else if($type=="admin") {
            $this->view->status        =    $this->_common->selectRow("admin","	eAdminActive","nAdminId='".$id."'");

        }
    }
    public function comments($page=1,$sortfield='',$orders='',$txtSearch='') {
        if($page==0) {
            $page 			= $this->get('page');
            if(!is_numeric($page))
                $page = 1;
            if(isset($page) && $page <=0 ) {
                $this->redirect('index/comments');
            }
        }
        $this->view->order          = $orders;
        $this->view->sortfield      = $sortfield;
        $cntComments                =  $this->_common->getDataCount("PC.nId","productcomment AS PC","product AS P ON P.nBusId=PC.nProductId","INNER JOIN","","");
        $this->view->pageCount      =  ceil($cntComments / PAGE_LIST_COUNT);
        $this->view->pageMaxCount   =   PAGE_LIST_COUNT;
        if($sortfield!=''){
            $ordertype                  = $sortfield.' '. $orders;
        }
        else{
            $ordertype                  = "";
        }
        $this->view->resComments    =  $this->_common->getDatas("PC.*,P.Title,P.nBusId","productcomment AS PC","product AS P ON P.nBusId=PC.nProductId","INNER JOIN","","",$ordertype,"","$page");
        $this->view->page           =  ($page) >  0 ? $page : 1;

         if($this->post('btnSearch') OR ($txtSearch!='')) {
                $txtSearch  =   ($this->post('txtSearch'))?trim($this->post('txtSearch')):$txtSearch;
                $condition  = " P.Title LIKE '%".$this->_common->escapeString($txtSearch)."%' OR PC.vComment LIKE '%".$this->_common->escapeString($txtSearch)."%'";
                $cntComments                = $this->_common->getDataCount("PC.nId","productcomment AS PC","product AS P ON P.nBusId=PC.nProductId","INNER JOIN",$condition,"");
                $this->view->txtSearch      =   $txtSearch;
                $this->view->pageCount      = ceil($cntComments / PAGE_LIST_COUNT);
                $this->view->pageMaxCount   =   PAGE_LIST_COUNT;
                $this->view->resComments    = $this->_common->getDatas("PC.*,P.Title,P.nBusId","productcomment AS PC","product AS P ON P.nBusId=PC.nProductId","INNER JOIN",$condition,"","","","$page");
                 $this->view->page          =  ($page) >  0 ? $page : 1;
          }

    }

    public function loadComments() {
        $this->view->disableLayout();
        $id =    $this->get('id');
        $resComments    =    $this->_common->getDatas("PC.*","productcomment AS PC","product AS P ON P.nBusId=PC.nProductId","LEFT JOIN","nId='".$id."'","","","","1");
        $this->view->resComments    =   $resComments[0];
    }
    public function updateComments() {
        $this->view->disableLayout();
        $this->view->disableView();
        $this->view->id    =   $id     = $this->post('id');
        $this->view->comm  = $comm  = $this->post('comm');
        $this->view->status  = $status  = $this->post('status');
        if($id!="" && $comm!="") {
            $arrUpdate  =   array("vComment"=>addslashes(trim($comm)),
                    "nStatus"=>addslashes(trim($status)));
            $this->_common->updateFields("productcomment",$arrUpdate,"nId='".$id."'");
            echo "1";
            exit;
        }
        else {
            echo "2";
            exit;
        }
        echo "3";
    }
    public function ratings($page=0,$sortfield='',$orders='',$txtSearch='') {
        if((!LibSession::get('admin_id'))) {
            $this->redirect("index");
            exit;
        }
        if($page==0) {
            $page 			= $this->get('page');
            if(!is_numeric($page))
                $page = 1;
            if(isset($page) && $page <=0 ) {
                $this->redirect('index/ratings');
            }
        }
        $this->view->order           = $orders;
        $this->view->sortfield        = $sortfield;
        if($sortfield!=''){
            $ordertype                  = $sortfield.' '. $orders;
        }
        else{
            $ordertype                  = "";
        }
        $cntComments                  =  $this->_common->getDataCount("PR.nId","productrating AS PR","product AS P ON P.nBusId=PR.nProductId","INNER JOIN","","");
        $this->view->pageCount        =  ceil($cntComments / PAGE_LIST_COUNT);
        $this->view->pageMaxCount     =   PAGE_LIST_COUNT;
        $this->view->resRatings       =  $this->_common->getDatas("PR.*,P.Title,P.nBusId","productrating AS PR","product AS P ON P.nBusId=PR.nProductId","INNER JOIN","","",$ordertype,"","$page");
        $this->view->page             =  ($page) >  0 ? $page : 1;
        if($this->post('btnSearch') OR ($txtSearch!='')) {
                $txtSearch  =   ($this->post('txtSearch'))?trim($this->post('txtSearch')):$txtSearch;
                $condition  = " P.Title LIKE '%".$this->_common->escapeString($txtSearch)."%' OR PR.nRate LIKE '%".$this->_common->escapeString($txtSearch)."%'";
                $this->view->txtSearch        =   $txtSearch;
                $cntComments                  =  $this->_common->getDataCount("PR.nId","productrating AS PR","product AS P ON P.nBusId=PR.nProductId","INNER JOIN",$condition,"");
                $this->view->pageCount        =  ceil($cntComments / PAGE_LIST_COUNT);
                $this->view->pageMaxCount     =   PAGE_LIST_COUNT;
                $this->view->resRatings       =  $this->_common->getDatas("PR.*,P.Title,P.nBusId","productrating AS PR","product AS P ON P.nBusId=PR.nProductId","INNER JOIN",$condition,"",$ordertype,"","$page");
                $this->view->page             =  ($page) >  0 ? $page : 1;
          }
    }
    public function deleteRating() {
        $this->view->disableLayout();
        $this->view->disableView();
        $this->view->id    =   $id     = $this->post('id');
        if($id!="") {
            $this->_common->deleteRecord("productrating","nId='".$id."'");
            echo "1";
            exit;
        }
        echo "2";
    }
    public function approveRating() {
        $this->view->disableLayout();
        $this->view->disableView();
        $this->view->id    =   $id     = $this->post('id');
        if($id!="") {
            $arrUpdate =   array("nStatus"=>1);
            $this->_common->updateFields("productrating",$arrUpdate,"nId='".$id."'");
            echo "1";
            exit;
        }
        echo "2";
    }

    /*
	function to load the settings template
    */
    public function settings() {
        if((!LibSession::get('admin_id'))) {
            $this->redirect("index");
            exit;
        }
        $this->view->message     =      ($this->get('message'))?$this->get('message'):'';
        $error='';
        if($this->isPost()) {
            $dataSettings=$_POST;

            //************************* SITE LOGO **********************/
            if(is_uploaded_file($_FILES['siteLogo']['tmp_name'])) {
                $logoParts = pathinfo($_FILES['siteLogo']['name']);
                $logoOriginal = ConfigUrl::imageroot('default')."mainlogo.".$logoParts['extension'];

                if(move_uploaded_file($_FILES['siteLogo']['tmp_name'], $logoOriginal)) {
                    $resizeObj = new LibResize($logoOriginal);
                    $resizeObj->resizeImage(150, 34, 'exact');
                    $rz=preg_replace("/\.([a-zA-Z]{3,4})$/","_disp.png",$logoOriginal);
                    $resizeObj->saveImage($rz, 100);
                    $logoUpdate['value']='mainlogo_disp.png';
                    $this->_common->updateFields("settings",$logoUpdate,"settingfield='siteLogo'");
                }
            }
            //************************* SITE LOGO ENDS **********************/
            //************************* SITE BANNER **********************/
            if(is_uploaded_file($_FILES['siteBanner']['tmp_name'])) {
                $bannerParts = pathinfo($_FILES['siteBanner']['name']);
                $bannerOriginal = ConfigUrl::imageroot('default')."mainbanner.".$bannerParts['extension'];
                if(move_uploaded_file($_FILES['siteBanner']['tmp_name'], $bannerOriginal)) {
                    $resizeObj2 = new LibResize($bannerOriginal);
                    $resizeObj2->resizeImage(468, 60, 'exact');
                    $rz2=preg_replace("/\.([a-zA-Z]{3,4})$/","_disp.gif",$bannerOriginal);
                    $resizeObj2->saveImage($rz2, 100);
                    $bannerUpdate['value']='mainbanner_disp.gif';
                    $this->_common->updateFields("settings",$bannerUpdate,"settingfield='siteBanner'");
                }
            }
            //************************* SITE BANNER ENDS **********************/
            foreach($dataSettings as $field=>$value) {
                //Update Other Fields
                
                $arrUpdate = array();
                $arrUpdate['value']=addslashes($value);
              
               
                $this->_common->updateFields("settings",$arrUpdate,"settingfield='".$field."'");
            }
            $this->view->message   = (empty($error)) ?    "<font color='green'>Changes Saved Successfully</font>" : $error;
        }

        /*********************** Section to load css files names / themes................................*/
        $theme_root=BASE_PATH.'public/styles';
        $csarr	=	array();
        $themes_dir = opendir($theme_root);
        $i	=	0;
        while ( ($theme_file = readdir($themes_dir)) !== false ) {
            if($theme_file <> '.' && $theme_file <> '..' && $theme_file <> 'index.php') {
                $thm		=	explode('.css',$theme_file);
                $csarr[$thm[0]]	=	$thm[0];
                $i++;
            }
        }
        $this->view->theme = $csarr;
        /*********************** Section to load css files names / themes................................*/
        // get Site Settings
//        getListFields($table,$field,$order='',$where='')
        $settings = $this->_common->getListFields('settings','*');


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

        $this->view->setting = $setting;

    } // End Setting

     public function metatag($sortfield='',$order='') {
        if((!LibSession::get('admin_id'))) {
            $this->redirect("index");
            exit;
        }
        $this->view->order      = $order;
        $this->view->sortfield   = $sortfield;
        $this->view->message	= ($_GET['msg'])?$_GET['msg']:'';
        $this->view->id	 	= $id = addslashes(($this->post('id')!='') 	? $this->post('id') :$this->get('id'));
        $this->view->act        =   $act	 	= addslashes(($this->post('act')!='') 	? $this->post('act') :$this->get('act'));

        $page 			= $this->get('page');
        if(!is_numeric($page))
            $page = 1;
        if(isset($page) && $page <=0 ) {
            $this->redirect('index/users');
        }

        if($this->isPost()) {

            if($this->post('btnTag')) {
		$act	 	= addslashes(($this->post('act')!='') 	? $this->post('act') :$this->get('act'));
                $url = addslashes(strtolower(trim($this->post('txtUrl'))));
                $title = addslashes(trim($this->post('txtTitle')));
                $keyword 	  = addslashes(trim($this->post('txtKeyword')));
                $description 	  = addslashes(trim($this->post('txtDescription')));
                

                if($url != '' && $title != '' && $keyword != '' && $description !='') {			// validate user fields
                    //$userExist        =    $this->_common->selectRow("users","nUserId","vLoginName='".$loginName."' AND nUserId!='".$id."'");
                    //if(verifyEmail($email)) {
                        //if(empty($userExist)) {
                            $arrProfile         =   array(
                                    "url"=>$url,
                                    "title"=>$title,
                                    "keyword"=>$keyword,
                                    "description"=>$description
                                    );
                            if($act =='add'){
                             $this->_common->addFields("metadata",$arrProfile);
                            }
                            else{
                                    $this->_common->updateFields("metadata",$arrProfile,"id='".$id."'");
                            }
                         $this->view->message = "<font color='green'>Successfully updated</font>";

//                        }
//                        else {
//                            $this->view->message = 'This Login Email already exist. Please try another one.';
//                        }
//                    }
//                    else {
//                        $this->view->message = 'Please enter valid Login Email.';
//                    }
                }
                else {
                    $this->view->message = 'Please enter all the details';
                }
            }
            
                      

        }
        
          if($id != '') {
            $this->view->resTags     = $this->_common->selectRecord('metadata',"*","id='".$id."'");
        }
        else {
            $cntTags                   = $this->_common->getDataCount('id','metadata','');
            if($sortfield!=''){
                $ordertype                  = $sortfield.' '. $order;
            }
            else{
                $ordertype                  = "";
            }
            $this->view->pageCount      = ceil($cntTags / PAGE_LIST_COUNT);
            $this->view->pageMaxCount   = PAGE_LIST_COUNT;
            $this->view->resTags       = $this->_common->selectResult('metadata',"*",'',$ordertype,'',$page);
        }
        

        
        $this->view->page           = ($page) >  0 ? $page : 1;


    } // End Setting

    
    /*
	function to load the form field template
    */
    public function formfields() {
        if((!LibSession::get('admin_id'))) {
            $this->redirect("index");
            exit;
        }
        // get Form Fields
        $this->view->message   ='';
        //$formFields = $this->_common->selectResult('productdesc','*');
        $formFields = $this->_common->selectAllResult('productdesc','*');
        $this->view->formFields = $formFields;        
        //Should be in Lowercase
        $this->view->mandatoryFields = array('title','description');
        $this->view->contentType = array('text' => 'big text', 'varchar' => 'small text', 'int' => 'Integer', 'date' => 'Date');
        $this->view->inputType = array('text' => 'Text', 'textarea' => 'Textarea', 'file-doc/txt' => 'File-Doc/txt', 'checkbox' => 'CheckBox');
        //Content type for static fields
        $this->view->contentTypeStatic = array('text' => 'big text');
        //Input type for static fields
        $this->view->inputTypeStatic = array('text' => 'Text');
        //Input type for video
        $this->view->inputTypeVideo = array('file-video/flv' => 'File-wmv/flv');
        //Input type for image
        $this->view->inputTypeImage = array('file-img/jpeg' => 'File-gif/jpg');

    }

    public function saveformfields() {
        $this->view->disableLayout();
        $this->view->disableView();
        // get Form Fields
        $dataFormFields = $_GET;
        $fieldSize=array('text' => '', 'varchar' => '250', 'int' => '11', 'date' => '');
        $arrUpdate = array();
        $msg = '';
        if(isset($_GET)) {
            $action = $_GET['ac'];
            $field = $_GET['fl'];
            $item = $_GET['no'];
            $fieldName = str_replace(" ", "", $_GET['nm']);
            $arrUpdate['vFldname'] = $fieldName;
            $arrUpdate['vFlddesc'] = $_GET['de'];
            $arrUpdate['vFldType'] = $_GET['ty'];
            $arrUpdate['vFldSize'] = $fieldSize[$_GET['ty']];
            $arrUpdate['vFldSearch'] = $_GET['se'];
            $arrUpdate['vInType'] = $_GET['ip'];
            $arrUpdate['vlink'] = $_GET['li'];
            $arrUpdate['nMandatory'] = $_GET['md'];



            $fieldSizeT=(!empty($fieldSize[$_GET['ty']])) ? "(".$fieldSize[$_GET['ty']].")" : "";

            if($action=='new') {
                // generate new field
                //chack for duplicate
                $formField = $this->_common->selectResult("productdesc","*","LOWER(vFldname)='".strtolower($arrUpdate['vFldname'])."'");
                if(empty($formField)) {
                    $arrUpdate['nEditable'] = 1;
                    $arrUpdate['nStatus'] = 1;
                    $arrUpdate['nRemovable'] = 1;
                    //Alter Product Description Table
                    $newField = $this->_common->addFields("productdesc",$arrUpdate);
                    //Alter Product Table
                    $alterQuery="ALTER TABLE ".$this->_common->tablePrefix."product ADD ".$arrUpdate['vFldname']." ".$arrUpdate['vFldType'].$fieldSizeT;
                    $this->_common->execute($alterQuery);

                    $msg = $newField;
                } else {
                    $msg = "duplicate";
                }

            } else {
                $formField = $this->_common->selectResult('productdesc','*','id='.$field);
                //Alter Product Description Table
                $this->_common->updateFields("productdesc",$arrUpdate,"id='".$field."'");
                //Alter Product Table
                $alterQuery="ALTER TABLE ".$this->_common->tablePrefix."product CHANGE ".$formField[0]->vFldname." ".$arrUpdate['vFldname']." ".$arrUpdate['vFldType'].$fieldSizeT;
                $this->_common->execute($alterQuery);

                $msg = 'Saved';
            }

            echo $msg;

        }


    } // End saveformfields

    public function newformfields() {
        $this->view->disableLayout();
        $this->view->disableView();
        $contentType = array('text' => 'big text', 'varchar' => 'small text', 'int' => 'Integer', 'date' => 'Date');
        $inputType = array('text' => 'Text', 'textarea' => 'Textarea', 'file-doc/txt' => 'File-Doc/txt', 'checkbox' => 'CheckBox');
        // get Form Fields
        $content = '';
        if(isset($_GET)) {
            $items = $_GET['no'];
            $i = $_GET['ct'];
            if(!empty($items)) {
                for($n=1; $n<=$items; $n++) {
                    //
                    $content .='<li id="listItem'.$i.'">
            <div class="manage_frm_div">
                <div class="manage_frn_title">
                    <div class="manage_title_dv"><input name="nStatus" id="nStatus'.$i.'" class="chkbx_div" type="checkbox" value="1" onchange="saveStatus(\''.$i.'\')"><span id="fieldLabel'.$i.'">New Field</span></div>
                    <div class="manage_title_controlls expand" id="'.$i.'" onclick="tabs(\''.$i.'\')">
                        <a href="javascript:void(0)">Edit&nbsp;</a>
                    </div>
                    <div class="clear"></div>
                </div>

                <div class="manage_form_table" id="manage_form_table'.$i.'" style="display: none;">
                    <table width="100%"  border="0" cellspacing="0" cellpadding="0">
                        <tr>
                            <td width="16%" class="brder_right">
                                <p>Field Name </p>
                                <input name="vFldname" id="vFldname'.$i.'" class="txt_area_manage" type="text" value="">
                            </td>
                            <td width="16%" class="brder_right">	<p>Display Name  </p>
                                <input name="vFlddesc" id="vFlddesc'.$i.'" class="txt_area_manage" type="text" value="">
                            </td>
                            <td width="16%" class="brder_right">	<p> Input Content Type </p>
                                '.BaseView::select('vFldType', $contentType, '', 'dropdwn_manage', '', 'vFldType'.$i).'
                            </td>
                            <td width="15%" class="brder_right"><p>Input Type </p>
                                '.BaseView::select('vInType', $inputType, '', 'dropdwn_manage','', 'vInType'.$i).'
                            </td>
                            <td width="12%" class="brder_right"><div align="center"><p >Display in advanced search  </p>
                               '.BaseView::checkbox('vFldSearch', '1', '', 'chkbx_manage','vFldSearch'.$i).'
                                </div></td>
                            <td width="9%" class="brder_right"><div align="center"><p>Is  it a Link? </p>
                                    '.BaseView::checkbox('vlink', '1', '', 'chkbx_manage','vlink'.$i).'
                                </div></td>
                            <td width="8%" class="brder_right"> <div align="center"><p>Mandatory </p>
                                    '.BaseView::checkbox('nMandatory', '1', '', 'chkbx_manage','nMandatory'.$i).'
                                </div></td>
                            <td width="8%">
                                <div align="center" class="btns_div_fmflds" id="btns_div_fmflds'.$i.'">
                                    <input type="hidden" name="fieldItem" id="fieldItem'.$i.'" value="" />
                                    <input type="button" class="btn_bg_admin" name="Submit" value="Save" id="saveField'.$i.'" onclick="saveField(\''.$i.'\',\'new\')">
                                        <input type="button" class="btn_bg_admin drp_btn" name="Submit" value="Drop" onclick="dropField(\''.$i.'\')">
                                </div>
                            </td>
                        </tr>
                    </table>

                    <div class="clear"></div>
                </div>

                <div class="clear"></div>
            </div>

        </li>';
                    $i++;
                }
            }

            echo $content;
        }


    } // End newformfields

    public function dropformfields() {
        $this->view->disableLayout();
        $this->view->disableView();
        $msg = '';
        if(isset($_GET)) {
            $field=$_GET['it'];
            // Select field
            $formField = $this->_common->selectResult('productdesc','*','id='.$field);
            // drop new field
            $deleteField = $this->_common->deleteRecord("productdesc",'id='.$field);
            //Drop from Product Table
            $alterQuery="ALTER TABLE ".$this->_common->tablePrefix."product DROP ".$formField[0]->vFldname;
            $this->_common->execute($alterQuery);
            $msg = 'droped';

        }
        echo $msg;

    } // End dropformfields

    public function savestatusformfields() {
        $this->view->disableLayout();
        $this->view->disableView();
        $msg = '';
        $enable = array();
        $enable['nStatus']=0;
        if(isset($_GET)) {
            $field=$_GET['it'];
            if(!empty($field)) {
                // Update Status
                $arrUpdate['nStatus']=$_GET['st'];
                $formField = $this->_common->selectResult('productdesc','*','id='.$field);
                if(strtolower($formField[0]->vFldname) == 'video') {
                    if($arrUpdate['nStatus']==1) { // if video is enabled disable videourl
                        $this->_common->updateFields("productdesc",$enable,"id='".($field+1)."'");
                    }
                } else if(strtolower($formField[0]->vFldname) == 'videourl') {
                    if($arrUpdate['nStatus']==1) { // if videourl is enabled disable video
                        $this->_common->updateFields("productdesc",$enable,"id='".($field-1)."'");
                    }
                }

                $this->_common->updateFields("productdesc",$arrUpdate,"id='".$field."'");
                $msg = 'updated';

            }

        }
        echo $msg;
    } // End savestatusformfields

//    public function listing($page=0) {
//        if((!LibSession::get('admin_id'))) {
//            $this->redirect("index");
//            exit;
//        }
//        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  = '';
//        $field  = substr($listFieldString,0,strlen($listFieldString)-1);
//        $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;
//        }
//
//
//    }


     public function listing($page,$sortfield='',$orders='',$txtSearch='')
    {
         //echo $sortfield; 
        if((!LibSession::get('admin_id'))){
            $this->redirect("index");
            exit;
        } // End If

        //$userId = LibSession::get('admin_id');
        //$this->view->order      = $orders;
        //$this->view->sortfield      = $sortfield;
        if($page==0 || $page=="")
        {
            LibSession::set('searchItem','');
            $page = $this->get('page');
            if(!is_numeric($page))
              $page = 1;

            if(isset($page) && $page <=0 ){
              $this->redirect('index/listing');
            }
        }

        if((!LibSession::get('searchItem'))){
            $txtSearch = '';
        } else {
            $txtSearch = LibSession::get('searchItem');
        }// End If


        $this->view->order      = $orders;
        $this->view->sortfield      = $sortfield;
        $this->view->txtSearch      = $txtSearch;
        /*****************/

        $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)
        {
            $listFieldString .= 'nBusId, DATE_FORMAT(dPostDate,"%m/%d/%Y") AS PostDate,dPostDate, nStatus ';
            foreach ($listFields as $lRecord)
            {
                $listFieldString.=', '.$lRecord->vFldname;
            }
        }

        $listArray   = array();
        $table  = 'product';
        $where  = '';

        $field = $listFieldString;
        $order1  = " ORDER BY dPostDate DESC";
        $listArray   = $this->_common->getTopList($table,$field,$order1,$where);        
        if(sizeof($listArray)>0)
        {
           $field .= ',u.vFirstName,u.vLastName';
            $this->view->listFields = explode(',',$field);
            $this->view->listArray  = $listArray;
            if($sortfield!=''){
                if($sortfield=='nStatus') {
                    $newOrder = ($orders=='ASC') ? 'DESC' :'ASC';
                    $ordertype                  = $sortfield.' '. $newOrder; 
                } else {
                   $ordertype                  = $sortfield.' '. $orders; 
                }

            }
            else{
                $ordertype                  = "";
            }
           // echo "<br>in contr",$ordertype;
             if($txtSearch != '') {
                   $condition  = " Title LIKE '%".$this->_common->escapeString($txtSearch)."%' OR u.vFirstName LIKE '%".$this->_common->escapeString($txtSearch)."%' OR u.vLastName LIKE '%".$this->_common->escapeString($txtSearch)."%' ";
             }  else {
                   $condition = "";
             }
             // $condition  = " Title LIKE '%".$this->_common->escapeString($txtSearch)."%' OR u.vFirstName LIKE '%".$this->_common->escapeString($txtSearch)."%' OR u.vLastName LIKE '%".$this->_common->escapeString($txtSearch)."%' ";

            
            //$cntComments                =  (integer)$this->_common->checkExists('product',"nBusId",$condition);
            $cntComments      = $this->_common->getDataCount("nBusId",'product AS p','users AS u ON u.nUserId=p.nUserId','left join',$condition);

            $this->view->pageCount      =  ceil($cntComments / PAGE_LIST_COUNT);
            $this->view->pageMaxCount   =   PAGE_LIST_COUNT;
            //$this->view->resProducts    =  $this->_common->getDatas($field,$table,"","","nUserId = '$userId'","","","",$page);
            $this->view->resProducts    =  $this->_common->getDatas($field,"product AS p","users AS u ON u.nUserId=p.nUserId","left join",$condition,"",$ordertype,"",$page);
            //($selFields = '*',$table1='',$table2='',$join='',$where='', $groupby = '',$orderby='',$limit='',$pagination='')
            $this->view->page           =  ($page) >  0 ? $page : 1;
        }

        if($this->post('btnSearch') OR  $this->get('txtSearch')) {
                $txtSearch  =   ($this->post('txtSearch'))?trim($this->post('txtSearch')):$this->get('txtSearch');
                LibSession::set('searchItem',$txtSearch);
                $condition  = " Title LIKE '%".$this->_common->escapeString($txtSearch)."%' OR u.vFirstName LIKE '%".$this->_common->escapeString($txtSearch)."%' OR u.vLastName LIKE '%".$this->_common->escapeString($txtSearch)."%' ";
                //$cntComments      = $this->_common->checkExists('product','nBusId',$condition);
                $cntComments      = $this->_common->getDataCount("nBusId",'product AS p','users AS u ON u.nUserId=p.nUserId','left join',$condition);
                
                //getDataCount($selFields = '*',$table1='',$table2='',$join='',$where='', $groupby = '')
                $this->view->txtSearch      =   $txtSearch;
                $this->view->pageCount      = ceil($cntComments / PAGE_LIST_COUNT);
                $this->view->pageMaxCount   =   PAGE_LIST_COUNT;
                $this->view->resProducts       = $this->_common->getDatas("nBusId,Title, DATE_FORMAT(dPostDate,'%m/%d/%Y') AS PostDate,dPostDate, nStatus,u.vFirstName,u.vLastName",'product AS p','users AS u ON u.nUserId=p.nUserId','left join',$condition,'','','',$page);
                $this->view->page           =  ($page) >  0 ? $page : 1;
          }
          //Export to excel
          if($this->post('btnExportExcel')){
                $txtSearch       =   ($this->post('txtSearch'))?trim($this->post('txtSearch')):$txtSearch;
                $sortfield       =   ($this->post('txtSortField'))?trim($this->post('txtSortField')):$sortfield;
                $orders           =   ($this->post('txtOrder'))?trim($this->post('txtOrder')):$orders;
                 if($sortfield=='nStatus') {
                    $newOrder = ($orders=='ASC') ? 'DESC' :'ASC';
                } else {
                   $newOrder  = $orders;
                }
                LibSession::set('searchItem',$txtSearch);                
               if($txtSearch!=''){
                    $condition       = " WHERE  p.Title LIKE '%".$this->_common->escapeString($txtSearch)."%' OR u.vFirstName LIKE '%".$this->_common->escapeString($txtSearch)."%' OR u.vLastName LIKE '%".$this->_common->escapeString($txtSearch)."%' ";
               }
               else{
                   $condition       = "";
               }
               //$resExportProducts     = $this->_common->selectAllResult('','*','',$condition);
               $resExportProducts     = $this->_common->getAllData('p.*,u.*','product AS p','LEFT JOIN '.$this->_common->tablePrefix.'users AS u ON u.nUserId=p.nUserId' ,$condition,'',$newOrder,$sortfield);
               
              // echo"<pre>"; print_r($resExportProducts);
                 
                $xldata	=	'<table width="100%"  border="1" cellspacing="0" cellpadding="0">
                          <tr>
                            <td class="support2" colspan="5">Listings  &nbsp;&nbsp;</td>
                          </tr>
                         </table>
                         <table width="100%"  border="1" cellspacing="0" cellpadding="0">
                          <tr>
                            <td class="ba1">
                              <table width="100%"  border="1" cellspacing="1" cellpadding="3">
                              <tr class="ba1">
                                <td width="" class="dollar"><strong>Sl No</strong> </td>
                                <td width="35%" class="dollar"><strong>Title</strong> </td>
                                <td width="25%" class="dollar"><strong>Posted by</strong> </td>
                                <td width="20%" class="dollar"><strong>Posted date</strong> </td>
                                <td width="10%" class="dollar"><strong>Status</strong> </td>
                                </tr>';
                                    if(sizeof($resExportProducts)>0) {
                                        $i=1;
                                        foreach($resExportProducts as $row) {
                                            $approvalStatus = ($row->nStatus==0) ? "Pending" : "Approved";
                                            $xldata	= $xldata.' <tr bgcolor="#FFFFFF" class="maintext">
                                            <td width="5%">'.$i.'</td>    
                                            <td width="35%">'.stripslashes($row->Title).'</td>
                                            <td width="20%">'.stripslashes($row->vFirstName).' '.stripslashes($row->vLastName).'</td>
                                            <td width="20%">'.stripslashes(date("m-d-Y",strtotime($row->dPostDate))).'</td>
                                            <td width="10%">'.stripslashes($approvalStatus).'</td>
                                            ';
                                            $i++;
                                        }//end for
				   
                                }
                                $xldata	= $xldata.'        </table>
                                        </td>
                                      </tr>
                                    </table>';
							 
        
	header("Content-type: application/ms-excel");
	header("Content-Transfer-Encoding: binary");
	header("Content-Disposition: attachment; filename=\"ListingReport.xls\"");
	echo $xldata;
        exit;
              
          }
        
        //$this->view->message='';

    }

    public function viewlisting($listId) {
        if((!LibSession::get('admin_id'))) {
            $this->redirect("index");
            exit;
        }
        $table  = 'product';
        $field  = '*';
        $order  = "";
        $where  = "nBusId = '$listId'";
        $listFieldString='';
        $listFields   = $this->_common->getListFields($table,$field,$order,$where);
        $this->view->listData   = $listFields;
        $this->view->listId     = $listId;

        /* Get the product rate */
        $productId = $listId;
        $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;

/*------------------------*/
        $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'");
        // Search Fields End ******************************************
        $fieldList = array();
        $tablist   = 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
        $this->view->listingFields      = $fieldList;
        $this->view->tablist            = $tablist;
         $this->view->fieldtype            = $fieldtype;
        $zipcode = $this->view->listData[0]->Zipcode;
        $this->view->isValidZip = (integer)$this->_common->checkExists('tbl_zipcode',"*","zipcode='$zipcode'");
/*------------------------*/
    }


    public function PaymentHistory($page=1,$sortfield='',$orders='',$txtSearch='') {
        if((!LibSession::get('admin_id'))) {
            $this->redirect("index");
            exit;
        }
        $table  = 'payments';
        $field  = '*';
        $order  = "";
        $where  = "vPaymentStatus='C'";
        $listFieldString='';
        $this->view->order           = $orders;
        $this->view->sortfield        = $sortfield;


        if($page<1) {
            $page = $this->get('page');
            if(!is_numeric($page))
                $page = 1;
            if(isset($page) && $page <=0 ) {
                $this->redirect('index/PaymentHistory');
            }
        }
        $field                      = '*';
        $table                      = 'payments';
        $where                      = "vPaymentStatus='C'";
        if($sortfield!=''){
                $ordertype                  = $sortfield.' '. $orders;
            }
            else{
                $ordertype                  = "";
            }
         if((!LibSession::get('searchItem'))){
            $txtSearch = '';            
        } else {
            $txtSearch = LibSession::get('searchItem');
        }// End If

        if($txtSearch != '')
            $condition          = $where." AND  vUserFirstName LIKE '%".$this->_common->escapeString($txtSearch)."%' OR vUserLastName LIKE '%".$this->_common->escapeString($txtSearch)."%' OR vTransactionId LIKE '%".$this->_common->escapeString($txtSearch)."%' OR vProductName LIKE '%".$this->_common->escapeString($txtSearch)."%' ";
        else
            $condition = $where;
        
        $cntComments                =  (integer)$this->_common->checkExists('payments',"nPaymentId",$condition);
        $this->view->pageCount      =  ceil($cntComments / PAGE_LIST_COUNT);
        $listFields                 = $this->_common->getDatas($field,$table,"","",$condition,"",$ordertype,"",$page);
        $this->view->page           =  ($page) >  0 ? $page : 1;
        $this->view->pageMaxCount   =   PAGE_LIST_COUNT;

        
        if($this->post('btnSearch') OR ($txtSearch!='')) {
            
                $txtSearch                  =   ($this->post('txtSearch'))?trim($this->post('txtSearch')):$txtSearch;
                LibSession::set('searchItem',$txtSearch);
                 if($txtSearch != '')
                    $condition          = $where." AND  vUserFirstName LIKE '%".$this->_common->escapeString($txtSearch)."%' OR vUserLastName LIKE '%".$this->_common->escapeString($txtSearch)."%' OR vTransactionId LIKE '%".$this->_common->escapeString($txtSearch)."%' OR vProductName LIKE '%".$this->_common->escapeString($txtSearch)."%' ";
                else
                    $condition = $where;
                //$condition                  =  $where." AND  vUserFirstName LIKE '%".$this->_common->escapeString($txtSearch)."%' OR vUserLastName LIKE '%".$this->_common->escapeString($txtSearch)."%' OR vTransactionId LIKE '%".$this->_common->escapeString($txtSearch)."%' OR vProductName LIKE '%".$this->_common->escapeString($txtSearch)."%' ";
                $cntComments                =  (integer)$this->_common->checkExists('payments',"nPaymentId","$condition");
                $this->view->txtSearch      =   $txtSearch;
                $this->view->pageCount      =  ceil($cntComments / PAGE_LIST_COUNT);
                $this->view->pageMaxCount   =   PAGE_LIST_COUNT;
                $listFields                 = $this->_common->getDatas($field,$table,"","","$condition","",$ordertype,"",$page);
                $this->view->page           =  ($page) >  0 ? $page : 1;
          }
          if($this->post('btnSearch')) {
              $txtSearch = trim($this->post('txtSearch'));
              if(empty($txtSearch)) {
                  LibSession::set('searchItem',$txtSearch);
              }
              $this->view->txtSearch      =   $txtSearch;
          }
          $this->view->listData   = $listFields;




    }

    public function saverate() {
        echo "1";
        die;
    }

    public function pendinglist($page,$sortfield='',$orders='',$txtSearch='') {
        if((!LibSession::get('admin_id'))) {
            $this->redirect("index");
            exit;
        }
        if($page==0 || $page=="") {
            LibSession::set('searchItem','');
            $page 			= $this->get('page');
            if(!is_numeric($page))
                $page = 1;
            if(isset($page) && $page <=0 ) {
                $this->redirect('index/ratings');
            }
        }

        if((!LibSession::get('searchItem'))){
            $txtSearch = '';
        } else {
            $txtSearch = LibSession::get('searchItem');
        }// End If
        
        $this->view->order          = $orders;
        $this->view->sortfield      = $sortfield;
        $this->view->txtSearch      = $txtSearch;
        if($sortfield!=''){
             $ordertype                  = $sortfield.' '. $orders;
        }
        else{
            $ordertype                  = "";
        }
        if($txtSearch != '') {
            $condition  = " nStatus ='0'
                                AND
                                    (Title LIKE '%".$this->_common->escapeString($txtSearch)."%'
                                OR
                                    u.vFirstName LIKE '%".$this->_common->escapeString($txtSearch)."%'
                                OR
                                    u.vLastName LIKE '%".$this->_common->escapeString($txtSearch)."%' )";
        } else {
            $condition  = " nStatus='0' ";
        }
        $cntUsers      = $this->_common->getDataCount("nBusId",'product AS p','users AS u ON u.nUserId=p.nUserId','left join',$condition);
        //echo '<br/>=>'.$cntUsers;
        $this->view->pageCount      =  ceil($cntUsers / PAGE_LIST_COUNT);
        $this->view->pageMaxCount   =   PAGE_LIST_COUNT;
       
        $this->view->resRatings    =  $this->_common->getDatas('p.*,u.vFirstName,u.vLastName',"product AS p","users AS u ON u.nUserId=p.nUserId","left join",$condition,"",$ordertype,"",$page);
        if($this->post('btnSearch') OR ($this->get('txtSearch'))) {
                $txtSearch  =   ($this->post('txtSearch'))?trim($this->post('txtSearch')):$txtSearch;
                //echo 'Y=>'.$txtSearch;
                LibSession::set('searchItem',$txtSearch);
                if($txtSearch != '') {
                    $condition  = " nStatus='0'
                                        AND
                                            (Title LIKE '%".$this->_common->escapeString($txtSearch)."%'
                                        OR
                                            u.vFirstName LIKE '%".$this->_common->escapeString($txtSearch)."%'
                                        OR
                                            u.vLastName LIKE '%".$this->_common->escapeString($txtSearch)."%') ";
                } else {
                     $condition  = " nStatus='0' ";
                }
                $cntUsers      = $this->_common->getDataCount("nBusId",'product AS p','users AS u ON u.nUserId=p.nUserId','left join',$condition);
                $this->view->txtSearch      =   $txtSearch;
                $this->view->pageCount      = ceil($cntUsers / PAGE_LIST_COUNT);
                $this->view->pageMaxCount   =   PAGE_LIST_COUNT;
                //$this->view->resRatings       = $this->_common->selectResult('product',"*",$condition,'','',$page);
                $this->view->resRatings       =$this->_common->getDatas("p.*,u.vFirstName,u.vLastName",'product AS p','users AS u ON u.nUserId=p.nUserId','left join',$condition,'',$ordertype,'',$page);
          }
        $this->view->page           =  ($page) >  0 ? $page : 1;
        $this->view->txtSearch      =   $txtSearch;
    }

    public function approveListing() {
        $this->view->disableLayout();
        $this->view->disableView();
        $this->view->id    =   $id     = $this->post('id');
        if($id!="") {
            $arrUpdate =   array("nStatus"=>1);
            $this->_common->updateFields("product",$arrUpdate,"nBusId='".$id."'");
            
            $this->_indexmodel->sendapprovemail($id);
            
            echo "1";
            exit;
        }
        echo "2";
    }

    public function deleteListing() {
        $this->view->disableLayout();
        $this->view->disableView();
        $this->view->id    =   $id     = $this->post('id');
        if($id!="") {
            $this->_common->deleteRecord("product","nBusId='".$id."'");
            echo "1";
            exit;
        }
        echo "2";
    }

     public function deletePlanlisting() {
        $this->view->disableLayout();
        $this->view->disableView();
        $this->view->id    =   $id     = $this->post('id');
        if($id!="") {
            $this->_common->deleteRecord("plans","nPlanId='".$id."'");
            echo "1";
            exit;
        }
        echo "2";
    }

    public function invalidlicence()
    {
        
        $this->view->setLayout('invalid');
        $this->view->licenseKey     =   $this->_common->selectRow("settings","value","settingfield='licenseKey'");      

        if($this->isPost()) {

            $txtLicenseKey  = trim($_POST['txtLicenseKey']);
            $password   =   md5(trim($_POST['password']));  

    
        if (trim($password) != "") {
            if (trim($txtLicenseKey) != "") {
                //if(check)
                $admin_paswd=$this->_common->selectRow('admin','vAdminPassword','nAdminId =1');
                if($admin_paswd==$password){
                    if (strlen($txtLicenseKey) == '30') {

                        $this->_common->updateFields("settings", array('value' => $txtLicenseKey), "settingfield = 'licenseKey'");

                        $this->redirect('index');

                        exit;

                    }else {

                        $this->view->message    =   'Invalid key. Please enter a valid key!';

                    }
                }
                else{
                    $this->view->message    =   'Incorrect password!';
                }

            }else {
                $this->view->message    =   'Please enter new key!';
            }
        } 
        else {
                $this->view->message    =   'Please enter admin password';
            }
        
        }

    }

    public function profileupdate()
    {
                if((!LibSession::get('admin_id'))) {
            $this->redirect("index");
            exit;
        }
        
        if(isset($_POST['btnPassword']))
        {
                        //update category position
            $where           = "nAdminId='1'";
            $pass            =  $this->post('txtPass');
            $repass          =  $this->post('txtCpass');
            if($pass==$repass)
            {
                $arrUpdate       =   array("vAdminPassword"=>md5(addslashes($pass)));
                $this->_common->updateFields("admin",$arrUpdate,$where);
                 $this->view->message = '<font color="green">Password reset successfully!!!</font>';
            }
            else
            {
                 $this->view->message = '<font color="red">Please enter same value for password and confirm password</font>';
            }


        }

        if(isset($_POST['btnProfile']))
        {
//
                    $where           = "nAdminId='1'";
                    $fname           = $this->post('txtFname');
                    $lname           = $this->post('txtLname');
                    $email           = $this->post('txtEmail');
                    $arrUpdate       =   array("vAdminFname"=>addslashes($fname),"vAdminLastname"=>addslashes($lname),"vAdminEmail"=>addslashes($email));
                    $this->_common->updateFields("admin",$arrUpdate,$where);
                    $this->view->message = '<font color="green">Profile updated successfully!!!</font>';
        }

        $table  = 'admin';
        $field  = '*';
        $where  = "nAdminId='1'";
        $this->view->admindetails = $this->_common->selectRecord($table,$field,$where);
    }

    public function edit($adID=''){
    
        $activeFields = $this->_common->selectAllResult("productdesc","vFldname, vFlddesc, vInType, vlink, nMandatory, nStatus","","WHERE nStatus='1'","");
        $staticFieldArr = array('Title', 'Description', 'Image', 'Video', 'VideoURL', 'Zipcode', 'Address');
        $postID=(!empty($adID)) ? $adID : $_POST['BusId'];
     
        //echopre($staticFieldArr);

        $success_message = $error= '';

            if($this->isPost())
            {//print_r($_POST);
                $dataArr = array();

                foreach($activeFields as $activeFld) {

                    if($activeFld->nMandatory==1) {

                        switch($activeFld->vInType){
                            case 'text':
                                    if(empty($_POST[$activeFld->vFldname])) {
                                        $error .='<br>'.'* '.'Enter '.$activeFld->vFlddesc;
                                    }
                                    break;
                            case 'textarea':
                                    if(empty($_POST[$activeFld->vFldname])) {
                                        $error .='<br>'.'* '.'Enter '.$activeFld->vFlddesc;
                                    }
                                    break;
                            case 'file-img/jpeg':
                                    if(is_uploaded_file($_FILES[$activeFld->vFldname]['tmp_name'])){
                                        $fileParts = pathinfo($_FILES[$activeFld->vFldname]['name']);
                                        $allowedFileType = array('jpg','jpeg');
                                        if(!in_array($fileParts['extension'], $allowedFileType)) {
                                            $error .='<br>'.'* '.'File format not supported for '.$activeFld->vFlddesc;
                                        } // End If
                                    } else {
                                        $error .='<br>'.'* '.'Upload '.$activeFld->vFlddesc;
                                    }
                                    break;
                            case 'file-video/flv':
                                    if(is_uploaded_file($_FILES[$activeFld->vFldname]['tmp_name'])){
                                        $fileParts = pathinfo($_FILES[$activeFld->vFldname]['name']);
                                        $allowedFileType = array('avi','dat','wmv','avi','mpeg','video/avi','video/x-ms-wmv','video/mpeg');
                                        if(!in_array($fileParts['extension'], $allowedFileType)) {
                                            $error .='<br>'.'* '.'File format not supported for '.$activeFld->vFlddesc;
                                        } // End If
                                    } else {
                                        $error .='<br>'.'* '.'Upload '.$activeFld->vFlddesc;
                                    }
                                    break;
                            case 'file-doc/txt':
                                    if(is_uploaded_file($_FILES[$activeFld->vFldname]['tmp_name'])){
                                        $fileParts = pathinfo($_FILES[$activeFld->vFldname]['name']);
                                        $allowedFileType = array('doc','pdf','xls');
                                        if(!in_array($fileParts['extension'], $allowedFileType)) {
                                            $error .='<br>'.'* '.'File format not supported for '.$activeFld->vFlddesc;
                                        } // End If
                                    } else {
                                        $error .='<br>'.'* '.'Upload '.$activeFld->vFlddesc;
                                    }
                                    break;
                            case 'checkbox':
                                    if(!isset($_POST[$activeFld->vFldname])){
                                        $error .='<br>'.'* '.'Check '.$activeFld->vFlddesc;
                                    } // End Isset
                                    break;

                        } //End Switch
                    } else {  // End Mandatory
                        switch($activeFld->vInType){
                            case 'file-img/jpeg':
                                    if(is_uploaded_file($_FILES[$activeFld->vFldname]['tmp_name'])){
                                        $fileParts = pathinfo($_FILES[$activeFld->vFldname]['name']);
                                        $allowedFileType = array('jpg','jpeg');
                                        if(!in_array($fileParts['extension'], $allowedFileType)) {
                                            $error .='<br>'.'* '.'File format not supported for '.$activeFld->vFlddesc;
                                        } // End If
                                    }
                                    break;
                            case 'file-video/flv':
                                    if(is_uploaded_file($_FILES[$activeFld->vFldname]['tmp_name'])){
                                        $fileParts = pathinfo($_FILES[$activeFld->vFldname]['name']);
                                        $allowedFileType = array('avi','dat','wmv','avi','mpeg','video/avi','video/x-ms-wmv','video/mpeg');
                                        if(!in_array($fileParts['extension'], $allowedFileType)) {
                                            $error .='<br>'.'* '.'File format not supported for '.$activeFld->vFlddesc;
                                        } // End If
                                    }
                                    break;
                            case 'file-doc/txt':
                                    if(is_uploaded_file($_FILES[$activeFld->vFldname]['tmp_name'])){
                                        $fileParts = pathinfo($_FILES[$activeFld->vFldname]['name']);
                                        $allowedFileType = array('doc','pdf','xls');
                                        if(!in_array($fileParts['extension'], $allowedFileType)) {
                                            $error .='<br>'.'* '.'File format not supported for '.$activeFld->vFlddesc;
                                        } // End If
                                    }
                                    break;
                        } //End Switch

                    }

                } // End Foreach




                if(empty($error)) {

                    foreach($activeFields as $activeFld) {

                        //-------------------------------
                        if(in_array($activeFld->vFldname, $staticFieldArr)) {

                                switch(strtolower($activeFld->vFldname)) {
                                    case 'title':
                                        $dataArr[$activeFld->vFldname] = addslashes($_POST[$activeFld->vFldname]);
                                        $title=$_POST[$activeFld->vFldname];
                                        break;
                                    case 'description':
                                        $dataArr[$activeFld->vFldname] = addslashes($_POST[$activeFld->vFldname]);
                                        break;
                                    case 'image':
                                        if(is_uploaded_file($_FILES['Image']['tmp_name'])){
                                            $imageUpParts = pathinfo($_FILES['Image']['name']);
                                            $imageName = 'image_'.date('HisdmY').'.'.$imageUpParts['extension'];
                                            $imageUpOriginal = ConfigUrl::uploadimageroot().$imageName;
                                            if(move_uploaded_file($_FILES['Image']['tmp_name'], $imageUpOriginal)){
                                                $resizeObj = new LibResize($imageUpOriginal);
                                                // --------------------------------------------------------------------------
                                                // 302 x 302 Image RESIZE
                                                $resizeObj->resizeImage(302, 302, 'exact');
                                                $imageName302x302 = '_302x302.'.$imageUpParts['extension'];
                                                $rz=preg_replace("/\.([a-zA-Z]{3,4})$/", $imageName302x302, $imageUpOriginal);
                                                $resizeObj->saveImage($rz, 100);
                                                // --------------------------------------------------------------------------
                                                // 450 x 400 Image RESIZE
                                                $resizeObj->resizeImage(450, 400, 'exact');
                                                $imageName450x400 = '_450x400.'.$imageUpParts['extension'];
                                                $rz=preg_replace("/\.([a-zA-Z]{3,4})$/", $imageName450x400, $imageUpOriginal);
                                                $resizeObj->saveImage($rz, 100);
                                                // --------------------------------------------------------------------------
                                                // 151 x 151 Image RESIZE
                                                $resizeObj->resizeImage(151, 151, 'exact');
                                                $imageName151x151 = '_151x151.'.$imageUpParts['extension'];
                                                $rz=preg_replace("/\.([a-zA-Z]{3,4})$/", $imageName151x151, $imageUpOriginal);
                                                $resizeObj->saveImage($rz, 100);
                                                // --------------------------------------------------------------------------
                                                $dataArr['Image']='image_'.date('HisdmY').'_302x302.'.$imageUpParts['extension'];
                                            } else {
                                                $error .= '<br>'.'* '.'Error in uploading the file for '.$activeFld->vFlddesc.', please try again !!';
                                            }
                                        }
                                        break;
                                    case 'video':
                                        if(is_uploaded_file($_FILES['Video']['tmp_name'])){
                                              
                                            $videoUpParts = pathinfo($_FILES['Video']['name']);
                                            $videoName = 'video_'.date('HisdmY').'.'.$videoUpParts['extension'];
                                            $videoUpOriginal = ConfigUrl::uploadvideoroot().$videoName;
                                             
                                            if(move_uploaded_file($_FILES['Video']['tmp_name'], $videoUpOriginal)) {
                                                
                                                @chmod($videoUpOriginal,0777);
                                                $video_thumb_image = 'video_'.date('HisdmY').'.jpg';
                                                $flv_filename = 'video_'.date('HisdmY').'.flv';
                                                /* video convert function to convert the uploaded videos to flash videos
                                                parameters are videoname,source directory and destination directory */
                                                
                                                    //checking uploaded file flv or not
                                                    switch($videoUpParts['extension'])
                                                    {
                                                        case "flv":
                                                          
                                                            $ffmpeg_value = 0;
                                                            //create thumb image
                                                            $destination = ConfigUrl::uploadvideoroot().$flv_filename;
                                                            $videoThumbPath = ConfigUrl::uploadvideoroot().$video_thumb_image;
                                                            exec("ffmpeg -i $destination -an -ss 00:00:03 -an -r 1 -vframes 1 -y -s 80x54 -f mjpeg $videoThumbPath",$return_array,$value_return);
                                                            break;
                                                        default:
                                                            
                                                            $ffmpeg_value = $this->_indexmodel->convertVideo($videoName,ConfigUrl::uploadvideoroot(),ConfigUrl::uploadvideoroot());
                                                           
                                                            break;
                                                    }//end switch

                                                    if($ffmpeg_value == 0) {
                                                        // Video uploaded successfully
                                                        $dataArr['Video']=$flv_filename;
                                                    }//end if
                                                    else {
                                                        $error .= '<br>'.'* '.'Video Conversion Failed for '.$activeFld->vFlddesc.'!!';
                                                    }//end else


                                                }//end if
                                                else
                                                {
                                                        $error .= '<br>'.'* '.'Error in uploading the file for '.$activeFld->vFlddesc.', please try again !!';
                                                }//end else

                                                // --------------------------------------------------------------------------
                                        }
                                        $dataArr[$activeFld->vFldname] = addslashes($_POST[$activeFld->vFldname]);
                                        break;
                                    case 'videourl':
                                        $dataArr[$activeFld->vFldname] = addslashes($_POST[$activeFld->vFldname]);
                                        break;
                                    case 'zipcode':
                                        $dataArr[$activeFld->vFldname] = addslashes($_POST[$activeFld->vFldname]);
                                        break;
                                    case 'address':
                                        $dataArr[$activeFld->vFldname] = addslashes($_POST[$activeFld->vFldname]);
                                        break;
                                } //End Switch

                        } // End If

                        if(!in_array($activeFld->vFldname, $staticFieldArr)) {
                                switch(($activeFld->vInType)) {
                                    case 'text':
                                        $dataArr[$activeFld->vFldname] = addslashes($_POST[$activeFld->vFldname]);
                                        break;
                                    case 'textarea':
                                        $dataArr[$activeFld->vFldname] = addslashes($_POST[$activeFld->vFldname]);
                                        break;
                                    case 'file-doc/txt':
                                        if(is_uploaded_file($_FILES[$activeFld->vFldname]['tmp_name'])){
                                            $fileUpParts = pathinfo($_FILES[$activeFld->vFldname]['name']);
                                            $fileName = 'doc_'.date('HisdmY').'.'.$fileUpParts['extension'];
                                            $fileUpOriginal = ConfigUrl::uploaddocroot().$fileName;
                                            if(move_uploaded_file($_FILES[$activeFld->vFldname]['tmp_name'], $fileUpOriginal)){
                                                $dataArr[$activeFld->vFldname] = $fileName;
                                            } else {
                                                $error .= '<br>'.'* '.'Error in uploading the file, please try again !!';
                                            }
                                        }
                                        break;
                                    case 'checkbox':
                                        $dataArr[$activeFld->vFldname] = (isset($_POST[$activeFld->vFldname])) ? 1 : 0;
                                        break;
                                } // End Switch
                        } // End If

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

                    } // End Foreach

                } // End Error // Validation Errors


                //Category ID
            $dataArr['nParentCatId'] = $_POST['category'];
            $dataArr['nCatid'] = $_POST['subcategory'];
            $categories = $this->_common->getAllData('nCategoryId, vCategoryDesc', 'category', '', "WHERE nParentId = '$dataArr[nParentCatId]'", '', 'ASC', 'vRoute');
            if (sizeof($categories) > 0 AND $dataArr['nCatid'] == "") {
                $error .='<br>' . '* ' . 'Select a subcategory ';
            }


                if(empty($error)){
                    // Success Message
                    $success_message = "<font color='green'>Changes saved Successfully.</font>";

                    $product_alias  =   Globalutils::checkAndValidateEntityAlias(MYSQL_TABLE_PREFIX.'product', $title,'nBusId' ,$_POST['BusId'], $alias_column="alias");
                    $dataArr['alias'] =$product_alias;
                    //MODIFY ADS
                    $updateAds = $this->_common->updateFields("product",$dataArr,"nBusId='".$_POST['BusId']."'");


                } // Error in Uploading any of Files

            } // End Post

             $errMsg = $error;
            if(!empty($error)) {
               $er = "Sorry, we cannot complete your posting.<br>Please provide us the missing or incorrect information enclosed below.<br><br>";
               $errMsg = $er.$error;
            } // Error
            else {
             //$this->redirect('business/ads/index');
            }
        /*------------- Categories Start -------------------*/
        $categroy_flag = true;
        $categories = $this->_common->getAllData('nCategoryId, vCategoryDesc', 'category','WHERE nParentId = 0');
        //echo 'hiiiiiiiii';exit;
// echo   $postID ;
        if($categories) {
            foreach($categories as $cat_val) {
                $products = $this->_common->selectAllResult('product','nBusId, nCatid, Title', '', "WHERE 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_title     = $category_title;
        /*------------- Categories End -------------------*/
        
$fieldValuesArr = $this->_common->selectResult("product","*","nBusId='".$postID."'",'');
//echo $fieldValuesArr[0]->nCatid;
    //echo "<pre>";    print_r($fieldValuesArr);
        //$category       =   $this->_common->selectResult("category","*","","nCategoryId='".$fieldValuesArr[0]->nCatid."'",'');
        //--------------------
        //print_r($category);
        $sub_categories = $this->_common->getAllData('nCategoryId, vCategoryDesc', 'category','',"WHERE nParentId =".$fieldValuesArr[0]->nParentCatId,'','ASC','vRoute');
        if($sub_categories) {
            foreach($sub_categories as $sub_cat) {
                $subCategoryList[$sub_cat->nCategoryId] = $sub_cat->vCategoryDesc;
            }
        }

         $this->view->parentCategory =$fieldValuesArr[0]->nParentCatId;
        $this->view->SubCategory =$fieldValuesArr[0]->nCatid;
        $this->view->subCategoryList =$subCategoryList;
        $this->view->activeFields = $activeFields;
        $this->view->staticFieldArr = $staticFieldArr;
        $this->view->fieldValuesArr = $fieldValuesArr;
        $this->view->message = $success_message;
        $this->view->error = $errMsg;
        


    } // End Function
    
    
     public function add($data='') {

 //unset($_SESSION['errorLogin']);
          $_SESSION['nUserid'] ='';
          $_SESSION['busid']   ='';
          $_SESSION['planid']  ='';
          $this->view->planfields = $this->_common->selectResult("plans","nPlanId,vPlanAmount, vPlanName,vPlanDuration","vPlanStatus='E'");
          $this->view->settings = $this->_common->selectResult("settings","settingfield,value","settingfield='listing_mode'");
          $this->view->users =  $this->_common->selectAllResult('users','nUserId, vLoginName', 'ORDER BY vLoginName ASC', "WHERE vStatus = 1 AND vDelStatus = 0 ");
    //echo "<pre>";print_r($this->view->users)   ;
    foreach($this->view->users As $users){
        $userslist[$users->nUserId]=$users->vLoginName;
    }
    $this->view->userslist = $userslist;
    
         /*------------- Categories Start -------------------*/
        $categroy_flag = true;
        $categories = $this->_common->getAllData('nCategoryId, vCategoryDesc', 'category');
        
        if($categories) {
            foreach($categories as $cat_val) {
                $products = $this->_common->selectAllResult('product','nBusId, nCatid, Title', '', "WHERE 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_title     = $category_title;
        /*------------- Categories End -------------------*/
          $_SESSION['planid']=$_POST['planid'];

          if($_POST['planid']=='')
              {
              $error .= '* '.'Enter Plan Id';
              }
       //Index
        //$this->view->setLayout('common');
        // if the user session exist , redirect to users page
        //echo '<pre>'; print_r($data); echo '</pre>';
        $activeFields = $this->_common->selectResult("productdesc","vFldname, vFlddesc, vInType, vlink, nMandatory, nStatus","nStatus='1'");
//echo '<pre>'; print_r($activeFields); echo '</pre>';
        $staticFieldArr = array('Title', 'Description', 'Image', 'Video', 'VideoURL', 'Zipcode', 'Address','Country');

        //$userLoggedIn = (isset($_SESSION['user']['userID'])) ? 1 : 0;

        $success_message = $error= '';

        // RECAPTCHA ELEMENT
        //$publickey = (!empty($this->siteSettings['recaptchaPublicKey'])) ? $this->siteSettings['recaptchaPublicKey'] : RECAPTCHA_PUBLICKEY;
        //$privatekey = (!empty($this->siteSettings['recaptchaPrivateKey'])) ? $this->siteSettings['recaptchaPrivateKey'] : RECAPTCHA_PRIVATEKEY ;
      
        //$recaptchaHTML = null;
        //$recaptchaError = null;

//        if(!empty($publickey) && !empty($privatekey)) {
//            $recaptchaHTML =recaptcha_get_html($publickey, $recaptchaError);
//        } // End If


        if($this->isPost()) {
            $dataArr = array();
            $userPlanarr=array();
            //echo "<pre>";print_r($_POST);
            //echo "entered post";exit;
            //if (isset($_POST["recaptcha_response_field"])) {
//                $resp = recaptcha_check_answer ($privatekey,
//                        $_SERVER["REMOTE_ADDR"],
//                        $_POST["recaptcha_challenge_field"],
//                        $_POST["recaptcha_response_field"]);
//
//                if ($resp->is_valid) {
                    
                
           //if(!isset($_SESSION['user']['userID']) && $_SESSION['user']['userID']=='') { // Email Validation
//                if(empty($_POST['email'])) { // Email is empty
//                    $error .= '* '.'Enter Email';
//                } else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { // Email is not empty
//                    $error .= '* '.'Enter valid Email';
//                }
            //} // End Email Validation

            foreach($activeFields as $activeFld) {

                if($activeFld->nMandatory==1) {

                    switch($activeFld->vInType) {
                        case 'text':
                            if(empty($_POST[$activeFld->vFldname])) {
                                $error .='<br>'.'* '.'Enter '.$activeFld->vFlddesc;
                            }
                            break;
                        case 'textarea':
                            if(empty($_POST[$activeFld->vFldname])) {
                                $error .='<br>'.'* '.'Enter '.$activeFld->vFlddesc;
                            }
                            break;
                        case 'file-img/jpeg':
                            if(is_uploaded_file($_FILES[$activeFld->vFldname]['tmp_name'])) {
                                $fileParts = pathinfo($_FILES[$activeFld->vFldname]['name']);
                                $allowedFileType = array('jpg','jpeg');
                                if(!in_array($fileParts['extension'], $allowedFileType)) {
                                    $error .='<br>'.'* '.'File format not supported for '.$activeFld->vFlddesc;
                                } // End If
                            } else {
                                $error .='<br>'.'* '.'Upload '.$activeFld->vFlddesc;
                            }
                            break;
                        case 'file-video/flv':
                            if(is_uploaded_file($_FILES[$activeFld->vFldname]['tmp_name'])) {
                                $fileParts = pathinfo($_FILES[$activeFld->vFldname]['name']);
                                $allowedFileType = array('avi','dat','wmv','avi','mpeg','video/avi','video/x-ms-wmv','video/mpeg');
                                if(!in_array($fileParts['extension'], $allowedFileType)) {
                                    $error .='<br>'.'* '.'File format not supported for '.$activeFld->vFlddesc;
                                } // End If
                            } else {
                                $error .='<br>'.'* '.'Upload '.$activeFld->vFlddesc;
                            }
                            break;
                        case 'file-doc/txt':
                            if(is_uploaded_file($_FILES[$activeFld->vFldname]['tmp_name'])) {
                                $fileParts = pathinfo($_FILES[$activeFld->vFldname]['name']);
                                $allowedFileType = array('doc','pdf','xls');
                                if(!in_array($fileParts['extension'], $allowedFileType)) {
                                    $error .='<br>'.'* '.'File format not supported for '.$activeFld->vFlddesc;
                                } // End If
                            } else {
                                $error .='<br>'.'* '.'Upload '.$activeFld->vFlddesc;
                            }
                            break;
                        case 'checkbox':
                            if(!isset($_POST[$activeFld->vFldname])) {
                                $error .='<br>'.'* '.'Check '.$activeFld->vFlddesc;
                            } // End Isset
                            break;

                    } //End Switch
                } else {  // End Mandatory
                    switch($activeFld->vInType) {
                        case 'file-img/jpeg':
                            if(is_uploaded_file($_FILES[$activeFld->vFldname]['tmp_name'])) {
                                $fileParts = pathinfo($_FILES[$activeFld->vFldname]['name']);
                                $allowedFileType = array('jpg','jpeg','png','gif');
                                if(!in_array($fileParts['extension'], $allowedFileType)) {
                                    $error .='<br>'.'* '.'File format not supported for '.$activeFld->vFlddesc;
                                } // End If
                            }
                            break;
                        case 'file-video/flv':
                            if(is_uploaded_file($_FILES[$activeFld->vFldname]['tmp_name'])) {
                                $fileParts = pathinfo($_FILES[$activeFld->vFldname]['name']);
                                $allowedFileType = array('avi','dat','wmv','avi','mpeg','video/avi','video/x-ms-wmv','video/mpeg');
                                if(!in_array($fileParts['extension'], $allowedFileType)) {
                                    $error .='<br>'.'* '.'File format not supported for '.$activeFld->vFlddesc;
                                } // End If
                            }
                            break;
                        case 'file-doc/txt':
                            if(is_uploaded_file($_FILES[$activeFld->vFldname]['tmp_name'])) {
                                $fileParts = pathinfo($_FILES[$activeFld->vFldname]['name']);
                                $allowedFileType = array('doc','pdf','xls');
                                if(!in_array($fileParts['extension'], $allowedFileType)) {
                                    $error .='<br>'.'* '.'File format not supported for '.$activeFld->vFlddesc;
                                } // End If
                            }
                            break;
                    } //End Switch

                }

            } // End Foreach




            if(empty($error)) {

                foreach($activeFields as $activeFld) {

                    //-------------------------------
                    if(in_array($activeFld->vFldname, $staticFieldArr)) {

                        switch(strtolower($activeFld->vFldname)) {
                            case 'title':
                                $dataArr[$activeFld->vFldname] = addslashes($_POST[$activeFld->vFldname]);
                                break;
                            case 'description':
                                $dataArr[$activeFld->vFldname] = addslashes($_POST[$activeFld->vFldname]);
                                break;
                            case 'image':
                                if(is_uploaded_file($_FILES['Image']['tmp_name'])) {
                                    $imageUpParts = pathinfo($_FILES['Image']['name']);
                                    $imageName = 'image_'.date('HisdmY').'.'.$imageUpParts['extension'];
                                    $imageUpOriginal = ConfigUrl::uploadimageroot().$imageName;
                                    if(move_uploaded_file($_FILES['Image']['tmp_name'], $imageUpOriginal)) {
                                        $resizeObj = new LibResize($imageUpOriginal);
                                        // --------------------------------------------------------------------------
                                        // 302 x 302 Image RESIZE
                                        $resizeObj->resizeImage(302, 302, 'exact');
                                        $imageName302x302 = '_302x302.'.$imageUpParts['extension'];
                                        $rz=preg_replace("/\.([a-zA-Z]{3,4})$/", $imageName302x302, $imageUpOriginal);
                                        $resizeObj->saveImage($rz, 100);
                                        // --------------------------------------------------------------------------
                                        // 450 x 400 Image RESIZE
                                        $resizeObj->resizeImage(450, 400, 'exact');
                                        $imageName450x400 = '_450x400.'.$imageUpParts['extension'];
                                        $rz=preg_replace("/\.([a-zA-Z]{3,4})$/", $imageName450x400, $imageUpOriginal);
                                        $resizeObj->saveImage($rz, 100);
                                        // --------------------------------------------------------------------------
                                        // 151 x 151 Image RESIZE
                                        $resizeObj->resizeImage(151, 151, 'exact');
                                        $imageName151x151 = '_151x151.'.$imageUpParts['extension'];
                                        $rz=preg_replace("/\.([a-zA-Z]{3,4})$/", $imageName151x151, $imageUpOriginal);
                                        $resizeObj->saveImage($rz, 100);
                                        // --------------------------------------------------------------------------


                                        $imageName151x151 = '_302x302.'.$imageUpParts['extension'];
                                        $rzimage=preg_replace("/\.([a-zA-Z]{3,4})$/", $imageName151x151, $imageName);
                                       
                                        $dataArr['Image']=$rzimage;
                                       
                                    } else {
                                        $error .= '<br>'.'* '.'Error in uploading the file for '.$activeFld->vFlddesc.', please try again !!';
                                    }
                                }
                                break;
                            case 'video':
                                if(is_uploaded_file($_FILES['Video']['tmp_name'])) {
                                    $videoUpParts = pathinfo($_FILES['Video']['name']);
                                    $videoName = 'video_'.date('HisdmY').'.'.$videoUpParts['extension'];
                                    $videoUpOriginal = ConfigUrl::uploadvideoroot().$videoName;
                                    if(move_uploaded_file($_FILES['Video']['tmp_name'], $videoUpOriginal)) {
                                        @chmod($videoUpOriginal,0777);
                                        $video_thumb_image = 'video_'.date('HisdmY').'.jpg';
                                        $flv_filename = 'video_'.date('HisdmY').'.flv';
                                        /* video convert function to convert the uploaded videos to flash videos
                                                parameters are videoname,source directory and destination directory */

                                        //checking uploaded file flv or not
                                        switch($videoUpParts['extension']) {
                                            case "flv":
                                                $ffmpeg_value = 0;
                                                //create thumb image
                                                $destination = ConfigUrl::uploadvideoroot().$flv_filename;
                                                $videoThumbPath = ConfigUrl::uploadvideoroot().$video_thumb_image;
                                                exec("ffmpeg -i $destination -an -ss 00:00:03 -an -r 1 -vframes 1 -y -s 80x54 -f mjpeg $videoThumbPath",$return_array,$value_return);
                                                break;
                                            default:
                                                $ffmpeg_value = $this->_postads->convertVideo($videoName,ConfigUrl::uploadvideoroot(),ConfigUrl::uploadvideoroot());
                                                break;
                                        }//end switch

                                        if($ffmpeg_value == 0) {
                                            // Video uploaded successfully
                                            $dataArr['Video']=$flv_filename;
                                        }//end if
                                        else {
                                            $error .= '<br>'.'* '.'Video Conversion Failed for '.$activeFld->vFlddesc.'!!';
                                        }//end else


                                    }//end if
                                    else {
                                        $error .= '<br>'.'* '.'Error in uploading the file for '.$activeFld->vFlddesc.', please try again !!';
                                    }//end else

                                    // --------------------------------------------------------------------------
                                }
                                $dataArr[$activeFld->vFldname] = addslashes($_POST[$activeFld->vFldname]);
                                break;
                            case 'videourl':
                                $dataArr[$activeFld->vFldname] = addslashes($_POST[$activeFld->vFldname]);
                                break;
                            case 'zipcode':
                                $dataArr[$activeFld->vFldname] = addslashes($_POST[$activeFld->vFldname]);
                                break;
                            case 'address':
                                $dataArr[$activeFld->vFldname] = addslashes($_POST[$activeFld->vFldname]);
                                break;
                            case 'country':
                                $dataArr[$activeFld->vFldname] = addslashes($_POST[$activeFld->vFldname]);
                                break;
                        } //End Switch

                    } // End If

                    if(!in_array($activeFld->vFldname, $staticFieldArr)) {
                        switch(($activeFld->vInType)) {
                            case 'text':
                                $dataArr[$activeFld->vFldname] = addslashes($_POST[$activeFld->vFldname]);
                                break;
                            case 'textarea':
                                $dataArr[$activeFld->vFldname] = addslashes($_POST[$activeFld->vFldname]);
                                break;
                            case 'file-doc/txt':
                                if(is_uploaded_file($_FILES[$activeFld->vFldname]['tmp_name'])) {
                                    $fileUpParts = pathinfo($_FILES[$activeFld->vFldname]['name']);
                                    $fileName = 'doc_'.date('HisdmY').'.'.$fileUpParts['extension'];
                                    $fileUpOriginal = ConfigUrl::uploaddocroot().$fileName;
                                    if(move_uploaded_file($_FILES[$activeFld->vFldname]['tmp_name'], $fileUpOriginal)) {
                                        $dataArr[$activeFld->vFldname] = $fileName;
                                    } else {
                                        $error .= '<br>'.'* '.'Error in uploading the file, please try again !!';
                                    }
                                }
                                break;
                            case 'checkbox':
                                $dataArr[$activeFld->vFldname] = (isset($_POST[$activeFld->vFldname])) ? 1 : 0;
                                break;
                        } // End Switch
                    } // End If

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

                } // End Foreach

            } // End Error // Validation Errors

            //Post Status -- active
            $dataArr['nStatus'] = 1;
            //Category ID
            $dataArr['nCatid'] = $_POST['category'];
            //Post Date
            $dataArr['dPostDate'] = date('Y-m-d');

            if(empty($error)) {
                // Success Message
                
                // Check For User
                //$postedEmail = (!isset($_SESSION['user']['userID']) && $_SESSION['user']['userID']=='') ? $_POST['email'] : '';
                $user=1;
                $chkdUser = $this->_indexmodel->checkUser($postedEmail, $_SESSION['user']['userID'],$this->siteSettings['userApproval']);

                //Posting User
                $dataArr['nUserId']  = $_POST['users'];
                $_SESSION['nUserid'] = $chkdUser['user']->nUserId;
               
                // Retuned User Details
                // $chkdUser['user'] // Newly registered User Details
                // $chkdUser['mailcontent']; // User Email Notification Content
                // $chkdUser['mailcontentadmin']; // Admin Email Notification Content
                // $chkdUser['autoregister']; // Auto Registration Status

                // If Auto Registration Send Mail
              
                if($chkdUser['autoregister']==1) {
                    
                    $subject = SITE_NAME.'Thank You For Registering With Us!';
                    $message = $chkdUser['mailcontentuser'];
                    $message = str_replace("{SITE_EMAIL}", $this->siteSettings['adminEmail'], $message);
                    $userNotif = array();
                    $userNotif['from']=$this->siteSettings['adminEmail'];
                    $userNotif['subject']=$subject;
                    $userNotif['message']=$message;
                    $userNotif['to']=$postedEmail;
                    LibEmailsend::email_senderNow($userNotif);

                    //Admin Notification
                    $subject_admin = 'New User Registration';
                    $messageAdmin = $chkdUser['mailcontentadmin'];
                    $adminNotif = array();
                    $adminNotif['from']=$this->siteSettings['adminEmail'];
                    $adminNotif['subject']=$subject_admin;
                    $adminNotif['message']=$messageAdmin;
                    $adminNotif['to']=$this->siteSettings['adminEmail'];
                    LibEmailsend::email_senderNow($adminNotif);

                    //Post Status -- pending for approval
                    $dataArr['nStatus'] = 0;
              /* if($this->siteSettings['userApproval']=='automatic')
                {
                    $success_message = 'Posting Saved Successfully!';
                }
              if($this->siteSettings['userApproval']=='admin')
                {*/
                    //$success_message = 'Posting has been saved and is in pending status. Please activate your account through the activation e-mail. Thank You!';
              /*  }

               * else  if($this->siteSettings['userApproval']=='email')
                {
                    $success_message = 'Posting has been saved and is in pending status. Please activate your acoount through the activation e-mail. Thank You!';
                }*/
             

                $success_message = "<font color='green'>Posting Saved Successfully</font>";

                } // End Auto Registration

                //POST ADS
                $dataArr['nPlanId']=$_POST['planid'];
                $dataArr['nPaymentStatus']='P';
                $postAds = $this->_common->addFields("product",$dataArr);



                

                $userPlanarr['vStatus']='N';
                $userPlanarr['nUserId']= $chkdUser['user']->nUserId;
                $userPlanarr['nPlanId']= $_SESSION['planid'];
                $this->view->busid = $this->_common->selectRow("product","nBusId","nUserId =".$_POST['users']."");
                $userPlanarr['nProductId']=$this->view->busid;
                $userPlanarr['dDate'] = date('d-m-Y');
                $this->_common->addFields("userplans",$userPlanarr);
                /*if($this->siteSettings['userApproval']=='automatic')
                {
                    $success_message = 'Posting Saved Successfully!';
                }
              else if($this->siteSettings['userApproval']=='admin')
                {*/
                    //$success_message = 'Posting has been saved ,waiting for the admin to approve!';
                $success_message = "<font color='green'>Posting Saved Successfully</font>";
                /*}
              else  if($this->siteSettings['userApproval']=='email')
                {
                    $success_message = 'Posting has been saved and is in pending status. Please activate your acoount through the activation e-mail. Thank You!';
                }*/
                 // $this->redirect('index/listing');
                    
//                     if($this->view->settings[0]->value=="planbased"){
//             $this->redirect('paypal/paymentdetails/'.$_SESSION['nUserid']);}
            } // Error in Uploading any of Files

            //} 
//            else {  // Captcha Error
//                    # set the error code so that we can display it
//                    //$error = $resp->error;
//                    $error = 'Invalid Security Code';
//                }
            //} // End Captcha Check

        } // End Post
        $errMsg = $error;
        if(!empty($error)) {
            
            $er = "Sorry, we cannot complete your posting.<br>Please provide us the missing or incorrect information enclosed below.<br><br>";
            $errMsg = $er.$error;
        } // Error


        $this->view->siteSettings = $this->siteSettings;
        $this->view->recaptchaHTML = $recaptchaHTML;
        $this->view->activeFields = $activeFields;
        $this->view->staticFieldArr = $staticFieldArr;
        $this->view->message = $success_message;
        $this->view->error = $errMsg;

    } // End Function
    //
    //cron
    public function cron() {
        $this->view->disableLayout();
        $this->view->disableView();
        
        //Get expired listings
        $join_expiry   =   " INNER JOIN ".$this->_common->tablePrefix."plans AS plans ON plans.nPlanId=product.nPlanId 
                            INNER JOIN ".$this->_common->tablePrefix."users AS users ON product.nUserId=users.nUserId ";
        $where_expiry  =   " WHERE product.nStatus=1 
                            AND product.nPaymentStatus='P' 
                            AND plans.vPlantype='M' 
                            AND CURDATE()= ADDDATE(product.nPlanExpiryDate,INTERVAL 1 DAY)";
        
                            //AND CURDATE()=ADDDATE(ADDDATE(dPostDate,INTERVAL (SELECT vPlanDuration FROM EasyIndex_plans WHERE nPlanId=product.nPlanId) MONTH),INTERVAL 1 DAY)";
    $resExpiryList =$this->_common->getAllData('*','product AS product',$join_expiry ,$where_expiry);
        
        if(sizeof($resExpiryList)>0){
            foreach($resExpiryList AS $listing){
                //update status
                $condition      = " nBusId ='".$listing->nBusId."'";
                $postedArray    = array('nStatus'=>'0',
                                    'nPaymentStatus'=>'N');
                $this->_common->updateFields('product',$postedArray,$condition);
                //send mail 
                //User Notification
                $mainContent = '<html>
                                <p><img src="{IMG}" /></p>
                                <p>Dear {MEMBER_NAME},</p><br><br>
                                        {MESSAGE_BODY}</html>';
                
                $msg = '<table class="maintext2" cellpadding="4" cellspacing="1" width="100%" border="0">
                                <tbody>
                                    <tr bgcolor="#ffffff">
                                        <td colspan="2" class="maintext2" align="left">Welcome to {SITE_NAME}.<br/><br/> 
                                        Your Ad in {SITE_NAME} has expired .<b><u><br /><br/>Details of the ad are as follows :</u></b></td>
                                    </tr>
                                    <tr bgcolor="#ffffff">
                                        <td width="14%" align="left">Title</td>
                                        <td width="86%">{TITLE}</td>
                                    </tr>
                                    <tr bgcolor="#ffffff">
                                        <td align="left">Description</td>
                                        <td>{DESCRIPTION}</td>
                                    </tr>';

               $msg .= '<tr>
                            <td colspan="2" align="left"><b>Please login in and renew your ad.</b></td> </tr> 

                        </tr>';
               $msg .='<tr><td>&nbsp;</td></tr>';
               $msg .= '<tr bgcolor="#ffffff">
                                        <td colspan="2" align="left">Thank You,</td>
                                    </tr>
                                    <tr bgcolor="#ffffff">
                                        <td colspan="2" align="left">{SITE_NAME} | {SITE_URL}<br /></td>
                                    </tr>
                                </tbody>
                            </table> ';

                
                $msgBody = str_replace("{MESSAGE_BODY}", $msg, $mainContent); // Replace the Message Body
                $msgBody = str_replace("{IMG}", ConfigUrl::images('default').PRODUCT_LOGO, $msgBody);
                $msgBody = str_replace("{MEMBER_NAME}", $listing->vFirstName, $msgBody); // Replace the Member Name
                $msgBody = str_replace("{SITE_NAME}", SITE_NAME, $msgBody); // Replace the Site Name
                $msgBody = str_replace("{TITLE}", $listing->Title, $msgBody); // Replace the Site Name
                $msgBody = str_replace("{DESCRIPTION}", $listing->Description, $msgBody); // Replace the Site Name
                $msgBody = str_replace("{SITE_URL}", ConfigUrl::base('default'), $msgBody); // Replace the Site Url
                $msgBody = str_replace("{activate_link}", $activate_link, $msgBody); // Replace the Activation Link
                $subject = SITE_NAME." : Ad Expiry Notification";
                $userNotif = array();
                $userNotif['from']=$this->siteSettings['adminEmail'];
                $userNotif['subject']=$subject;
                $userNotif['message']=$msgBody;
                $userNotif['to']=$listing->vEmail;
                LibEmailsend::email_senderNow($userNotif);
                //echo $msgBody;
                
            }
        }
        
        //Get listings 3 days prior to expiry
        $join   =   " INNER JOIN ".$this->_common->tablePrefix."plans AS plans ON plans.nPlanId=product.nPlanId 
                       INNER JOIN ".$this->_common->tablePrefix."users AS users ON product.nUserId=users.nUserId ";
        $where  =   " WHERE product.nStatus=1 
                    AND product.nPaymentStatus='P' 
                    AND plans.vPlantype='M' 
                    AND CURDATE()= ADDDATE(product.nPlanExpiryDate,INTERVAL -3 DAY)";
                    //AND CURDATE()=ADDDATE(ADDDATE('dPostDate',INTERVAL (SELECT vPlanDuration FROM EasyIndex_plans WHERE nPlanId=product.nPlanId) MONTH),INTERVAL -3 DAY)";

       $resRenewalList =$this->_common->getAllData('*','product AS product',$join ,$where);
        if(sizeof($resRenewalList)>0){
            foreach($resRenewalList AS $listing){
                //send mail 
                //User Notification
                $mainContent = '<html>
                                <p><img src="{IMG}" /></p>
                                <p>Dear {MEMBER_NAME},</p><br><br>
                                        {MESSAGE_BODY}</html>';
                
                $msg = '<table class="maintext2" cellpadding="4" cellspacing="1" width="100%" border="0">
                                <tbody>
                                    <tr bgcolor="#ffffff">
                                        <td colspan="2" class="maintext2" align="left">Welcome to {SITE_NAME}.<br/><br/> 
                                        Your Ad in {SITE_NAME} will expire within 3 days .<b><u><br /><br/>Details of the ad are as follows :</u></b></td>
                                    </tr>
                                    <tr bgcolor="#ffffff">
                                        <td width="14%" align="left">Title</td>
                                        <td width="86%">{TITLE}</td>
                                    </tr>
                                    <tr bgcolor="#ffffff">
                                        <td align="left">Description</td>
                                        <td>{DESCRIPTION}</td>
                                    </tr>';

               $msg .= '<tr>
                            <td colspan="2" align="left"><b>Please login in and renew your ad.</b></td> </tr> 

                        </tr>';
               $msg .='<tr><td>&nbsp;</td></tr>';
               $msg .= '<tr bgcolor="#ffffff">
                                        <td colspan="2" align="left">Thank You,</td>
                                    </tr>
                                    <tr bgcolor="#ffffff">
                                        <td colspan="2" align="left">{SITE_NAME} | {SITE_URL}<br /></td>
                                    </tr>
                                </tbody>
                            </table> ';

                $activate_link = ConfigUrl::base('default').'login/activation/'.$activationKey;

                $msgBody = str_replace("{MESSAGE_BODY}", $msg, $mainContent); // Replace the Message Body
                $msgBody = str_replace("{IMG}", ConfigUrl::images('default').PRODUCT_LOGO, $msgBody);
                $msgBody = str_replace("{MEMBER_NAME}", $listing->vFirstName, $msgBody); // Replace the Member Name
                $msgBody = str_replace("{SITE_NAME}", SITE_NAME, $msgBody); // Replace the Site Name
                $msgBody = str_replace("{TITLE}", $listing->Title, $msgBody); // Replace the Site Name
                $msgBody = str_replace("{DESCRIPTION}", $listing->Description, $msgBody); // Replace the Site Name
                $msgBody = str_replace("{SITE_URL}", ConfigUrl::base('default'), $msgBody); // Replace the Site Url
                $msgBody = str_replace("{activate_link}", $activate_link, $msgBody); // Replace the Activation Link
                $subject = SITE_NAME." : Ad Expiry Notification";
                $userNotif = array();
                $userNotif['from']=$this->siteSettings['adminEmail'];
                $userNotif['subject']=$subject;
                $userNotif['message']=$msgBody;
                $userNotif['to']=$listing->vEmail;
                LibEmailsend::email_senderNow($userNotif);
                //echo $msgBody;
               
            }
        }

    }
    public function loadSubCategories(){

        $catId = $_POST['categoryId'];
        //$subCategories = $this->_common->selectAllResult("category","*","WHERE nParentId ='$catId'");
        //print_r($subCategories);exit;
        $categories = $this->_common->selectAllResult('category','nCategoryId, vCategoryDesc',"WHERE nParentId = '$catId'",'','ASC','vCategoryDesc');
        if($categories) {
            foreach($categories as $cat_val) {
                $category_title[$cat_val->nCategoryId] = $cat_val->vCategoryDesc;
            }
        }
        //echo "<pre>";print_r($category_title);exit;
        echo $this->view->select('subcategory', $category_title, '', 'select_drpbx','','subcategory',' size="4"');
        exit;
    }

    function checkData($mydate) {
        if (date('Y-m-d H:i:s', strtotime($mydate)) == $mydate) {
            return true;
        } else {
            return false;
        }
    }  
    
     public function contentmanagement($contentId)
    {                 
         //echo $sortfield;
         
        if((!LibSession::get('admin_id'))){
            $this->redirect("index");
            exit;
        } // End If   

       
        $listArray   = array();
        $table  = 'cms';
        $where  = '';
        $field = 'nContentId,vTitle';
        
        $order1  = " ORDER BY nContentId ASC";
        $listArray   = $this->_common->getTopList($table,$field,$order1,$where);
        $this->view->cmsContent  = $listArray;
       
        if(isset($contentId)&& $contentId!=''){
            $table  = 'cms';
            $where  = 'nContentId = '.$contentId ;
            $field = '*';  
            
            $contentArray   = $this->_common->selectRecord($table,$field,$where);  
            $this->view->cmsContentRecord  = $contentArray;
        }
    if(isset($_POST['saveContent']) && $_POST['saveContent']!='')
    {       
      unset ($_POST['saveContent']);
      $this->_common->updateFields("cms",$_POST,"nContentId= '".$_POST['nContentId']."'");      
      $this->view->message = "The Contents has been Edited Successfully.";
     
    }       
        
 
    }
}
?>