<?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: Meena Susan Joseph <meena.s@armiasystems.com>                     |
// +----------------------------------------------------------------------+
// | Copyrights Armia Systems ? 2010                                      |
// | All rights reserved                                                  |
// +----------------------------------------------------------------------|



class ControllerAds extends BaseController
{
	/*
		construction function. we can initialize the models here
	*/
    public $userName   =   '';
    public $userPass   =   '';
    public $userId     =   0;
    public $categoryTitle;
    public $siteSettings;

    public function init()
    {
        parent::init();
		if(LibSession::get('user_id')=="")
                   {
                       $this->switchmodule(ConfigUrl::base('default'));
                       exit;
                   }
		$this->_common		= new ModelCommon;
                $this->_postads = new ModelPostads;
//              $this->_indexmodel      = new ModelIndex;
                                    
        // get Site Settings ***************************************
        $settings = $this->_common->selectResult('settings','*');

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

        $this->view->setting = $setting;
        $this->siteSettings = $setting;
        // get Site Settings end ***************************************
        
        /*------------- Categories End -------------------*/
        $categroy_flag = true;
        $categories = $this->_common->getAllData('nCategoryId, vCategoryDesc', 'category','','WHERE nParentId = 0','','ASC','vRoute');
        
        if($categories) {
            foreach($categories as $cat_val) {
                $products = $this->_common->selectResult('product','nBusId, nCatid, Title', '', "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->categoryTitle = $category_title;
        $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", "", "WHERE nStatus='1' AND vFldSearch='1'");
        // Search Fields End ******************************************
        $fieldList = array();

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

        } //End Init
    
    
    /*
        function to load the index template
    */
    public function index($page,$sortfield='',$order='')
    {
        if((!LibSession::get('user_id'))){
            $this->redirect("index");
            exit;
        } // End If
       
        //exit($txtSearch.'=>');
        $userId = LibSession::get('user_id');       
       
        if($page==0 || $page=="")
        {           
            LibSession::set('searchItem','');
            $page = $this->get('page');
            if(!is_numeric($page))
              $page = 1;

            if(isset($page) && $page <=0 ){
              $this->redirect('ads/index');
            }
        }
        
        
        if((!LibSession::get('searchItem'))){
            $txtSearch = '';
        } else {
            $txtSearch = LibSession::get('searchItem');
        }// End If
        
       
        $this->view->order      = $order;
        $this->view->sortfield      = $sortfield;
        $this->view->txtSearch      = $txtSearch;
        
        /*****************/
        
        $listFields  = array();
        $table  = 'productdesc';
        $field  = 'vFldname';
        $orders  = " ORDER BY id ASC";
        $where  = "nStatus = '1'";
        $listFieldString = '';
        $listFields   = $this->_common->getListFields($table,$field,$orders,$where);
        if($sortfield!=''){
                if($sortfield=='nStatus') {
                    $newOrder = ($order=='ASC') ? 'DESC' :'ASC';
                    $ordertype                  = $sortfield.' '. $newOrder;
                } else {
                    $ordertype                  = $sortfield.' '. $order;

                }
            }
            else{
                $ordertype                  = "";
            }
       
           
        if(sizeof($listFields)>0)
        {
            //$listFieldString .= 'nBusId,alias, DATE_FORMAT(dPostDate,"%m/%d/%Y") AS dPostDate, nStatus,DATE_FORMAT(nPlanExpiryDate,"%m/%d/%Y") AS nPlanExpiryDate';
            $listFieldString .= 'nBusId,alias, dPostDate, nStatus, nPlanExpiryDate';

            foreach ($listFields as $lRecord)
            {                           
                $listFieldString.=', '.$lRecord->vFldname;
            }            
        }    
        
        $listArray   = array();
        $table  = 'product AS product';
        $where  = '';
               
        $field = $listFieldString;        
        $order  = " ORDER BY dPostDate DESC";       
        $listArray   = $this->_common->getTopList($table,$field,$order,$where);
        
        if(sizeof($listArray)>0)
        {
            if($txtSearch != '')
                    $condition          = "nUserId = '$userId'  AND (Title LIKE '%".$this->_common->escapeString($txtSearch)."%' OR dPostDate LIKE '%".$this->_common->escapeString($txtSearch)."%' OR nStatus LIKE '%".$this->_common->escapeString($txtSearch)."%' )  ";
                else
                    $condition = "nUserId = '$userId'";
            $this->view->listFields = explode(',',$field);
            $this->view->listArray  = $listArray;
            $cntComments                =  (integer)$this->_common->checkExists('product',"nBusId",$condition);
            $this->view->pageCount      =  ceil($cntComments / PAGE_LIST_COUNT);
            $this->view->pageMaxCount   =   PAGE_LIST_COUNT;
            
            //($selFields = '*',$table1='',$table2='',$join='',$where='', $groupby = '',$orderby='',$limit='',$pagination='')
            $join  ="plans AS plans ON plans.nPlanId =product.nPlanId"; 
            $this->view->resProducts    =  $this->_common->getDatas($field.',plans.*',$table,$join,"left join",$condition,"",$ordertype,"",$page);
            $this->view->page           =  ($page) >  0 ? $page : 1;
        }
        $this->view->message='';
         if($this->post('btnSearch') OR $this->get('txtSearch')) {
           //echo "dsfdsf";
                $txtSearch  =   ($this->post('txtSearch'))?trim($this->post('txtSearch')):$this->get('txtSearch');
                LibSession::set('searchItem',$txtSearch);
                if($txtSearch != '')
                    $condition          = "nUserId = '$userId'  AND (Title LIKE '%".$this->_common->escapeString($txtSearch)."%' OR dPostDate LIKE '%".$this->_common->escapeString($txtSearch)."%' OR nStatus LIKE '%".$this->_common->escapeString($txtSearch)."%' )  ";
                else
                    $condition = "nUserId = '$userId'";
                
                $cntComments                =  (integer)$this->_common->checkExists('product',"nBusId",$condition);
                //echo "<pre>";print_r($cntComments);
                $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);
          }

          //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;
                $order           =   ($this->post('txtOrder'))?trim($this->post('txtOrder')):$order;
                LibSession::set('searchItem',$txtSearch);
                if($sortfield!=''){
                     if($sortfield=='nStatus') {
                        $newOrder = ($order=='ASC') ? 'DESC' :'ASC';
                        $ordertype                  = ' ORDER BY '.$sortfield.' '. $newOrder;
                     } else{
                        $ordertype                  = ' ORDER BY '.$sortfield.' '. $order;
                     }
                } else {
                    $ordertype                  = "";
                }
               if($txtSearch!=''){
                     $condition          = "WHERE nUserId = '$userId' AND Title LIKE '%".$this->_common->escapeString($txtSearch)."%' OR dPostDate LIKE '%".$this->_common->escapeString($txtSearch)."%' OR nStatus LIKE '%".$this->_common->escapeString($txtSearch)."%' ";
               }
               else{
                   $condition       = "WHERE nUserId = '$userId'";
               }
               //echo $condition."---";               
               $resExportProducts     = $this->_common->selectAllResult('product','*',$ordertype,$condition);

              // echo"<pre>"; print_r($resExportProducts);

                $xldata	=	'<table width="100%"  border="1" cellspacing="0" cellpadding="0">
                          <tr>
                            <td class="support2" colspan="4">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="40%" class="dollar"><strong>Title</strong> </td>
                                <td width="35%" class="dollar"><strong>Posted date</strong> </td>
                                <td width="20%" 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="60%">'.stripslashes($row->Title).'</td>
                                            <td width="35%">'.stripslashes(date("m-d-Y",strtotime($row->dPostDate))).'</td>
                                            <td width="35%">'.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;

          }
        
    } // End Function

    public function drop(){
     $this->view->disableLayout();
     $this->view->disableView();
     $status = 0;
     if(isset($_POST['id'])){
        $id=$_POST['id'];
        $this->_common->deleteRecord("product","nBusId='".$id."'");     
        $status = 1;
     } // Isset ID
     echo $status;
     exit;
    } // End Function

    public function edit($adID=''){
        
        $activeFields = $this->_common->selectResult("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'];
        
       
        $success_message = $error= '';
            
            if($this->isPost())
            {              
                $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->_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;
                                } //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'];
                
                
                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');
            }
            
        $fieldValuesArr = $this->_common->selectResult("product","*","","WHERE nBusId='".$postID."'");
        //echo "<pre>";print_r($fieldValuesArr);
        //$category       =   $this->_common->selectResult("category","nParentId","","WHERE 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;
            }
        }
        //$category_title
       // echo "<pre>";print_r($subCategoryList);exit;
       // echo $this->view->select('subcategory', $category_title, '', 'select_drpbx','','subcategory',' size="4"');
        //--------------------------------
        
        
        $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 downloaddoc($file){
        $fileParts = pathinfo($file);
        $fileParts['extension'];
        $filePath = ConfigUrl::uploaddocroot().$file;
        header('Content-disposition: attachment; filename='.$file);
        header('Content-type: application/'.$fileParts['extension']);
        readfile($filePath);
        exit();
    } // End Function

