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

class ControllerPostads extends BaseController {
    /*
	Initializing the models
    */
    public $categoryTitle;
    public $siteSettings;

    public function init() {

        parent::init();
        $this->_common	= new ModelCommon;
        $this->_category = new ModelCategory;
        $this->_postads = new ModelPostads;

        // 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 ***************************************
        // Social Plugins **********************************************
        $_SESSION['facebookKey'] = array('enableFb' =>$setting['enableFb'], 'facebookAppId' => $setting['facebookAppId'], 'facebookSecret' => $setting['facebookSecret']);
        $_SESSION['twitterKey'] = array('enableTwitter' => $setting['enableTwitter'], 'twitterConsumerKey' => $setting['twitterConsumerKey'], 'twitterConsumerSecret' => $setting['twitterConsumerSecret']);
        // Social Plugins End ******************************************
        /*------------- Categories End -------------------*/
        $categroy_flag = true;
        $categories = $this->_common->getAllData('nCategoryId, vCategoryDesc', 'category','','WHERE nParentId = 0','','ASC','vRoute');
        if($categories) {
            foreach($categories as $cat_val) {
                $products = $this->_common->selectResult('product','nBusId, nCatid, Title', "nCatid = {$cat_val->nCategoryId} 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 -------------------*/
        //-----------------------Twitter login-----------------
     /* TWITTER COMMENTED FOR PHP 5.4 FIX
      *   include 'apps/twitter-oauth/lib/EpiCurl.php';
        include 'apps/twitter-oauth/lib/EpiOAuth.php';
        include 'apps/twitter-oauth/lib/EpiTwitter.php';
        $consumer_key = $_SESSION['twitterKey']['twitterConsumerKey'];
        $consumer_secret = $_SESSION['twitterKey']['twitterConsumerSecret'];
        $twitterObj = new EpiTwitter($consumer_key, $consumer_secret);

        $this->view->url = $twitterObj->getAuthorizationUrl();
      * TWITTER COMMENTED FOR PHP 5.4 FIX
      */
        //-----------------------Twitter login-----------------

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

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

    }

    public function index($data='') {

        //unset($_SESSION['errorLogin']);
        $_SESSION['nUserid'] ='';
        $_SESSION['busid']   ='';
        $_SESSION['planid']  ='';
        $this->view->planfields = $this->_common->selectResult("plans","nPlanId,vPlanAmount, vPlanName,vPlanDuration","vPlanStatus='E'");
        $this->view->settings = $this->_common->selectResult("settings","settingfield,value","settingfield='operationMode'");

        $_SESSION['planid']=$_POST['planid'];

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

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

        $success_message = $error= '';

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

        $recaptchaHTML = null;
        $recaptchaError = null;

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


        if($this->isPost()) {
            //print_r($_POST);exit;
            $dataArr = array();
            $userPlanarr=array();
            
            if (isset($_POST["postadd"])) {

                if (PRODUCT_CAPTCHA_MODE == 'Y') {
                    // echo "entered if";
                    $resp = recaptcha_check_answer ($privatekey,
                            $_SERVER["REMOTE_ADDR"],
                            $_POST["recaptcha_challenge_field"],
                            $_POST["recaptcha_response_field"]);
                    $flag   =   $resp->is_valid;
                }
                else {//echo "entered else";
                    $flag = 1;
                }
//echo $flag;exit;
                if ($flag == 1  || PRODUCT_CAPTCHA_MODE == 'N' ) {

                    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','flv','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','flv','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);
                                                // --------------------------------------------------------------------------


                                                $imageName151x151 = '_302x302.'.$imageUpParts['extension'];
                                                $rzimage=preg_replace("/\.([a-zA-Z]{3,4})$/", $imageName151x151, $imageName);

                                                $dataArr['Image']=$rzimage;

                                            } else {
                                                $error .= '<br>'.'* '.'Error in uploading the file for '.$activeFld->vFlddesc.', please try again !!';
                                            }
                                        }
                                        break;
                                    case 'video':
                                        if(is_uploaded_file($_FILES['Video']['tmp_name'])) {
                                            $videoUpParts = pathinfo($_FILES['Video']['name']);
                                            $videoName = 'video_'.date('HisdmY').'.'.$videoUpParts['extension'];
                                            $videoUpOriginal = ConfigUrl::uploadvideoroot().$videoName;
                                            if(move_uploaded_file($_FILES['Video']['tmp_name'], $videoUpOriginal)) {
                                                @chmod($videoUpOriginal,0777);
                                                $video_thumb_image = 'video_'.date('HisdmY').'.jpg';
                                                $flv_filename = 'video_'.date('HisdmY').'.flv';
                                                /* video convert function to convert the uploaded videos to flash videos
                                                parameters are videoname,source directory and destination directory */
                                                
                                                //checking uploaded file flv or not
                                                switch($videoUpParts['extension']) {
                                                    case "flv":
                                                        $ffmpeg_value = 0;
                                                        //create thumb image
                                                        $destination = ConfigUrl::uploadvideoroot().$flv_filename;
                                                        $videoThumbPath = ConfigUrl::uploadvideoroot().$video_thumb_image;
                                                        exec("ffmpeg -i $destination -an -ss 00:00:03 -an -r 1 -vframes 1 -y -s 80x54 -f mjpeg $videoThumbPath",$return_array,$value_return);
                                                        break;
                                                    default:
                                                        
                                                        $ffmpeg_value = $this->_postads->convertVideo($videoName,ConfigUrl::uploadvideoroot(),ConfigUrl::uploadvideoroot());
                                                        break;
                                                }//end switch
                                               
                                                if($ffmpeg_value == 0) {
                                                    // Video uploaded successfully
                                                    $dataArr['Video']=$flv_filename;                                                   
                                                }//end if
                                                else {
                                                    $error .= '<br>'.'* '.'Video Conversion Failed for '.$activeFld->vFlddesc.'!!';
                                                }//end else


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

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

                            } // End If

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

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

                        } // End Foreach

                    } // End Error // Validation Errors

                    //Post Status -- active
                    if($this->siteSettings['userApproval']!='automatic')
                            $dataArr['nStatus'] = 0;
                            else
                            $dataArr['nStatus'] = 1;   
                            
                            
                            
                           // print_r($dataArr); exit;
                            
                    //Category ID
                    $dataArr['nParentCatId'] = $_POST['category'];
					 $dataArr['nCatid'] = $_POST['subcategory'];
					$categories = $this->_common->getAllData('nCategoryId, vCategoryDesc', 'category','',"WHERE nParentId = '$dataArr[nParentCatId]'",'','ASC','vRoute');
						if(sizeof($categories)>0 AND $dataArr['nCatid']=="") {
							$error .='<br>'.'* '.'Select a subcategory ';
						}
                   
                    //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']);

                        //Posting User
                        $dataArr['nUserId']  = $chkdUser['user']->nUserId;
                        $_SESSION['nUserid'] = $chkdUser['user']->nUserId;
                        $_SESSION['autoregister'] = $chkdUser['autoregister'];
                        //echo "<pre>";print_r($_SESSION);echo"</pre>";exit;

                        // 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) {
                            //Post Status -- pending for approval
                            
                            if($this->siteSettings['userApproval']!='automatic')
                            $dataArr['nStatus'] = 0;
                            else
                            $dataArr['nStatus'] = 1;    
                            if($this->view->settings[0]->value=="free") {
                            $subject = SITE_NAME.'Thank You For Registering With Us!';
                            $message = "<p><img src=".BASE_URL."/public/images/default/mainlogo_disp.png /></p>";
                            $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);
                            //mail('smitha.m@armiasystems.com','Test mail ', 'test mail body');

                            //Admin Notification
                            $messageAdmin = "<p><img src=".BASE_URL."/public/images/default/mainlogo_disp.png /></p>";
                            $messageAdmin .= $chkdUser['mailcontentadmin'];
                            //echo $messageAdmin;exit;
                            $subject_admin = 'New User Registration';
                            $adminNotif = array();
                            $adminNotif['from']=$this->siteSettings['adminEmail'];
                            $adminNotif['subject']=$subject_admin;
                            $adminNotif['message']=$messageAdmin;
                            $adminNotif['to']=$this->siteSettings['adminEmail'];
                            LibEmailsend::email_senderNow($adminNotif);
                            
                            /* if($this->siteSettings['userApproval']=='automatic')
                {
                    $success_message = 'Posting Saved Successfully!';
                }
              if($this->siteSettings['userApproval']=='admin')
                {*/
                            $success_message = 'Posting has been saved and is in pending status. Please activate your account through the activation e-mail. Thank You!';
                            /*  }
              else  if($this->siteSettings['userApproval']=='email')
                {
                    $success_message = 'Posting has been saved and is in pending status. Please activate your acoount through the activation e-mail. Thank You!';
                }*/


                            }

                        } // End Auto Registration
                        if($this->view->settings[0]->value=="free") {
                            //Admin Notification for new add
                            $msgAdmin = "<p><img src=".BASE_URL."/public/images/default/mainlogo_disp.png /></p>";
                            //$messageAdmin .= $chkdUser['mailcontentadmin'];
                            $msgAdmin .= 'Dear Administrator,<br><br>
                            New Ad has been posted in {SITE_NAME} and is waiting for your approval<br>
                            {SITE_NAME} | {SITE_URL}';
                            $msgBodyAdmin = str_replace("{SITE_NAME}", SITE_NAME, $msgAdmin); // Replace the Site Name
                            $msgBodyAdmin = str_replace("{SITE_URL}", ConfigUrl::base('default').'admin', $msgBodyAdmin); // Replace the Site Url
                            //$msgBodyAdmin = str_replace("{USER_EMAIL}", $email, $msgBodyAdmin); // Replace the User Email
                            
                            //echo $messageAdmin;exit;
                            $subject_admin = 'New Ad Posted';
                            $adminNotif = array();
                            $adminNotif['from']=$this->siteSettings['adminEmail'];
                            $adminNotif['subject']=$subject_admin;
                            $adminNotif['message']=$msgBodyAdmin;
                            $adminNotif['to']=$this->siteSettings['adminEmail'];
                            LibEmailsend::email_senderNow($adminNotif);
                        }
                        //POST ADS
                        $dataArr['nPlanId']=$_SESSION['planid'];

                        $planId = $_POST['planid'];
                        $selectedPlan = $this->_common->selectRecord('plans','nPlanId,vPlantype,vPlanDuration',"nPlanId='$planId'");
                        $planType = $selectedPlan->vPlantype;
                        if($planType == 'M') {
                            $duration = $selectedPlan->vPlanDuration;
                            $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);
                            $dataArr['nPlanExpiryDate'] = $row['0'];
                        }
                        $dataArr['nPaymentStatus']='N';
                        
