<?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 $userName   =   '';
    public $userPass   =   '';
    public $userId     =   0;
    public function init() {
        parent::init();
        $this->_common		= new ModelCommon;
        $this->_libEmailSend = new LibEmailsend();
        $this->_session = new LibSession();
//                $this->_indexmodel      = new ModelIndex;
 
        if($this->_session->get('user_id')=="") {
            $this->switchmodule(ConfigUrl::base('default'));
            exit;
        }

           
        // get Site Settings ***************************************
        $settings = $this->_common->selectResult('settings','*');

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

        $this->view->setting = $setting;
        // get Site Settings end ***************************************

        /*------------- Categories End -------------------*/
        $categroy_flag = true;
        $categories = $this->_common->getAllData('nCategoryId, vCategoryDesc', 'category');
        if($categories) {
            foreach($categories as $cat_val) {
                $products = $this->_common->selectResult('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_flag      = $categroy_flag;
        $this->view->category           = $category;
        $this->view->category_title     = $category_title;
        /*------------- Categories End -------------------*/

        // Search Fields **********************************************
        $txtsearch = '';
        $listingFields = $this->_common->selectResult("productdesc","vFldname, vFlddesc,vlink", "", "WHERE nStatus='1'");
        // Search Fields End ******************************************
        $fieldList = array();

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

    }

    public function authenticate() {

    }

    /*
	function to load the index template
    */
    public function index() {
        $this->redirect('index/dashboard');

    }

    public function payment() {

        $this->view->listId  = $this->_session->get('temp_listing_id');

        if( $this->view->listId == '') {
            $this->redirect('index/dashboard');
            exit;
        }


        if(SITE_PAYMENT_MODE!='paid') {
            $arrProfile         =   array("nFeatured"=>1);
           
            $this->_common->updateFields("product",$arrProfile,"nBusId='".$this->view->listId."'");
            $this->view->payMessage = "<font color='green'>Successfully updated</font>";
            $where  = "nBusId = '".$this->view->listId."'";
            $alias    =   $this->_common->selectRow('product','alias',$where);             
            $this->redirect('index/viewlisting/'.$alias.'/1/1/');
            exit;
        }


        $this->userId   = $this->_session->get('user_id');
        $authorizeEnable      =   $this->_common->selectRow("settings","value","settingfield='authorize_enable'");
        $paypalEnable      =   $this->_common->selectRow("settings","value","settingfield='enablepaypal'");

        $this->view->paypalEnabled =($paypalEnable=='Y')? true :false;
        $this->view->authorizeEnabled = ($authorizeEnable=='Y')? true : false;
        $this->view->message=($paypalEnable!='Y' && $authorizeEnable!='Y') ? 'No Payment Option Available. Please Contact Administrator.':'';

        $listFields  = array();
        $table  = 'users';
        $field  = 'vFirstName,vLastName,vAddress1,vCity,vState,vCountry,vEmail,nZip';
        $where  = " nUserId ='".$this->userId."' ";
        $order  = " LIMIT 0,1";
        $resBusiness   =   $this->_common->selectRecord($table,$field,$order,$where);


        if($this->post('process')) {
            $this->view->fname =$this->post('fname');
            $this->view->lname =$this->post('lname');
            $this->view->email =$this->post('email');
            $this->view->address =$this->post('add1');
            $this->view->city =$this->post('city');
            $this->view->state =$this->post('state');
            $this->view->country =$this->post('country');
            $this->view->zip =$this->post('zip');
        }

        if($resBusiness) {
            $this->view->fname =$resBusiness->vFirstName;
            $this->view->lname =$resBusiness->vLastName;
            $this->view->email =$resBusiness->vEmail;
            $this->view->address =$resBusiness->vAddress1;
            $this->view->city =$resBusiness->vCity;
            $this->view->state =$resBusiness->vState;
            $this->view->country =$resBusiness->vCountry;
            $this->view->zip =$resBusiness->nZip;

        }

    }

    public function dashboard($flag=0) {
        if($flag==1) {
            $this->view->updateMessage='Account has been activated !';
            
        } else if($flag==2) {
            $this->view->updateMessage='The account has already been activated!';
        }

        $this->userName = $this->_session->get('user_login');
        $this->userPass = $this->_session->get('user_pass');
        $this->userId   = $this->_session->get('user_id');
//        echo "business index..."; die;
//        $traficArray = array();
//        $table  = 'statistics';
//        $field  = 'nCount,dTrackingDate';
//
//        $traficArray = $this->_common->getSiteTraffic($table,$field);
//        if(sizeof($traficArray)>0)
//        {
//            foreach ($traficArray as $tRecord)
//            {
//            $this->graph->setCategory(date("M",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,3";
        $listFieldString='';
        $listFields   = $this->_common->selectResult($table,$field,$order);
        if(sizeof($listFields)>0) {
            foreach ($listFields as $lRecord) {
                $listFieldString.=$lRecord->vFldname.',';
            }
        }
//        $listFieldString.='nBusId';
//        substr($listFieldString,0,strlen($listFieldString)-1);
        $listArray   = array();
        $table  = 'product';
        $field  = substr($listFieldString,0,strlen($listFieldString)-1).',alias,DATE_FORMAT(dPostDate,"%m/%d/%Y") AS dPostDate,nBusId';
        $order  = " ORDER BY dPostDate DESC  LIMIT 0,5";
        $where  = "WHERE nUserId='".$this->userId."'";
//        error_reporting(0);
        $listArray   = $this->_common->selectResult($table,$field,$order,$where);
        if(sizeof($listArray)>0) {
            $this->view->listFields = explode(',',$field);
            $this->view->listArray  = $listArray;
        }
        // Top rated contenet listing
        $query="SELECT PRT.`nProductId`,SUM(PRT.`nRate`) AS RATE,PDT.nBusId as BusId,PDT.Title,PDT.alias 
                  FROM `".MYSQL_TABLE_PREFIX."productrating` PRT
            INNER JOIN ".MYSQL_TABLE_PREFIX."product PDT ON  PDT.nBusId= PRT.nProductId
                 WHERE PRT.`nStatus`='1'
              GROUP BY `nProductId`
              ORDER BY round(nRate/COUNT(nProductId)) DESC";
        $catArray   = $this->_common->selectQuery($query);
        $this->view->catArray   = $catArray ;
        $this->view->index      = $this;

    }

    public function profile() {
        $this->userId   = $this->_session->get('user_id');
        ;
        if($this->isPost()) {

            if($this->post('btnProfile')) {
                $email = addslashes(strtolower(trim($this->post('txtEmail'))));
                $loginName = addslashes(strtolower(trim($this->post('loginName'))));

                $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($loginName != '' && $fName != '' && $lName != '') {			// validate user fields
                    $userExist        =    $this->_common->selectRow("users","nUserId","vLoginName='".$loginName."' AND nUserId!='".$this->userId."'");
                    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);
                            $this->_common->updateFields("users",$arrProfile,"nUserId='".$this->userId."'");

                            $arrProfile   =   array("fname"=>$fName,"lname"=>$lName,"email"=>$email);


                            $this->_common->updateForumFields("users",$arrProfile,"username='".$loginName."'");


                            $this->view->message = 'Successfully updated';
                            $this->view->messageClass ='green';

                        }
                        else {
                            $this->view->message = 'This Login Email already exist. Please try another one.';
                            $this->view->messageClass ='red';
                        }
                    }
                    else {
                        $this->view->message = 'Please enter valid Login Email.';
                        $this->view->messageClass ='red';
                    }
                }
                else {
                    $this->view->message = 'Please enter all the details';
                    $this->view->messageClass ='red';
                }
            }
            else if($this->post('btnPassword')) {
                $password = addslashes(strtolower(trim($this->post('txtPass'))));

                $arrProfile         =   array("vPassword"=>md5($password));

                $this->_common->updateFields("users",$arrProfile,"nUserId='".$this->userId."'");
                $this->view->message = 'Successfully updated';
                $this->view->messageClass ='green';
            }



        }
        if($this->userId != 0) {
            $this->view->resUsers     = $this->_common->selectRecord('users',"*",'',"nUserId='".$this->userId."'");
        }
    }
    /* public function comments()
    {
      
          $this->view->resComments    =   $this->_common->getDatas('PC.*,P.Name','productcomment AS PC',"product AS P ON PC.nProductId=P.nBusId",'LEFT JOIN ','','','','','1');
    }
    */


    public function ProductRatingStar($pid,$units='',$static='') {


        if($pid!='') {

            $select_rating_count=$this->_common->selectQuery("SELECT round(nRate/COUNT(nProductId)) AS average_rating
                                          FROM ".MYSQL_TABLE_PREFIX."productrating
                                         WHERE nProductId = '$pid' AND nStatus='1' GROUP BY nProductId ORDER BY nRate DESC");
            $average_rating_count    =0;

            if(sizeof($select_rating_count)>0) {

                //                     $rating_count = @mysqli_fetch_array($select_rating_count);


                if($select_rating_count[0]->average_rating!='') {
                    $average_rating_count    = $select_rating_count[0]->average_rating;

                }
                else {
                    $average_rating_count    =0;
                }

            }


        }
        return $average_rating_count;


    }

    //comments section
    public function comments($page=1,$sortfield='',$order='') {
        if((!$this->_session->get('user_id'))) {
            $this->redirect("index");
            exit;
        }
        $userId =   $this->_session->get('user_id');
        if($page==0 || $page=="") {
            $page 			= $this->get('page');
            if(!is_numeric($page))
                $page = 1;
            if(isset($page) && $page <=0 ) {
                $this->redirect('index/comments');
            }
        }
        $this->view->order      = $order;
        $this->view->sortfield      = $sortfield;
        if($sortfield!='') {
            $ordertype                  = $sortfield.' '. $order;
        }
        else {
            $ordertype                  = "";
        }
        //echo "order type = ".$ordertype;
        $cntComments                  =  $this->_common->getDataCount("PC.nId","productcomment AS PC","product AS P ON P.nBusId=PC.nProductId","LEFT JOIN","P.nUserId='".$userId."'","");
        $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 as BusID,P.alias","productcomment AS PC","product AS P ON P.nBusId=PC.nProductId","LEFT JOIN","P.nUserId='".$userId."'","","$ordertype","","$page");
        $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');
            if($txtSearch != '')
                $condition          = "nUserId = '$userId' AND Title LIKE '%".$this->_common->escapeString($txtSearch)."%' OR vComment LIKE '%".$this->_common->escapeString($txtSearch)."%' OR  dPostDate LIKE '%".$this->_common->escapeString($txtSearch)."%' OR  vName LIKE '%".$this->_common->escapeString($txtSearch)."%' OR  vEmail LIKE '%".$this->_common->escapeString($txtSearch)."%'   OR PC.nStatus LIKE '%".$this->_common->escapeString($txtSearch)."%'   ";
            else
                $condition          = "nUserId = '$userId'";

            $cntComments                  =  $this->_common->getDataCount("PC.nId","productcomment AS PC","product AS P ON P.nBusId=PC.nProductId","LEFT JOIN","$conditon","");
            $this->view->txtSearch      =   $txtSearch;
            $this->view->pageCount      = ceil($cntComments / PAGE_LIST_COUNT);
            $this->view->pageMaxCount   =   PAGE_LIST_COUNT;
            // $this->view->resProducts    =  $this->_common->getDatas($field,$table,"","","$condition","",$ordertype,"",$page);
            $this->view->resComments    =  $this->_common->getDatas("PC.*,P.Title","productcomment AS PC","product AS P ON P.nBusId=PC.nProductId","LEFT JOIN","$condition","","$ordertype","","$page");
        }

                

    }

    public function loadComments() {

        if((!$this->_session->get('user_id'))) {
            $this->redirect("index");
            exit;
        }
        $userId =   $this->_session->get('user_id');
        $this->view->disableLayout();
        $id =    $this->get('id');
        $resComments    =    $this->_common->getDatas("PC.*,P.Title","productcomment AS PC","product AS P ON P.nBusId=PC.nProductId","LEFT JOIN","nId='".$id."' AND P.nUserId='".$userId."'","","","","1");
        $this->view->resComments    =   $resComments[0];
    }
    public function updateComments() {
        if((!$this->_session->get('user_id'))) {
            $this->redirect("index");
            exit;
        }
        $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";
    }
    //Ratings section
    public function ratings($page=1,$sortfield='',$order='') {
        if((!$this->_session->get('user_id'))) {
            $this->redirect("index");
            exit;
        }
        $userId =   $this->_session->get('user_id');
        if($page==0 || $page =="") {
            $page 			= $this->get('page');
            if(!is_numeric($page))
                $page = 1;
            if(isset($page) && $page <=0 ) {
                $this->redirect('index/ratings');
            }
        }
        $this->view->order      = $order;
        $this->view->sortfield      = $sortfield;
        if($sortfield!='') {
            $ordertype                  = $sortfield.' '. $order;
        }
        else {
            $ordertype                  = "";
        }
        $cntComments                  =  $this->_common->getDataCount("PR.nId","productrating AS PR","product AS P ON P.nBusId=PR.nProductId","LEFT JOIN","P.nUserId='".$userId."'","");
        $this->view->pageCount      =  ceil($cntComments / PAGE_LIST_COUNT);
        $this->view->pageMaxCount   =   PAGE_LIST_COUNT;
        $this->view->resRatings   =  $this->_common->getDatas("PR.*,P.Title,P.alias","productrating AS PR","product AS P ON P.nBusId=PR.nProductId","LEFT JOIN","P.nUserId='".$userId."'","","$ordertype","","$page");
        $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');
            if($txtSearch != '')
                $condition          = "nUserId = '$userId' AND Title LIKE '%".$this->_common->escapeString($txtSearch)."%' OR nRate LIKE '%".$this->_common->escapeString($txtSearch)."%' OR dPostDate LIKE '%".$this->_common->escapeString($txtSearch)."%' OR PR.nStatus LIKE '%".$this->_common->escapeString($txtSearch)."%'   ";
            else
                $condition          = "nUserId = '$userId'";

            $cntComments                  =  $this->_common->getDataCount("PR.nId","productrating AS PR","product AS P ON P.nBusId=PR.nProductId","LEFT JOIN","$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($field,$table,"","","$condition","",$ordertype,"",$page);
            $this->view->resRatings   =  $this->_common->getDatas("PR.*,P.Title","productrating AS PR","product AS P ON P.nBusId=PR.nProductId","LEFT JOIN","$condition","","$ordertype","","$page");
        }
    }
    public function deleteRating() {
        if((!$this->_session->get('user_id'))) {
            $this->redirect("index");
            exit;
        }
        $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() {
        if((!$this->_session->get('user_id'))) {
            $this->redirect("index");
            exit;
        }
        $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";
    }

    public function enquiry($page=1,$sortfield='',$order='') {
        if((!$this->_session->get('user_id'))) {
            $this->redirect("index");
            exit;
        }
        $userId =   $this->_session->get('user_id');
        if($page==0 || $page == "") {
            $page 			= $this->get('page');
            if(!is_numeric($page))
                $page = 1;
            if(isset($page) && $page <=0 ) {
                $this->redirect('index/enquiry');
            }
        }
        $this->view->order      = $order;
        $this->view->sortfield      = $sortfield;

        if($sortfield!='') {
            $ordertype                  = $sortfield.' '. $order;
        }
        else {
            $ordertype                  = "";
        }


        $cntComments                =  $this->_common->getDataCount("EQ.nId","enquiry AS EQ","product AS P ON P.nBusId=EQ.nProductId","INNER JOIN","P.nUserId='".$userId."'","");
        $this->view->pageCount      =  ceil($cntComments / PAGE_LIST_COUNT);
        $this->view->pageMaxCount   =   PAGE_LIST_COUNT;
        $this->view->resComments    =  $this->_common->getDatas("EQ.*,EQ.vTitle AS Title,EQ.vEmail AS Email,EQ.vPostedBy AS Username","enquiry AS EQ","product AS P ON P.nBusId=EQ.nProductId","INNER JOIN","P.nUserId='".$userId."'","","$ordertype","","$page");
        $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');
            if($txtSearch != '')
                $condition          = "P.nUserId = '$userId' AND Title LIKE '%".$this->_common->escapeString($txtSearch)."%' OR vDescription LIKE '%".$this->_common->escapeString($txtSearch)."%' OR dPostDate LIKE '%".$this->_common->escapeString($txtSearch)."%' OR vEmail LIKE '%".$this->_common->escapeString($txtSearch)."%' OR vPostedBy LIKE '%".$this->_common->escapeString($txtSearch)."%' OR EQ.nStatus LIKE '%".$this->_common->escapeString($txtSearch)."%'   ";
            else
                $condition          = "P.nUserId = '$userId'";
            $cntComments                =  $this->_common->getDataCount("EQ.nId","enquiry AS EQ","product AS P ON P.nBusId=EQ.nProductId","INNER JOIN","$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($field,$table,"","","$condition","",$ordertype,"",$page);
            $this->view->resComments    =  $this->_common->getDatas("EQ.*,EQ.vTitle AS Title,EQ.vEmail AS Email,EQ.vPostedBy AS Username","enquiry AS EQ","product AS P ON P.nBusId=EQ.nProductId","INNER JOIN","$condition","","$ordertype","","$page");
        }
    }

    public function sendreply() {
        $this->view->disableLayout();
        $id =    $this->get('id');
        $resComments    =    $this->_common->getDatas("PC.*","enquiry AS PC","product AS P ON P.nBusId=PC.nProductId","INNER JOIN","nId='".$id."'","","","","1");
        $this->view->resMessage    =   $resComments[0];
    }

    public function sendmessage() {
        if((!$this->_session->get('user_id'))) {
            $this->redirect("index");
            exit;
        }
        $this->view->disableLayout();
        $this->view->disableView();
        $this->view->id    =   $id     = $this->post('id');
        $this->view->subject  = $subject  = $this->post('subject');
        $message = "<p><img src=".BASE_URL."/public/images/default/mainlogo_disp.png /></p>";
        $this->view->status  = $message  .= $this->post('message');
        $toName     = $this->post('to');
        $toemail    = $this->post('toemail');
        if($id!="" && $subject!="") {
            $account = array();
            //$account['from']='rajath.k@armiasystems.com';
            $settings = $this->_common->selectResult('settings','*');
              foreach($settings as $field ){
              $setting[$field->settingfield]= $field->value;
                                           }
              $this->siteSettings = $setting;
              
            $account['from']=$this->siteSettings['adminEmail'];
            $account['from']= $this->siteSettings['adminEmail'];
            $account['subject']=$subject;
       // $account['message']=$message;
  //    $account['message'].='Hi '.$toName."\n".$message;
            $account['message'].= str_replace("\n", "<br>", $message);
           // echo $message;exit;
            $account['to']=$toemail;

            $this->_libEmailSend->email_senderNow($account);
            $arrUpdate  =   array("nStatus"=>1);
            $this->_common->updateFields("enquiry",$arrUpdate,"nId='".$id."'");
            echo "1";
            exit;
        }
        else {
            echo "2";
            exit;
        }
        echo "3";
    }
    public function deleteenquiry() {
        $userId = $this->_session->get('user_id');
        $enqId  = $this->post('id');
        $query= "DELETE FROM `".MYSQL_TABLE_PREFIX."enquiry` WHERE nId='$enqId' AND nProductId IN (SELECT nBusId FROM `".MYSQL_TABLE_PREFIX."product` WHERE nUserId='$userId')";
        $this->_common->deleteQuery($query);
//        $this->deleteRecord('',)
        echo "1";
        exit;

    }

    public function listing($page=1) {
        $userId =   $this->_session->get('user_id');
        if($page==0 || $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).',alias';
        $order  = " ORDER BY dPostDate DESC";
        $listArray   = $this->_common->getTopList($table,$field,$order,$where);
        if(sizeof($listArray)>0) {
            $this->view->listFields = explode(',',$field);
            $this->view->listArray  = $listArray;
            $where  = "nStatus = '1' AND nUserId = '$userId'";
            $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 viewlisting($productId='',$page='',$flag=0) {
//
//        if($flag==1)
//            $this->view->updateMessage ='Successfuly updated !';
//        else if($flag==2)
//            $this->view->updateMessage ='Payment is successful !';
//
////        if(isset())
//        LibSession::set('temp_listing_id',$productId);
//        $this->view->produId = $productId;
//        $table  = 'product';
//        $field  = '*';
//        $order  = "";
//        $where  = "nBusId = '$productId'";
//        $listFieldString='';
//        $listFields   = $this->_common->getListFields($table,$field,$order,$where);
//        $this->view->listData   = $listFields;
//
//
//
//        /* Get the product rate */
//
//        $table  = 'productrating';
//        $field  = 'round( COALESCE(SUM( `nRate` ) / COUNT( `nId` ),0) ) AS RATE';
//        $order  = "";
//        $where  = "nProductId = '$productId'";
//        $this->view->productRating = $this->_common->selectRow($table,$field,$where);
//
//        /* To show the comments */
////        $page 			= $this->get('page');
//        if(!is_numeric($page))
//            $page = 1;
//        if(isset($page) && $page <=0 ) {
//            $this->redirect('index/pagelisting');
//        }
//        $userId                     =   LibSession::get('user_id');
//        $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;
//
//        $zipcode = $this->view->listData[0]->Zipcode;
//        $this->view->isValidZip = (integer)$this->_common->checkExists('tbl_zipcode',"*","zipcode='$zipcode'");
//
//        if(LibSession::get('tmp_rate_flag_'.$productId,'business')) {
//            $this->view->tmp_rate_flag   = 'set';
//            $this->view->tmp_rate_count = LibSession::get('tmp_rate_count_'.$productId,'business');
//        }
//
//
//
//
//
//    }
    
    public function viewlisting($alias='',$page='',$flag=0) {

        if($flag==1) {
            //$this->view->updateMessage ='Successfuly updated !';
            $this->view->updateMessage ='Listing has been made featured !';
        }
        else if($flag==2) {
            //$this->view->updateMessage ='Payment is successful !';
            $this->view->updateMessage ='Payment has been done successfully !';
        }

//        if(isset())
        
        
        $table  = 'product';
        $field  = '*';
        $order  = "";
        //$where  = "nBusId = '$productId'";
        $where  = "alias = '$alias'";
        $productId    =   $this->_common->selectRow($table,'nBusId',$where);
		$this->view->produId = $productId;
		$this->view->alias=$alias;
		$this->_session->set('temp_listing_id',$productId);
        $listFieldString='';
        $listFields   = $this->_common->getListFields($table,$field,$order,$where);
        $this->view->listData   = $listFields;
		//echopre($listFields



        /* Get the product rate */

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

        /* To show the comments */
//        $page 			= $this->get('page');
        if(!is_numeric($page))
            $page = 1;
        if(isset($page) && $page <=0 ) {
            $this->redirect('index/pagelisting');
        }
        $userId                     =   $this->_session->get('user_id');
        $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;

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

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





    }


    public function creditcard($listId='',$status='') {



        // User Information

        $this->userName = $this->_session->get('user_login');

        $this->userPass = $this->_session->get('user_pass');

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

        if($listId == ''){
            $listId = $this->_session->get('temp_listing_id');
        }
        else{
            $listId = $listId;
        }


        $this->Libauthorize_class  = new  LibAuthorize_class();

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

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

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

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

        $authorizeTestMode    =   $this->_common->selectRow("settings","value","settingfield='authorize_test_mode'");
        if($status == ''){
            $amount   =   $this->_common->selectRow("settings","value","settingfield='nFeatured_Amount'");
        }
        else{
            $join   =" INNER JOIN ".MYSQL_TABLE_PREFIX."plans AS plans ON plans.nPlanId = product.nPlanId";
            $where  =" WHERE  product.nBusId =".$listId;
            $row_listings    =   $this->_common->getAllData('plans.vPlanAmount,plans.vPlanDuration','product AS product',$join ,$where);
           //echopre1($row_listings);
            $amount = $row_listings[0]->vPlanAmount;
            $duration = $row_listings[0]->vPlanDuration;
           //$amount   =   $this->_common->selectRow("settings","value","settingfield='nFeatured_Amount'"); 
        }

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


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







        $authorizeInfo =array();

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

        $authorizeInfo['amount'] = $amount;

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

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





        $return =  $this->Libauthorize_class->submit_authorize_post($authorizeInfo);
        //echopre1($return);
        $details = $return[0];

        $transaction_id = $return[1];

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

        if($paymentsuccessful)
            $this->view->msg = 'Payment is Successfull';
        else
            $this->view->errorMsg = 'Payment  failed';


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

            $arrProfile =   array("nListId"=>$listId,
                    "vUserFirstName"=>$this->post('fname'),
                    "vUserLastName"=>$this->post('lname'),
                    "vAmount"=>$authorizeInfo['amount'],
                    "vProductName"=>$listName,
                    "vPaymentStatus"=>"C",
                    "vTransactionId"=>$transaction_id
            );
            if($status ==''){
                $arrProfile['vPaymentType']='F';
            }
            else{
                $arrProfile['vPaymentType']='L';
            }
            


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


            if($status ==''){
                $arrProfile         =   array("nFeatured"=>1, "nPaymentStatus "=>'P');
                $this->_common->updateFields("product",$arrProfile,"nBusId='".$listId."'");
            }
            else{
            $res=$this->_common->execute("SELECT ADDDATE(CURDATE(),INTERVAL $duration Month) AS Expiry_date");
            $row=$this->_common->fetchOne($res);
//                $res = mysqli_query("SELECT ADDDATE(CURDATE(),INTERVAL $duration Month) AS Expiry_date");
//                $row = mysqli_fetch_row($res);
               
                $arrProfile         =   array("nStatus 	"=>1,
                                        "nPaymentStatus "=>'P',
                                        "nPlanExpiryDate"=>$row['0']);
                //echopre1($arrProfile);
                $this->_common->updateFields("product",$arrProfile,"nBusId='".$listId."'");
            }

            $where  = "nBusId = '$listId'";
            $alias    =   $this->_common->selectRow('product','alias',$where);
            $this->redirect('index/viewlisting/'.$alias.'/1/2/');
            exit;



        }






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





    }

    public function logout() {

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

        $this->_session->destroy();
        session_start();
        $_SESSION['fbLogout'] = 1;
        header("Location:".ConfigUrl::base('default').'index');
    }


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

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

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


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

        echo 1;

    }

    public function renderRate($productId,$starNo) {
        $this->view->disableLayout();
        $this->view->disableView();

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

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

    }
    
    public function renew($listing_id) {

        $this->view->listId  = $listing_id;

        if( $this->view->listId == '') {
            $this->redirect('index/dashboard');
            exit;
        }


//        if(SITE_PAYMENT_MODE!='paid') {
//            $arrProfile         =   array("nFeatured"=>1);
//            //
//            $this->_common->updateFields("product",$arrProfile,"nBusId='".$this->view->listId."'");
//            $this->view->payMessage = 'Successfully updated';
//
//            $this->redirect('index/viewlisting/'.$this->view->listId.'/1/1/');
//            exit;
//        }


        $this->userId   = $this->_session->get('user_id');
        $authorizeEnable      =   $this->_common->selectRow("settings","value","settingfield='authorize_enable'");
        $paypalEnable      =   $this->_common->selectRow("settings","value","settingfield='enablepaypal'");

        $this->view->paypalEnabled =($paypalEnable=='Y')? true :false;
        $this->view->authorizeEnabled = ($authorizeEnable=='Y')? true : false;
        $this->view->message=($paypalEnable!='Y' && $authorizeEnable!='Y') ? 'No Payment Option Available. Please Contact Administrator.':'';

        $listFields  = array();
        $table  = 'users';
        $field  = 'vFirstName,vLastName,vAddress1,vCity,vState,vCountry,vEmail,nZip';
        $where  = " nUserId ='".$this->userId."' ";
        $order  = " LIMIT 0,1";
        $resBusiness   =   $this->_common->selectRecord($table,$field,$order,$where);


        if($this->post('process')) {
            $this->view->fname =$this->post('fname');
            $this->view->lname =$this->post('lname');
            $this->view->email =$this->post('email');
            $this->view->address =$this->post('add1');
            $this->view->city =$this->post('city');
            $this->view->state =$this->post('state');
            $this->view->country =$this->post('country');
            $this->view->zip =$this->post('zip');
        }

        if($resBusiness) {
            $this->view->fname =$resBusiness->vFirstName;
            $this->view->lname =$resBusiness->vLastName;
            $this->view->email =$resBusiness->vEmail;
            $this->view->address =$resBusiness->vAddress1;
            $this->view->city =$resBusiness->vCity;
            $this->view->state =$resBusiness->vState;
            $this->view->country =$resBusiness->vCountry;
            $this->view->zip =$resBusiness->nZip;

        }

    }
    
    public function paymenthistory($page=1,$sortfield='',$orders='',$txtSearch='') {
        $this->userId = $this->_session->get('user_id');
        $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');
            }
        }
        
        if ($sortfield != '') {
            $ordertype = $sortfield . ' ' . $orders;
        } else {
            $ordertype = "";
        }
        $cntComments = (integer) $this->_common->checkExists('payments', "nPaymentId", "vPaymentStatus='C'");
        //$cntComments = (integer) $this->_common->getDataCount('nPaymentId','payments AS payments','product AS product ON product.nBusId=payments.nListId LEFT JOIN '.MYSQL_TABLE_PREFIX.'users AS users ON users.nUserId=product.nUserId','left join',"payments.vPaymentStatus='C' AND ", $groupby = '');
        $this->view->pageCount = ceil($cntComments / PAGE_LIST_COUNT);
        $listFields = $this->_common->getDatas($field, $table, "", "", "$where", $ordertype, "", "", $page);
        $this->view->page = ($page) > 0 ? $page : 1;
        $this->view->pageMaxCount = PAGE_LIST_COUNT;

        $this->view->listData = $listFields;
        if ($this->post('btnSearch') OR ($txtSearch != '')) {
            $txtSearch = ($this->post('txtSearch')) ? trim($this->post('txtSearch')) : $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) . "%' ";
            $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;
        }
    }



}
?>