    public function postads($data='') {

        //Index
        //$this->view->setLayout('common');
        // if the user session exist , redirect to users page
        //echo '<pre>'; print_r($data); echo '</pre>';
        $activeFields = $this->_common->selectAllResult("productdesc","vFldname, vFlddesc, vInType, vlink, nMandatory, nStatus","","WHERE nStatus='1'");

        $staticFieldArr = array('Title', 'Description', 'Image', 'Video', 'VideoURL', 'Zipcode', 'Address');

        $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();
            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');
                                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;
                        } //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
                $success_message = "<font color='green'>Posting Saved Successfully</font>";
                // Check For User
                $postedEmail = (!isset($_SESSION['user']['userID']) && $_SESSION['user']['userID']=='') ? $_POST['email'] : '';
                
                $chkdUser = $this->_postads->checkUser($postedEmail, $_SESSION['user']['userID'],$this->siteSettings['userApproval']);
echo"hello12";exit;
                //Posting User
                $dataArr['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 = "<font color='green'>Posting Saved Successfully!</font>";
                }
              else if($this->siteSettings['userApproval']=='admin')
                {
                    $success_message = "<font color='green'>Posting has been saved waiting for the admin to approve!</font>";
                }
              else  if($this->siteSettings['userApproval']=='email')
                {
                    $success_message = "<font color='green'>Posting has been saved and is in pending status. Please activate your acoount through the activation e-mail. Thank You!</font>";
                }




                } // End Auto Registration

                //POST ADS
                $postAds = $this->_common->addFields("product",$dataArr);

            } // 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
     public function loadSubCategories(){

        $catId = $_POST['categoryId'];
        //$subCategories = $this->_common->selectResult("category","*","nParentId ='$catId'");
        $categories = $this->_common->getAllData('nCategoryId, vCategoryDesc', 'category','',"WHERE nParentId = '$catId'",'','ASC','vRoute');
      
        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;
    }

}
?>