                        $product_alias  =   Globalutils::checkAndValidateEntityAlias(MYSQL_TABLE_PREFIX.'product', $title,'nBusId' ,$id = "", $alias_column="alias");
                        $dataArr['alias']=$product_alias;
                        //echopre($dataArr);
                        $postAds = $this->_common->addFields("product",$dataArr);





//                        $userPlanarr['vStatus']='N';
//                        $userPlanarr['nUserId']= $chkdUser['user']->nUserId;
//                        $userPlanarr['nPlanId']= $_SESSION['planid'];
//                        $this->view->busid = $this->_common->selectRow("product","nBusId","nUserId =".$chkdUser['user']->nUserId."");
//                        $userPlanarr['nProductId']=$this->view->busid;
//                        $userPlanarr['dDate'] = date('d-m-Y');
//                        $this->_common->addFields("userplans",$userPlanarr);
                        /*if($this->siteSettings['userApproval']=='automatic')
                {
                    $success_message = 'Posting Saved Successfully!';
                }
              else if($this->siteSettings['userApproval']=='admin')
                {*/
                     if($this->siteSettings['userApproval']=='email' && $_SESSION['autoregister']=='1'){   
                        $success_message = 'Posting has been saved waiting for the admin approval. Please activate your account through the activation e-mail. Thank You!';
                        unset($_POST);

                     }
                     elseif($this->siteSettings['userApproval']=='admin' && $_SESSION['autoregister']=='1'){ 
                        $success_message = 'Posting has been saved, waiting for the admin  approval';
                        unset($_POST);
                     }elseif($this->siteSettings['userApproval']=='automatic' && $_SESSION['autoregister']=='1'){ 
                         $success_message = 'Posting has been saved, You can Sign in to your account,Please check the mail for login credentials';
                         unset($_POST);
                     }elseif($this->siteSettings['userApproval']=='email' && $_SESSION['autoregister']!='1'){   
                        $success_message = 'Posting has been saved, waiting for the admin approval.Thank You';
                        unset($_POST);

                     }elseif($this->siteSettings['userApproval']=='admin' && $_SESSION['autoregister']!='1'){ 
                        $success_message = 'Posting has been saved, waiting for the admin  approval';
                        unset($_POST);
                     }elseif($this->siteSettings['userApproval']=='automatic' && $_SESSION['autoregister']!='1'){ 
                         $success_message = 'Congratulations! Your Posting has been submited';
                         unset($_POST);
                     }
                        /*}
              else  if($this->siteSettings['userApproval']=='email')
                {
                    $success_message = 'Posting has been saved and is in pending status. Please activate your acoount through the activation e-mail. Thank You!';
                }*/


                        if($this->view->settings[0]->value=="paid") {
                            $this->redirect('paypal/paymentdetails/'.$_SESSION['nUserid']);
                        }
                    } // Error in Uploading any of Files

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

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


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

    } // End Function

    public function sortcategory() {
        $this->view->disableLayout();
        $this->view->disableView();
        $content = '';
        $sortText = $_GET['tx'];
        if(isset($_GET['tx'])) {

            $newCategory = array();
            $sortedCategory = array();

            if(!empty($this->categoryTitle)) {
                $categories=$this->categoryTitle;
                asort($categories);
                $sortedCategory = $this->_category->getSorted($sortText, $this->categoryTitle);
                $newCategory = (empty($sortedCategory)) ? $categories : $sortedCategory;
            }// End If

            $content .= BaseView::select('category', $newCategory, '', 'select_drpbx','','category');


        } // End isset

        echo $content;

    } // 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','vCategoryDesc');
        if($categories) {
            foreach($categories as $cat_val) {
//                $products = $this->_common->selectResult('product','nBusId, nCatid, Title', "nCatid = {$cat_val->nCategoryId} LIMIT 0, 10");
//                $category[$cat_val->nCategoryId] = array();
//                if($products) {
//                    foreach($products as $prd_val) {
//                        $category[$cat_val->nCategoryId][$prd_val->nBusId] = $prd_val->Title;
//                    }
//                }
//                unset($products);

                $category_title[$cat_val->nCategoryId] = $cat_val->vCategoryDesc;
            }
        }
        //echo "<pre>";print_r($category_title);exit;
        echo $this->view->select('subcategory', $category_title, $_POST['subcategory'], 'select_drpbx','','subcategory',' size="4"');
        exit;
    }

}
?>