<?php
/***************************************************************************
 *                                                                          *
 * Copyright (c) 2005 ISPG Technologies (I) Pvt Ltd. All rights reserved.   *
 *                                                                          *
 * This  is  commercial  software,  only  users  who have purchased a valid *
 * license  and  accept  to the terms of the  License Agreement can install *
 * and use this program.                                                    *
 *                                                                          *
 ****************************************************************************
 * PLEASE READ THE FULL TEXT  OF THE SOFTWARE  LICENSE   AGREEMENT  IN  THE *
 * "copyright.txt" FILE PROVIDED WITH THIS DISTRIBUTION PACKAGE.            *
 ****************************************************************************/ //
//$Id: BusinessController.php, v 1.0 2011/06/14 20:52:11
//
class BusinessController extends Controller {
    //INDEX ACTION
    public function indexAction() {
        $ObjBusiness     = new BusinessModel();
        $ObjBusinessType = new BusinessTypeModel();
        $ObjProduct      = new ProductModel();
        $ObjCountry      = new CountryModel();
        $languageIDs     = $this->ObjView->languageIDs;
        $sortByOption    = $this->getRequestValue("sortby");
        $sortByOrder     = $this->getRequestValue("orderby");
        $link            = 'business/index/';
        $statusprivilege = $this->ObjCommon->hasPrivilege('business/edit/');
        $this->ObjView->assign("statusprivilege", $statusprivilege);
        $deleteprivilege = $this->ObjCommon->hasPrivilege('business/destroy/');
        $this->ObjView->assign("deleteprivilege", $deleteprivilege);
        $locprivilege = $this->ObjCommon->hasPrivilege('business/location/');
        $this->ObjView->assign("locprivilege", $locprivilege);
        $userprivilege = $this->ObjCommon->hasPrivilege('business/user/');
        $this->ObjView->assign("showprivilege", $this->ObjCommon->hasPrivilege('business/show/'));
        $this->ObjView->assign("userprivilege", $userprivilege);
        $productURL = '';
        $order      = '';
        if (isset($_POST['changeStatus'])) {
            
            for ($i = 0; $i < count($_REQUEST['checkbusinessIDs']); $i++) {
                $businessID = $_REQUEST['checkbusinessIDs'][$i];
                $prevStatus = $ObjBusiness->getBusinessStatus($businessID);
                
                if ($_POST['changeStatus'] == 'Deleted') {
                    $productExistsForBusiness = $ObjProduct->isProductsExistByBusiness($businessID);
                    if ($productExistsForBusiness > 0) {
                        $productExistsArray[] = $ObjBusiness->getBusinessDetails($businessID, $languageIDs);
                    } else {
                        $changestatus = $ObjBusiness->changeBusinessStatus($_POST, $businessID, $deleteprivilege);
                    }
                } else {
                    $changestatus = $ObjBusiness->changeBusinessStatus($_POST, $businessID, $deleteprivilege);
                }
                if($prevStatus!=$_POST['changeStatus']) {                   
                    $this->saveActivity($businessID);
                }                
            }
            //for loop ends  				
            if (isset($productExistsArray) && is_array($productExistsArray) && ($_POST['changeStatus'] == "Deleted")) {
                for ($i = 0; $i < count($productExistsArray); $i++) {
                    $businessName[] = $productExistsArray[$i]['businessName'];
                }
                $errCouldNotBusiness = $this->getLanguageValue("errCouldNotBusiness");
                $this->setMessage($errCouldNotBusiness . addslashes(implode(", ", $businessName)), "error");
            } else if ($changestatus && $_POST['changeStatus'] == "Deleted") {
                $this->setMessage("language.msgBusinessDelete", "success");
            } else if ($changestatus) {
                $this->setMessage("language.msgStatus", "success");
            }
            $this->setRedirect();
        }
        if (isset($_POST['submitSearch'])) {
            if ($_POST['businessTypeID'] != '') {
                $link .= 'type/' . $_POST['businessTypeID'] . '/';
            }
            if ($_POST['businessName'] != '') {
                $link .= 'name/' . $this->encodeUrlString($_POST['businessName']) . '/';
            }
            if (isset($_POST['countryID']) && $_POST['countryID'] > 0) {
                $link .= 'country/' . $_POST['countryID'] . '/';
            }
            if (isset($_POST['locStateID']) && $_POST['locStateID'] > 0 && $_POST['stateSelectedType'] == 'state') {
                $link .= 'state/' . $_POST['locStateID'] . '/';
            }
            if (isset($_POST['locProvince']) && $_POST['locProvince'] != '' && $_POST['stateSelectedType'] == 'province') {
                $link .= 'province/' . $this->encodeUrlString($_POST['locProvince']) . '/';
            }
            if (isset($_POST['city']) && $_POST['city'] != '') {
                $link .= 'city/' . $this->encodeUrlString($_POST['city']) . '/';
            }
            $this->setRedirect($link);
        }
        $businessTypeID   = $this->getRequestValue('type');
        //TO GET REQUEST VALUE
        $businessName     = $this->decodeUrlString($this->getRequestValue('name'));
        $countryID        = $this->getRequestValue('country');
        $stateID          = $this->getRequestValue('state');
        $city             = $this->getRequestValue('city');
        $province         = $this->decodeUrlString($this->getRequestValue('province'));
        $languageIDs      = $this->ObjView->languageIDs;
        $resBusinessTypes = $ObjBusinessType->getParentBusinessType($languageIDs);
        $this->ObjView->assign('resBusinessTypes', $resBusinessTypes);
        $this->ObjView->assign('businessTypeID', $businessTypeID);
        $this->ObjView->assign('businessName', $businessName);
        $this->ObjView->assign('locProvince', $province);
        $this->ObjView->assign('countryID', $countryID);
        $this->ObjView->assign('city', $city);
        $this->ObjView->assign('statehidValue', $stateID);
        $languageIDs['Current'] = $languageIDs['Content'];
        // export
        if (isset($_POST['exportBusiness'])) {
            $exportHeaders = array(
                'MerchantName' => $this->getLanguageValue("lblBusinessName"),
                'MerchantAddress1' => $this->getLanguageValue("lblMerchantAddress1"),
                'MerchantAddress2' => $this->getLanguageValue("lblMerchantAddress2"),
                'MerchantCity' => $this->getLanguageValue("lblBusinesscity"),
                'MerchantProvince' => $this->getLanguageValue("lblMerchantProvince"),
                'MerchantProfile' => $this->getLanguageValue("lblBusinessProfile"),
                'MerchantState' => $this->getLanguageValue("lblState"),
                'MerchantCountry' => $this->getLanguageValue("lblCountry"),
                'MerchantZipcode' => $this->getLanguageValue("lblZipcode"),
                'MerchantContactPerson' => $this->getLanguageValue("lblMerchantContactPersonFirstName"),
                'MerchantConatctLastName' => $this->getLanguageValue("lblLastName"),
                'MerchantDesignation' => $this->getLanguageValue("lblDesignation"),
                'MerchantPhone' => $this->getLanguageValue("lblPhone"),
                'MerchantFax' => $this->getLanguageValue("lblFax"),
                'MerchantEmailID' => $this->getLanguageValue("lblEmailID"),
                'MerchantWebsite' => $this->getLanguageValue("lblWebsite")
            );
            list($resBusinessexport, $header) = $ObjBusiness->listBusinessForExport($languageIDs, $businessTypeID, $businessName, $exportHeaders, $countryID, $stateID, $province, $city);
            foreach ($resBusinessexport as &$element) {
                $element['businessName']          = isset($element['businessName']) ? $this->decodeSplChar($element['businessName']) : '';
                $element['businessAddress1']      = isset($element['locAddress1']) ? $this->decodeSplChar($element['locAddress1']) : '';
                $element['businessAddress2']      = isset($element['locAddress2']) ? $this->decodeSplChar($element['locAddress2']) : '';
                $element['businessCity']          = isset($element['locCity']) ? $this->decodeSplChar($element['locCity']) : '';
                $element['businessStateProvince'] = isset($element['locProvince']) ? $this->decodeSplChar($element['locProvince']) : '';
            }
            $ObjCsv = new Csv();
            if (!empty($resBusinessexport)) {
                $dateTime = date('d_m_Y_H_i_s');
                $data     = $ObjCsv->output($dateTime . '.csv', $resBusinessexport, $header);
            } else {
                $this->setMessage("language.msgNoBusiness", 'error');
            }
        }
        // export
        // pagination settings
        list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
        //NO OF RECORDS PER PAGE
        $resBusiness = $ObjBusiness->listBusiness($languageIDs, $limitFrom, $limitTo, $status = '', $businessTypeID, $businessName, $sortByOption, $sortByOrder, $countryID, $stateID, $province, $city);
        //echo $triangle = mb_convert_encoding('&#x3060;', 'UTF-8', 'HTML-ENTITIES');
        //$this->ObjView->assign( "column", $column );
        $this->ObjView->assign("order", $order == 'ds' ? 'desc' : 'asc');
        $link .= (($businessName != "") ? "name/" . $this->encodeUrlString($businessName) . "/" : "");
        $link .= (($businessTypeID != "") ? "type/" . $businessTypeID . "/" : "");
        $link .= "list";
        if ($sortByOption == 'businessName' && $sortByOrder == "asc") {
            $sortBusiness = "desc";
        } else {
            $sortBusiness = "asc";
        }
        if ($sortByOption == 'productCount' && $sortByOrder == "asc") {
            $sortProductCount = "desc";
        } else {
            $sortProductCount = "asc";
        }
        $resPagesCount = $this->setPagesCount($key = 'page');
        //$this->ObjView->assign("page", $page);
        $this->ObjView->assign('sortByOrder', $sortByOrder);
        $this->ObjView->assign('sortByOption', $sortByOption);
        $this->ObjView->assign('sortBusiness', $sortBusiness);
        $this->ObjView->assign('sortProductCount', $sortProductCount);
        $this->ObjView->assign("link", $link);
        if (!$sortByOption) {
            $this->ObjView->assign('sortByOption', 'businessName');
            $this->ObjView->assign('sortByOrder', 'asc');
            $this->ObjView->assign('sortBusiness', 'desc');
        }
        $this->ObjView->assign('resListCountryOptions', $ObjCountry->listCountriesForOption($languageIDs));
        $this->ObjView->assign('resBusiness', $resBusiness);
        $this->ObjView->assign("listPrivilege", $this->ObjCommon->hasPrivilege('product/index/'));
        $this->ObjView->display('BusinessList.tpl');
    }
    //END OF FUNCTION
    //TO ADD NEW BUSINESS
    public function newAction() {
        $ObjBusinessType        = new BusinessTypeModel();
        $ObjCountry             = new CountryModel();
        $ObjBusiness            = new BusinessModel();
        $ObjContent             = new ContentModel();
        $ObjUser          	= new UserModel();
        $cityValue             = '';
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $currentLanguageID      = $languageIDs['Current'];
        $businessID             = $this->getRequestValue('id');
		$listRoles = '';
        if ($this->ObjForm->isValid('frmBusiness', 'submitBusiness')) {
            $_POST['languageIDs']     = $languageIDs;
            $logoImageWidth           = $this->getSettingValue('product_cart_settings', 'logo_image_width');
            $logoImageHeight          = $this->getSettingValue('product_cart_settings', 'logo_image_height');
            $_POST['logoImageWidth']  = $logoImageWidth;
            $_POST['logoImageHeight'] = $logoImageHeight;
            $_POST['businessKey']     = ($_POST['businessKey']) ? $_POST['businessKey'] : $this->ObjCommon->generateKey("business", $_POST['businessName'], 0, "unique");
            $_POST['profileStatus']='Complete';
            $businessPassword_mail =(trim($_POST['businessPassword1']));
            $_POST['businessPassword'] = $this->generateHash(trim($_POST['businessPassword1']));
            $resBusinessID            = $ObjBusiness->saveBusiness($_POST);
            //send mail to business user				
            if (!$businessID) {
                $ObjEmailtemplate       = new EmailtemplateModel();
                // sent mail to user
                $languageIDs['Current'] = $_POST['businessDefaultLanguageID'];
                $emailbody              = $ObjEmailtemplate->getEmailTemlateDetails($languageIDs, '', 'business-request-approved');
                $from                   = array(
                    $emailbody['emailFromEmail'],
                    $emailbody['emailFromName']
                );
                $siteName               = $this->getSettingValue('site_settings', 'site_name');
                $siteUrl                = $this->getSettingValue('site_settings', 'global_http_url');
                $companyLogo            = $this->getSettingValue('company_information', 'company_logo');
                $userName               = $_POST['businessCFirstName'] . " " . $_POST['businessCLastName'];
                $subject                = $emailbody['emailSubject'];
                $bodytag                = str_replace('{$siteName}', $siteName, $emailbody['emailHtml']);
                $bodytag                = str_replace('{$userName}', $userName, $bodytag);
                $bodytag                = str_replace('{$businessLogin}', $_POST['businessLogin'], $bodytag);
                $bodytag                = str_replace('{$businessPassword}',$businessPassword_mail, $bodytag);
                $bodytag                = str_replace('{$companyLogo}', $companyLogo, $bodytag);
                $bodytag                = str_replace('{url}', rtrim($siteUrl, "/") . '/business/', $bodytag);
                $this->ObjView->assign('emailbody', $bodytag);
                $this->ObjView->assign('siteUrl', $siteUrl);
                $this->ObjView->assign('siteName', $siteName);
                $this->ObjView->assign('userName', $userName);
                $this->ObjView->assign('companyLogo', $companyLogo);
                $body                           = $this->ObjCommon->fetch("email_templates/Layout.tpl", $languageIDs);
                $mail_settings                  = $this->getSettingValue('mail_settings');
                $mail_settings['smtp_password'] = $this->encryptDecrypt("decrypt", $mail_settings['smtp_password']);
                $ObjMail                        = new Mail($mail_settings);
                $emailID                        = trim(addslashes($_POST['businessEmail']));
                $ObjMail->IsHTML();
                
                $ObjMail->sendMail($from, $emailID, $subject, $body);
                if ($ObjMail->Send()) {
                }
                //api creation code

                $this->setMessage("language.msgBusinessAdd", "success");
            }
            $this->setRedirect('business/index/');
        }
        $resCountryCode= $ObjCountry->getAllCountryCode($languageIDs);
        $this->ObjView->assign('resCountryCode', $resCountryCode);
        $defaultOption       = (isset($_POST['businessTypeID'])) ? $_POST['businessTypeID'] : '';
        $resListBusinessType = $ObjBusinessType->getBusinessTypeOption($languageIDs, '', $defaultOption);
        $this->ObjView->assign('resCountry', $ObjCountry->listCountriesForOption($languageIDs, 'Yes'));
        $agrement = $ObjContent->getContentDetails($languageIDs, '', '', 'business-agreement', 'publish', '', 'yes');
        $this->ObjView->assign('agrement', $agrement['content']);
        //to get ajax post value			
        if (isset($_POST['locCity'])) {
            $cityValue = $_POST['locCity'];
        } else if (isset($_POST['province'])) {
            $cityValue = $_POST['province'];
        }
        if (isset($_POST['businessLatitude'])) {
            $this->ObjView->assign('businessLatitude', $_POST['businessLatitude']);
            $this->ObjView->assign('businessLongitude', $_POST['businessLongitude']);
        }
        //--------GOOGLE MAP-----------	
        $ObjCommon                 = new CommonModel();
        $settings                  = array();
        $settings['mapContainer']  = 'map_canvas';
        $settings['zoom']          = 14;
        $settings_lat              = (isset($_POST['businessLatitude']) ? $_POST['businessLatitude'] : '40.37871715896132');
        $settings_long             = (isset($_POST['businessLongitude']) ? $_POST['businessLongitude'] : '-3.696368895874002');
        $settings['latLng']        = array(
            $settings_lat,
            $settings_long
        );
        $settings['latLngTextBox'] = array(
            'frmLat',
            'frmLon'
        );
        $settings['address']       = array(
            'address1' => 'locAddress1',
            'address2' => 'locAddress2',
            'city' => 'locCity',
            'province' => 'locProvince',
            'country' => 'locCountryID'
        );
        $settings['changeTags']    = array(
            'locAddress1',
            'locAddress2',
            'locCity',
            'locProvince',
            'locCountryID'
        );
        $settings['isclickable']   = 'true';
        $settings['title']         = "";
        $settings['info']          = "";
        $ObjCommon->addMarker($settings);
        $this->ObjView->assign("map", $ObjCommon->showmap());
        //--------GOOGLE MAP-----------		
	$resListCountryCode        = $ObjUser->loadAllCountryCode($languageIDs); 
	$this->ObjView->assign('resListCountryCode', $resListCountryCode);	        
        $this->ObjView->assign('defaultLang', $languageIDs['Default']);
        $this->ObjView->assign('currentLang', $currentLanguageID);
        $this->ObjView->assign('resListBusinessType', $resListBusinessType);
        $this->ObjView->assign('cityValue', $cityValue);
        $this->ObjView->assign('cityhidValue', $cityValue);
        $this->ObjView->assign('listRoles',isset($listRoles) ? $listRoles : array());
        $this->ObjView->display('BusinessAdd.tpl');
    }
    //END OF FUNCTION
    //BUSINESS EDIT ACTION
    public function editAction($businessReqID = '') { 
        $ObjBusinessType        = new BusinessTypeModel();
        $ObjCountry             = new CountryModel();
        $ObjBusiness            = new BusinessModel();
        $ObjImage               = new ImageModel();
        $ObjUser          		= new UserModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $currentLanguageID      = $languageIDs['Current'];
        $businessID             = $this->getRequestValue('id');
		$listRoles = '';
        if ($businessID > 0) {
            $lat           = '';
            $lng           = '';
            $resBusiness   = $ObjBusiness->getBusinessDetails($businessID, $languageIDs);
         //   print_r($resBusiness);exit; 
             if(count($resBusiness)>0){
                $phone=explode("-",$resBusiness['businessPhone']);
                $userCountrycode=$phone[0];
                $resBusiness['businessPhone']=$phone[1];
            }
            $this->ObjView->assign('busCountrycode', isset($userCountrycode)?$userCountrycode:'');
            $defaultOption = $resBusiness['businessTypeID'];
            if (!$resBusiness) {
                $this->setRedirect('/new/');
            }
            $this->ObjView->assignValues($resBusiness);
            $this->ObjView->assign('businessProfile', $resBusiness['businessProfile']);
            $businessLocID = $resBusiness['businessLocID'];
            $this->ObjView->assign('businessLocID', $businessLocID);
            if ($resBusiness['locStateID'] > 0)
            {
                $stateValue = $resBusiness['locStateID'];
            }
            elseif ($resBusiness['locProvince'] != '')
            {
                $stateValue = $resBusiness['locProvince'];
            }
            $resBusiness['businessSubTypeID'] = isset($resBusiness['businessSubTypeID']) ? $resBusiness['businessSubTypeID'] : '';
            $this->ObjView->assign('hidBusinessSubTypeID', $resBusiness['businessSubTypeID']);
            $resbusinessLangID = $businessID;
            $lat               =($resBusiness['locLatitude']) ?$resBusiness['locLatitude'] : '40.37871715896132';
            $lng               =($resBusiness['locLongitude']) ? $resBusiness['locLongitude'] : '-3.696368895874002';

        } else if ($businessReqID > 0) {
            $ObjBusinessRequest = new BusinessRequestModel();
            $resBusinessReq     = $ObjBusinessRequest->getBusinessRequestDetailsForEdit($businessReqID);
			$address            = '';
			if($resBusinessReq['locAddress1']!=''){
				$address            .= $resBusinessReq['locAddress1'] ;
			}
			if($resBusinessReq['locAddress2']!=''){
				$address            .= "+" . $resBusinessReq['locAddress2'] ;
			}
			if($resBusinessReq['locCity']!=''){
				$address            .= "+" . $resBusinessReq['locCity'] ;
			}
			if($resBusinessReq['statename']!=''){
				$address            .= "+" . $resBusinessReq['statename'] ;
			}
			if($resBusinessReq['countryName']!=''){
				$address            .= "+" . $resBusinessReq['countryName'] ;
			}
           
            $this->ObjView->assignValues($resBusinessReq);
          //  echo $resBusinessReq['businessReqPhone'];exit;
           if($resBusinessReq['businessPhone']!=''){
                $phone=explode("-",$resBusinessReq['businessPhone']);
                $busCountrycode=$phone[0];
                $resBusinessReq['businessPhone']=$phone[1];
                $this->ObjView->assign('businessPhone', isset($resBusinessReq['businessPhone'])?$resBusinessReq['businessPhone']:'');
                $this->ObjView->assign('busCountrycode', isset($busCountrycode)?$busCountrycode:'');
            }
            
            if ($resBusinessReq['locStateID'] > 0)
            {
                $stateValue = $resBusinessReq['locStateID'];
            }
            elseif ($resBusinessReq['locProvince'] != '')
            {
                $stateValue = $resBusinessReq['locProvince'];
            }
            $defaultOption = $resBusinessReq['businessSubTypeID'];
            $this->ObjView->assign('businessReqID', $businessReqID);
        }
         $resCountryCode= $ObjCountry->getAllCountryCode($languageIDs);
        $this->ObjView->assign('resCountryCode', $resCountryCode);
        $ObjEmailtemplate       = new EmailtemplateModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        if (isset($_POST['submitBusiness'])) {
            $rule = "isKey~*businessKey->database->business,businessKey,businessID!='" . $businessID . "' AND businessStatus!='Deleted'";
            $this->validate_dbrule_confirm('frmBusiness', 'businessKey', $rule);
        }
        if ($this->ObjForm->isValid('frmBusiness', 'submitBusiness')) {
            $prevStatus = $resBusiness['businessStatus'];
            $newPwd   = trim($_POST['businessPassword']);
            $cnfrmPwd = trim($_POST['businessPassword1']);
            if ((trim($_POST['businessPassword']) != '') && (trim($_POST['businessPassword']) == trim($_POST['businessPassword1'])) && (trim($_POST['businessPassword1']) != '')) {
                $_POST['businessPassword'] = $this->generateHash(trim($_POST['businessPassword1']));
            } else {
                $_POST['businessPassword'] = $resBusiness['businessPassword'];
            }
            $_POST['languageIDs']     = $languageIDs;
            $logoImageWidth           = $this->getSettingValue('product_cart_settings', 'logo_image_width');
            $logoImageHeight          = $this->getSettingValue('product_cart_settings', 'logo_image_height');
            $_POST['logoImageWidth']  = $logoImageWidth;
            $_POST['logoImageHeight'] = $logoImageHeight;
            /*unlink old image*/
            if (!empty($_POST["business_logo_temp"])) {
                $imagePath = __UPLOADS_FOLDER . 'business/' . trim($resBusiness['businessLogo']);
                $ObjImage->unlinkImage($imagePath);
                $imagePath = __UPLOADS_FOLDER . 'business/thumb/' . trim($resBusiness['businessLogo']);
                $ObjImage->unlinkImage($imagePath);
            }
            /*unlink old image*/
            $_POST['businessKey'] = ($_POST['businessKey']) ? $_POST['businessKey'] : $this->ObjCommon->generateKey("business", $_POST['businessName'], $businessID, "unique");
            $_POST['profileStatus']='Complete';
            $resbusinessID        = $ObjBusiness->saveBusiness($_POST);
            $resbusinessLangID    = $_POST['businessDefaultLanguageID'];
            if ($businessReqID > 0) {
                $ObjBusinessRequest->changeBusinessRequestStatus($businessReqID, 'Approved', $resbusinessID);
            }
            if ($businessReqID > 0) {
                // sent mail to user
                $languageIDs['Current'] = $resbusinessLangID;
                $emailbody              = $ObjEmailtemplate->getEmailTemlateDetails($languageIDs, '', 'business-request-approved');
                $from                   = array(
                    $emailbody['emailFromEmail'],
                    $emailbody['emailFromName']
                );
                $siteName               = $this->getSettingValue('site_settings', 'site_name');
                $siteUrl                = $this->getSettingValue('site_settings', 'global_http_url');
                $companyLogo            = $this->getSettingValue('company_information', 'company_logo');
                $userName               = $_POST['businessCFirstName'] . " " . $_POST['businessCLastName'];
                $subject                = $emailbody['emailSubject'];
                $bodytag                = str_replace('{$siteName}', $siteName, $emailbody['emailHtml']);
                $bodytag                = str_replace('{$userName}', $userName, $bodytag);
                $bodytag                = str_replace('{$businessLogin}', $_POST['businessLogin'], $bodytag);
                $bodytag                = str_replace('{$businessPassword}', $newPwd, $bodytag);
                $bodytag                = str_replace('{$companyLogo}', $companyLogo, $bodytag);
                $bodytag                = str_replace('{url}', rtrim($siteUrl, "/") . '/business/', $bodytag);
                $this->ObjView->assign('emailbody', $bodytag);
                $this->ObjView->assign('siteUrl', $siteUrl);
                $this->ObjView->assign('siteName', $siteName);
                $this->ObjView->assign('userName', $userName);
                $this->ObjView->assign('companyLogo', $companyLogo);
                $body                           = $this->ObjCommon->fetch("email_templates/Layout.tpl", $languageIDs);
                $mail_settings                  = $this->getSettingValue('mail_settings');
                $mail_settings['smtp_password'] = $this->encryptDecrypt("decrypt", $mail_settings['smtp_password']);
                $ObjMail                        = new Mail($mail_settings);
                $emailID                        = trim(addslashes($_POST['businessEmail']));
                $ObjMail->IsHTML();
                $ObjMail->sendMail($from, $emailID, $subject, $body);
                if ($ObjMail->Send()) {
                }
            } else if ((!empty($newPwd)) && (!empty($cnfrmPwd))) {
                //send mail to business user
                // sent mail to user
                $languageIDs['Current'] = $resbusinessLangID;
                $emailbody              = $ObjEmailtemplate->getEmailTemlateDetails($languageIDs, '', 'user-password-changed');
                $from                   = array(
                    $emailbody['emailFromEmail'],
                    $emailbody['emailFromName']
                );
                $siteName               = $this->getSettingValue('site_settings', 'site_name');
                $siteUrl                = $this->getSettingValue('site_settings', 'global_http_url');
                $companyLogo            = $this->getSettingValue('company_information', 'company_logo');
                $userName               = $_POST['businessCFirstName'] . " " . $_POST['businessCLastName'];
                $subject                = $emailbody['emailSubject'];
                $bodytag                = str_replace('{$siteName}', $siteName, $emailbody['emailHtml']);
                $bodytag                = str_replace('{$userName}', $userName, $bodytag);
                $bodytag                = str_replace('{$userPassword}', $newPwd, $bodytag);
                $bodytag                = str_replace('{$companyLogo}', $companyLogo, $bodytag);
                $bodytag                = str_replace('{url}', rtrim($siteUrl, "/") . '/business/', $bodytag);
                $this->ObjView->assign('emailbody', $bodytag);
                $this->ObjView->assign('siteUrl', $siteUrl);
                $this->ObjView->assign('siteName', $siteName);
                $this->ObjView->assign('userName', $userName);
                $this->ObjView->assign('companyLogo', $companyLogo);
                $body                           = $this->ObjCommon->fetch("email_templates/Layout.tpl", $languageIDs);
                $mail_settings                  = $this->getSettingValue('mail_settings');
                $mail_settings['smtp_password'] = $this->encryptDecrypt("decrypt", $mail_settings['smtp_password']);
                $ObjMail                        = new Mail($mail_settings);
                $emailID                        = trim(addslashes($_POST['businessEmail']));
                $ObjMail->IsHTML();
                $ObjMail->sendMail($from, $emailID, $subject, $body);
                if ($ObjMail->Send()) {
                }
            }
            if ($businessReqID > 0) {
                $this->setMessage("language.msgBusinessRequestApproved", "success", "Business", "approve_message");
                $this->setRedirect('/businessrequest/index/');
            } else {
                $ObjControllerRef        = new ProductController();                       
                if($prevStatus!=$_POST['businessStatus']) {                   
                    $this->saveActivity($businessID);
                }                 
                if ((!empty($newPwd)) && (!empty($cnfrmPwd))) {
                    //$this->setMessage("language.msgBusinessUpdatePasswordCase", "message_success");
                    $this->setMessage("language.msgBusinessUpdate", "message_success");
                } else {
                    $this->setMessage("language.msgBusinessUpdate", "message_success");

                }
            }
            $this->setRedirect('/business/index/');
        }
        //to get ajax post value			
        if (isset($_POST['locStateID']))
        {
            $stateValue = $_POST['locStateID'];
			
        }
        else if (isset($_POST['locProvince']))
        {
            $stateValue = $_POST['locProvince'];
        }
        if (isset($_POST['locLatitude'])) {
            $this->ObjView->assign('locLatitude', $_POST['locLatitude']);
            $this->ObjView->assign('locLongitude', $_POST['locLongitude']);
        }
        if (isset($_POST['businessTypeID'])) {
            $defaultOption = ($_POST['businessTypeID'] != '') ? $_POST['businessTypeID'] : '';
        }
        //--------GOOGLE MAP-----------	
        $ObjCommon                = new CommonModel();
        $settings                 = array();
        $settings['mapContainer'] = 'map_canvas';
        $settings['zoom']         = 14;
       
        
        if (empty($lat)) {
          
            $address = isset($address) ? $address : '';
			if($address!=''){
            $latLng  = $ObjCommon->getLatLng($address, 'array');
            if (is_array($latLng)) {
                $lat = $latLng['lat'][0];
                $lng = $latLng['lng'][0];
            }
			}
        }
        if (isset($latLng) && $latLng == 'No Result') {
            
            $lat = 9.968;
            $lng = 76.31799999999998;
        }
        if ($lat != '') {
            $settings['latLng'] = array(
                $lat,
                $lng
            );
        }
        $this->ObjView->assign("locLatitude", $lat);
        $this->ObjView->assign("locLongitude", $lng);
        $settings['latLngTextBox'] = array(
            'frmLat',
            'frmLon'
        );
        $settings['address']       = array(
            'address1' => 'locAddress1',
            'address2' => 'locAddress2',
            'city' => 'locCity',
            'province' => 'locProvince',
            'country' => 'locCountryID'
        );
        $settings['changeTags']    = array(
            'locAddress1',
            'locAddress2',
            'locCity',
            'locProvince',
            'locCountryID'
        );
        $settings['isclickable']   = 'true';
        $settings['title']         = "";
        $settings['info']          = "";
        $ObjCommon->addMarker($settings);
        $this->ObjView->assign("map", $ObjCommon->showmap());
        //--------GOOGLE MAP-----------		
        $languageIDs['Current'] = $languageIDs['Content'];
        $this->ObjView->assign('resCountry', $ObjCountry->listCountriesForOption($languageIDs, 'Yes'));
        $resBusiness['businessLatitude']  = isset($resBusiness['businessLatitude']) ? $resBusiness['businessLatitude'] : '';
        $resBusiness['businessLongitude'] = isset($resBusiness['businessLongitude']) ? $resBusiness['businessLongitude'] : '';
        $resListBusinessType              = $ObjBusinessType->getBusinessTypeOption($languageIDs, '', $defaultOption);
        $this->ObjView->assign('defaultLang', $languageIDs['Default']);
        $this->ObjView->assign('currentLang', $currentLanguageID);
        $this->ObjView->assign('resListBusinessType', $resListBusinessType);
        if (isset($stateValue)) {
            $this->ObjView->assign('stateValue', isset($stateValue)?$stateValue:'');
        $this->ObjView->assign('statehidValue', isset($stateValue)?$stateValue:0);
        }
        $this->ObjView->assign('businessLatitude', $resBusiness['businessLatitude']);
        $this->ObjView->assign('businessLongitude', $resBusiness['businessLongitude']);
        if ($businessReqID > 0) {
            $resBusinessReq['businessLatitude']  = isset($resBusinessReq['businessLatitude']) ? $resBusinessReq['businessLatitude'] : '';
            $resBusinessReq['businessLongitude'] = isset($resBusinessReq['businessLongitude']) ? $resBusinessReq['businessLongitude'] : '';
            $resBusiness['businessAgreement']    = isset($resBusiness['businessAgreement']) ? $resBusiness['businessAgreement'] : '';
            $this->ObjView->assign('businessLatitude', $resBusinessReq['businessLatitude']);
            $this->ObjView->assign('businessLongitude', $resBusinessReq['businessLongitude']);
        }
        if ($resBusiness['businessAgreement'] == '' || $businessReqID > 0) {
            $ObjContent = new ContentModel();
            $agrement   = $ObjContent->getContentDetails($languageIDs, '', '', 'business-agreement', 'publish', '', 'yes');
            $this->ObjView->assign('agrement', $agrement['content']);
        }
	$resListCountryCode        = $ObjUser->loadAllCountryCode($languageIDs); 
	$this->ObjView->assign('resListCountryCode', $resListCountryCode);	        
        //SALES REP END
        $this->ObjView->assign('listRoles',isset($listRoles) ? $listRoles : array());
        $this->ObjView->assign("showPrivilege", $this->ObjCommon->hasPrivilege('business/show/'));
        $this->ObjView->display('BusinessAdd.tpl');
    }
    //END OF FUNCTION
    //TO SHOW BUSINESS
    public function showAction() {
        $ObjBusiness            = new BusinessModel();
        $businessID             = $this->getRequestValue('id');
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $this->ObjView->assign("editprivilege", $this->ObjCommon->hasPrivilege('business/edit/'));
        $this->ObjView->assign("agreementPrivilege", $this->ObjCommon->hasPrivilege('agreements/index/'));
        if ($businessID > 0) {
            $global_url  = $this->getSettingValue('site_settings', 'global_http_url');
            $resBusiness = $ObjBusiness->getBusinessDetails($businessID, $languageIDs);
            if (!$resBusiness) {
                $this->setRedirect('/new/');
            }
            $this->ObjView->assign('businessAccountDetail', $resBusiness['businessAccountDetails']);
            $website         = $resBusiness['businessWebsite'];
            $website         = str_replace("HTTP://", "http://", $website);
            $website         = str_replace("HTTPS://", "https://", $website);
            $websiteStr      = strstr($website, 'http://');
            $websiteStrHttps = strstr($website, 'https://');
            if ($websiteStr == "" && $websiteStrHttps == "") {
                $website = "http://" . $website;
            }
            $resBusiness['website'] = $website;
            $this->ObjView->assignValues($resBusiness);

        }
        $previousURl = $this->getPreviousURL();
        // get business locations
        list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
        $businessLocDetails = $ObjBusiness->listBusinessLocations($limitFrom, $limitTo, '', $businessID, $languageIDs);
        $resPagesCount      = $this->setPagesCount($key = 'page');
        $this->ObjView->assign('global_url', $global_url);
        list($limitFrom, $limitTo) = $this->getPageSettings($key = 'review-page');
        $params['languageIDs'] = $languageIDs;
        $params['limitFrom']   = $limitFrom;
        $params['limitTo']     = $limitTo;
        $params['businessID']  = $businessID;
        $resBusinessReviews    = $ObjBusiness->listBusinessRatingsAndReviews($params);
        $resPagesCount         = $this->setPagesCount($key = 'review-page');
        $resBusinessRatings    = $ObjBusiness->selectUserRating($businessID);
        $this->ObjView->assign('businessLocDetails', $businessLocDetails);
        $this->ObjView->assign('previousURl', $previousURl);
        $this->ObjView->assign('resBusinessRatings', $resBusinessRatings);
        $this->ObjView->assign('locLatitude', $resBusiness['locLatitude']);
        $this->ObjView->assign('locLongitude', $resBusiness['locLongitude']);
        $this->ObjView->assign('resBusinessReviews', $resBusinessReviews);
        $this->ObjView->assign('businessDetails', $resBusiness);
        $this->ObjView->assign('businessProfile', $resBusiness['businessProfile']);
        $this->ObjView->assign("editreviewprivilege", $this->ObjCommon->hasPrivilege('business/review/'));
        $this->ObjView->assign("delreviewprivilege", $this->ObjCommon->hasPrivilege('business/destroyreview/'));
        $this->ObjView->display('BusinessView.tpl');
    }
    //END OF FUNCTION
    //TO SHOW BUSINESS SUBTYPE
    public function ajaxBusinessSubtypeAction() {
        $ObjBusinessType   = new BusinessTypeModel();
        $parentBusTypeID   = $_POST['businessTypeID'];
        $businessSubTypeID = $_POST['businessSubTypeID'];
        $languageIDs       = $this->ObjView->languageIDs;
        if ($parentBusTypeID) {
            $resBusinessTypes = $ObjBusinessType->getSubBusinessType($languageIDs, $parentBusTypeID, '', 'Active');
            $this->ObjView->assign('resBusinessTypes', $resBusinessTypes);
            $this->ObjView->assign('businessSubTypeID', $businessSubTypeID);
        }
        $this->ObjView->display('BusinessSubTypes.tpl');
    }
    //END OF FUNCTION
    // admin to Edit user review comment
    public function reviewAction() {
        $ObjBusiness = new BusinessModel();
        $languageIDs = $this->ObjView->languageIDs;
        $reviewID    = $this->getRequestValue('id');
        $userID      = $this->getRequestValue('user');
        $businessID  = $this->getRequestValue('business');
        if ($this->ObjForm->isValid('formReviewEditSubmit', 'submitReviewEdit')) {
            $userComment  = $_POST['userComment'];
            $reviewStatus = $_POST['reviewStatus'];
            $respEdits    = $ObjBusiness->saveUserReviewComment($languageIDs, $businessID, $userID, $userComment, $reviewID, '', '', '', '', '', '', '', $reviewStatus);
            $this->setMessage("language.msgCommentPostAdd", "success");
            echo '<script type="text/javascript">parent.location.reload();parent.$.colorbox.close(); </script>';
            exit;
        }
        $resUserComment = $ObjBusiness->selectUserReviewComment($languageIDs, $reviewID, $businessID, $userID);
        $this->ObjView->assign('userComment', $resUserComment['userComment']);
        $this->ObjView->assign('reviewStatus', $resUserComment['reviewStatus']);
        $this->ObjView->display('BusinessReviewEdit.tpl');
    }
    //FUNCTION TO MANAGE BUSINESS LOCATIONS
    public function locationAction() {
        $this->ObjCommon->askPrivilege('business/edit/');
        $ObjBusiness            = new BusinessModel();
        $ObjCountry             = new CountryModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $businessID             = $this->getRequestValue('id');
        $resBusiness            = $ObjBusiness->getBusinessDetails($businessID, $languageIDs);
        $this->ObjView->assign('businessName', $resBusiness['businessName']);
        $this->ObjView->assign('businessID', $businessID);
        $currentLanguageID     = $languageIDs['Current'];
        $resListCountryOptions = $ObjCountry->listCountries($languageIDs, '');
        $this->ObjView->assign('resCountry', $resListCountryOptions);
        $resCountryCode= $ObjCountry->getAllCountryCode($languageIDs);
        $this->ObjView->assign('resCountryCode', $resCountryCode);
        $_POST['locStateID'] = isset($_POST['locStateID']) ? $_POST['locStateID'] : '';
        if (isset($_POST['locStateID'])) {
            $state = $_POST['locStateID'];
        } else {
            $state = $_POST['locProvince'];
        }
        $businessLocID = $this->getRequestValue('businessLocID');
        if ($businessLocID > 0) {
            $businessLocDetails = $ObjBusiness->getBusinessLocationDetails('', $businessLocID, $languageIDs);
             if(count($businessLocDetails)>0){
            $phone=explode("-",$businessLocDetails['locPhone']);
            $userCountrycode=$phone[0];
            $businessLocDetails['locPhone']=$phone[1];
        }
        $this->ObjView->assign('busCountrycode', isset($userCountrycode)?$userCountrycode:'');
            $locLatitude        = $businessLocDetails['locLatitude'];
            $locLongitude       = $businessLocDetails['locLongitude'];
            if (($businessLocDetails['locStateID']) > 0) {
                $state = $businessLocDetails['locStateID'];
            } else {
                $state = $businessLocDetails['locProvince'];
            }
            $this->ObjView->assign("show", 'yes');
            $this->ObjView->assignValues($businessLocDetails);
        }
        $key = $this->getRequestValue('key');
        if ($key == 1) {
            $this->ObjView->assign('key', 1);
        }
        //change status of business location			
        if (isset($_POST['changeStatus'])) {
            $deleteBusinessLocation = $ObjBusiness->changeBusinessLocationStatus($_POST);
            if ($deleteBusinessLocation && $_POST['changeStatus'] == 'Deleted') {
                $this->setMessage("language.msgBusinessLocDelete", "success");
            } else if ($deleteBusinessLocation) {
                $this->setMessage("language.msgStatus", "success");
            }
            $this->setRedirect();
        }
        //submit locations
        $page = (($this->getRequestValue('page') > 0) ? $this->getRequestValue('page') : "1");
        $this->ObjView->assign('page', $page);
        if ($this->ObjForm->isValid('frmBusinessLocation', 'submitBusinessLocation')) {
            $_POST['languageIDs'] = $languageIDs;
            $insert               = $ObjBusiness->saveBusinessLocation($languageIDs, $_POST);
            if ($_POST['businessLocID'] > 0) {
                $this->setMessage("language.msgLocationUpdate", "success");
                if ($page) {
                    $this->setRedirect('business/location/id/' . $businessID . "/page/" . $page . "/");
                } else {
                    $this->setRedirect('business/location/id/' . $businessID . "/");
                }
            } else {
                $this->setMessage("language.msgLocationAdd", "success");
                $this->setRedirect('business/location/id/' . $businessID . "/");
            }
        } else if (isset($_POST['submitBusinessLocation'])) {
            $this->ObjView->assign('submitted', 1);
        }
        if (isset($_POST['locLatitude'])) {
            $locLatitude  = isset($_POST['locLatitude']) ? $_POST['locLatitude'] : '';
            $locLongitude = $_POST['locLongitude'];
            $this->ObjView->assign('locLatitude', $_POST['locLatitude']);
            $this->ObjView->assign('locLongitude', $_POST['locLongitude']);
        }
        $this->ObjView->assign('stateValue', $state);
        $this->ObjView->assign('statehidValue', $state);
        $this->ObjView->assign('defaultLang', $languageIDs['Default']);
        $this->ObjView->assign('currentLang', $currentLanguageID);
        // get business locations
        // pagination settings
        list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
        $link = 'businessID/' . $businessID . '/';
        $page = $this->getRequestValue('page');
        if ($page)
            $link .= "page/" . $page . "/";
        $businessLocDetails = $ObjBusiness->listBusinessLocations($limitFrom, $limitTo, '', $businessID, $languageIDs);
        $this->ObjView->assign('businessLocDetails', $businessLocDetails);
        $resPagesCount = $this->setPagesCount($key = 'page');
        //For add location
        if ($this->getRequestValue("task") == 'new')
            $this->ObjView->assign("show", 'yes');
        //--------GOOGLE MAP-----------	
        $ObjCommon                = new CommonModel();
        $settings                 = array();
        $settings['mapContainer'] = 'map_canvas';
        $settings['zoom']         = 14;
        if (isset($locLatitude)) {
            $settings['latLng'] = array(
                $locLatitude,
                $locLongitude
            );
        } else {
            $settings['latLng'] = array(
                '40.37871715896132',
                '-3.696368895874002'
            );
        }
        $settings['latLngTextBox'] = array(
            'frmLat',
            'frmLon'
        );
        $settings['address']       = array(
            'location' => 'locName',
            'address1' => 'locAddress1',
            'address2' => 'locAddress2',
            'city' => 'locCity',
            'state' => 'locStateID',
            'province' => 'locProvince',
            'country' => 'locCountryID'
        );
        $settings['changeTags']    = array(
            'locName',
            'locCity',
            'locStateID',
            'locCountryID'
        );
        $settings['isclickable']   = 'true';
        $settings['title']         = "";
        $settings['info']          = "";
        $ObjCommon->addMarker($settings);
        $this->ObjView->assign("map", $ObjCommon->showmap());
        //--------GOOGLE MAP-----------		
        $this->ObjView->assign('link', $link);
        $this->ObjView->display('BusinessLocations.tpl');
    }
    //END OF FUNCTION
    //FUNCTION TO MANAGE BUSINESS LOCATIONS
    public function userAction() {
        $ObjBusiness      = new BusinessModel();
        $ObjCountry       = new CountryModel();
        $ObjEmailtemplate = new EmailtemplateModel();
        $languageIDs      = $this->ObjView->languageIDs;
        $businessID       = $this->getRequestValue('id');
        $resBusiness      = $ObjBusiness->getBusinessDetails($businessID, $languageIDs);
        $this->ObjView->assign('businessName', $resBusiness['businessName']);
        $this->ObjView->assign('businessID', $businessID);
        $businessUserID      = $this->getRequestValue('businessUserID');
        $resBusinessLocation = $ObjBusiness->listBusinessLocations('', '', 'Active', $businessID, $languageIDs, '', '', 'Yes');
        foreach ($resBusinessLocation as $location) {
            $locations[] = array(
                $location['businessLocID'],
                $location['location'] . '<br/>'
            );
        }
        $this->ObjView->assign("businessLocations", $locations);
        // pagination settings
        list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
        $link = 'businessID/' . $businessID . '/';
        $page = $this->getRequestValue('page');
        if ($page)
            $link .= "page/" . $page . "/";
        $businessUserDetails = $ObjBusiness->listBusinessUsers($languageIDs, $limitFrom, $limitTo, $businessID);
        $this->ObjView->assign('businessUserDetails', $businessUserDetails);
        $resPagesCount = $this->setPagesCount($key = 'page');
        if ($businessUserID > 0) {
            $businessUserDetails = $ObjBusiness->getBusinessUser($businessUserID);
            $dbPassword          = $this->decodeString($businessUserDetails['businessUserPassword']);
            $arrLocations        = explode(",", $businessUserDetails['locName']);
            $this->ObjView->assign("show", 'yes');
            $this->ObjView->assign("arrLocations", $arrLocations);
            $this->ObjView->assign("businessUserID", $businessUserDetails['businessUserID']);
            $this->ObjView->assign("businessUserFirstName", $businessUserDetails['businessUserFirstName']);
            $this->ObjView->assign("businessUserLastName", $businessUserDetails['businessUserLastName']);
            $this->ObjView->assign("businessUserEmail", $businessUserDetails['businessUserEmail']);
            $this->ObjView->assign("businessUserUserName", $businessUserDetails['businessUserUserName']);
            $this->ObjView->assign("businessUserStatus", $businessUserDetails['businessUserStatus']);
        }
        $key = $this->getRequestValue('key');
        if ($key == 1) {
            $this->ObjView->assign('key', 1);
        }
        //change status of business user			
        if (isset($_POST['businessUserStatus'])) {
            if (sizeof($_POST['checkbusinessUserIDs']) > 0) {
                $businessUsers = array();
                foreach ($_POST['checkbusinessUserIDs'] as $businessUserID) {
                    array_push($businessUsers, $businessUserID);
                }
                $updateBusinessUser = $ObjBusiness->updateBusinessUserStatus($businessUsers, $_POST['businessUserStatus']);
                if ($_POST['businessUserStatus'] == 'Deleted') {
                    $this->setMessage("language.lblUserDeleted", "success");
                } else {
                    $this->setMessage("language.lblStatusChanged", "success");
                }
                $this->setRedirect();
            }
        }
        //submit locations
        $page = (($this->getRequestValue('page') > 0) ? $this->getRequestValue('page') : "1");
        $this->ObjView->assign('page', $page);
        if ($this->ObjForm->isValid('frmBusinessUser', 'submitBusinessUser')) {
            $insert = $ObjBusiness->saveBusinessUser($_POST);
            if ($businessUserID > 0) {
                if (trim($dbPassword) != trim($_POST['userConfirmPassword']) && trim($_POST['userConfirmPassword']) != '') {
                    /*mailing new password*/
                    $languageIDs['Current'] = $businessUserDetails['businessDefaultLanguageID'];
                    $emailbody              = $ObjEmailtemplate->getEmailTemlateDetails($languageIDs, '', 'user-password-changed');
                    $from                   = array(
                        $emailbody['emailFromEmail'],
                        $emailbody['emailFromName']
                    );
                    $siteName               = $this->getSettingValue('site_settings', 'site_name');
                    $siteUrl                = $this->getSettingValue('site_settings', 'global_http_url');
                    $companyLogo            = $this->getSettingValue('company_information', 'company_logo');
                    $userName               = $_POST['businessUserFirstName'] . " " . $_POST['businessUserLastName'];
                    $subject                = $emailbody['emailSubject'];
                    $bodytag                = str_replace('{$siteName}', $siteName, $emailbody['emailHtml']);
                    $bodytag                = str_replace('{$userName}', $userName, $bodytag);
                    $bodytag                = str_replace('{$userPassword}', $_POST['businessUserPassword'], $bodytag);
                    $bodytag                = str_replace('{$companyLogo}', $companyLogo, $bodytag);
                    $bodytag                = str_replace('{url}', rtrim($siteUrl, "/") . '/business/', $bodytag);
                    $this->ObjView->assign('emailbody', $bodytag);
                    $this->ObjView->assign('siteUrl', $siteUrl);
                    $this->ObjView->assign('siteName', $siteName);
                    $this->ObjView->assign('userName', $userName);
                    $this->ObjView->assign('companyLogo', $companyLogo);
                    $body                           = $this->ObjCommon->fetch("email_templates/Layout.tpl", $languageIDs);
                    $mail_settings                  = $this->getSettingValue('mail_settings');
                    $mail_settings['smtp_password'] = $this->encryptDecrypt("decrypt", $mail_settings['smtp_password']);
                    $ObjMail                        = new Mail($mail_settings);
                    $emailID                        = trim(addslashes($_POST['businessUserEmail']));
                    $ObjMail->IsHTML();
                    $ObjMail->sendMail($from, $emailID, $subject, $body);
                    if ($ObjMail->Send()) {
                    }
                    /*mailing new password*/
                }
            } else {
                // sent mail to user
                $languageIDs['Current'] = $resBusiness['businessDefaultLanguageID'];
                $emailbody              = $ObjEmailtemplate->getEmailTemlateDetails($languageIDs, '', 'business-user-added');
                $from                   = array(
                    $emailbody['emailFromEmail'],
                    $emailbody['emailFromName']
                );
                $siteName               = $this->getSettingValue('site_settings', 'site_name');
                $siteUrl                = $this->getSettingValue('site_settings', 'global_http_url');
                $companyLogo            = $this->getSettingValue('company_information', 'company_logo');
                $userName               = $_POST['businessUserFirstName'] . " " . $_POST['businessUserLastName'];
                $subject                = $emailbody['emailSubject'];
                $bodytag                = str_replace('{$siteName}', $siteName, $emailbody['emailHtml']);
                $bodytag                = str_replace('{$userName}', $userName, $bodytag);
                $bodytag                = str_replace('{$businessLogin}', $_POST['businessUserUserName'], $bodytag);
                $bodytag                = str_replace('{$businessPassword}', $_POST['businessUserPassword'], $bodytag);
                $bodytag                = str_replace('{$businessName}', $resBusiness['businessName'], $bodytag);
                $bodytag                = str_replace('{$companyLogo}', $companyLogo, $bodytag);
                $bodytag                = str_replace('{url}', rtrim($siteUrl, "/") . '/business/', $bodytag);
                $this->ObjView->assign('emailbody', $bodytag);
                $this->ObjView->assign('siteUrl', $siteUrl);
                $this->ObjView->assign('siteName', $siteName);
                $this->ObjView->assign('userName', $userName);
                $this->ObjView->assign('companyLogo', $companyLogo);
                $body                           = $this->ObjCommon->fetch("email_templates/Layout.tpl", $languageIDs);
                $mail_settings                  = $this->getSettingValue('mail_settings');
                $mail_settings['smtp_password'] = $this->encryptDecrypt("decrypt", $mail_settings['smtp_password']);
                $ObjMail                        = new Mail($mail_settings);
                $emailID                        = trim(addslashes($_POST['businessUserEmail']));
                $ObjMail->IsHTML();
                $ObjMail->sendMail($from, $emailID, $subject, $body);
                if ($ObjMail->Send()) {
                }
            }
            if ($_POST['businessUserID'] > 0) {
                $this->setMessage("language.lblUserUpdated", "success");
                if ($page) {
                    $this->setRedirect('business/user/id/' . $businessID . "/page/" . $page . "/");
                } else {
                    $this->setRedirect('business/user/id/' . $businessID . "/");
                }
            } else {
                $this->setMessage("language.msgUserAdd", "success");
                $this->setRedirect('business/user/id/' . $businessID . "/");
            }
        } else if (isset($_POST['submitBusinessUser'])) {
            $this->ObjView->assign('submitted', 1);
        }
        // get business users
        //For add location
        if ($this->getRequestValue("task") == 'new')
            $this->ObjView->assign("show", 'yes');
        $this->ObjView->display('BusinessUsers.tpl');
    }
    //END OF FUNCTION
    //FUNCTION to delete Business User
    public function ajaxdestroyuserAction() {
        $ObjBusiness     = new BusinessModel();
        $userList        = array(
            $_POST['userid']
        );
        $delBusinessUser = $ObjBusiness->updateBusinessUserStatus($userList, 'Deleted');
        $this->setMessage("language.lblUserDeleted", "success");
        echo 1;
    }
    //END of function deleteBusinessUserAction
    //FUNCTION to change Business User status
    public function ajaxchangeuserstatusAction() {
        $ObjBusiness     = new BusinessModel();
        $userList        = array(
            $_POST['userid']
        );
        $delBusinessUser = $ObjBusiness->updateBusinessUserStatus($userList, $_POST['status']);
        $this->setMessage("language.msgUserStatusUpdate", "success");
        if ($delBusinessUser)
            echo 1;
    }
    //END of function deleteBusinessUserAction

    public function followAction() {
        $ObjBusiness        = new BusinessModel();
        $businessID         = $this->getRequestValue("id");
        //$previousURl              = $this->getPreviousURL();
        $settingsDateFormat = $this->getSettingValue('site_settings', 'date_format');
        $settingsTimeFormat = $this->getSettingValue('site_settings', 'time_format');
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $currentLanguageID     = $languageIDs['Current'];
        $link            = 'business/follow/';
        if (isset($_POST['submitSearch'])) {
            if ($_POST['businessName'] != '') {
                 $link .= 'name/' . $this->encodeUrlString($_POST['businessName']) . '/';
            }
        $this->setRedirect($link);
        }
        $businessName     = $this->decodeUrlString($this->getRequestValue('name'));
        $this->ObjView->assign('businessName', $businessName);
        $this->ObjView->assign("link", $link);
        list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');

         if ($businessID!='') {  
        $resListBusinessFollowers = $ObjBusiness->listBusineesFollwers($businessID,$businessName, '', $status = "No", $limitFrom, $limitTo,$currentLanguageID);
      
         }else{   
              $resListBusinessFollowers = $ObjBusiness->listBusineesFollwers('',$businessName, '', $status = "No", $limitFrom, $limitTo,$currentLanguageID);
          
         }
        $resPagesCount            = $this->setPagesCount($key = 'page');
        if (isset($_POST['businessFollowers'])) {
            $MAX               = 3;
            // maximum number of elements
            $ObjCsv            = new Csv();
            $csvOutputHeader   = array(
                $this->getLanguageValue("lblName"),
                $this->getLanguageValue("lblContactEmail"),
                $this->getLanguageValue("lblFollowedDate"),
                $this->getLanguageValue("lblMerchant")
            );
            $csvOutputFileName = "Merchant_Followers_" . date('d_m_Y_h_i_s_A');
            $csvOutputData     = $ObjCsv->output($csvOutputFileName . '.csv', $resListBusinessFollowers, $csvOutputHeader);
        }
        $privilageReq = $this->ObjCommon->hasPrivilege('businessrequest/');
        $this->ObjView->assign("privilageReq", $privilageReq);
        /* $privilagePayment = $this->ObjCommon->hasPrivilege('business/payment/');
        $this->ObjView->assign("privilagePayment", $privilagePayment); */
        $this->ObjView->assign('resListBusinessFollowers', $resListBusinessFollowers);
        //$this->ObjView->assign('previousURl', $previousURl);
        $this->ObjView->assign('businessID', $businessID);
        $this->ObjView->assign('date_format', $settingsDateFormat);
        $this->ObjView->assign('time_format', $settingsTimeFormat);
        $this->ObjView->display('FollowList.tpl');
    }

    function validate_dbrule_confirm($form_name, $field_name, $rule) {
        $_SESSION['SESS_FORM_VALIDATE'][$form_name][$field_name]['validate'] = $rule;
    }
    public function destroyAction() {
        $ObjBusiness           = new BusinessModel();
        $ObjProduct            = new ProductModel();
        $languageIDs           = $this->ObjView->languageIDs;
        $deleteprivilege       = $this->ObjCommon->hasPrivilege('business/destroy/');
        $businessID            = $_POST['businessID'];
        $_POST['changeStatus'] = 'Deleted';
        $productExistsArray    = array();
        if ($_POST['changeStatus'] == 'Deleted') {
            $productExistsForBusiness = $ObjProduct->isProductsExistByBusiness($businessID);
            if ($productExistsForBusiness > 0) {
                $productExistsArray[] = $ObjBusiness->getBusinessDetails($businessID, $languageIDs);
            } else {
                $changestatus = $ObjBusiness->changeBusinessStatus($_POST, $businessID, $deleteprivilege);
            }
        } else {
            $changestatus = $ObjBusiness->changeBusinessStatus($_POST, $businessID, $deleteprivilege);
        }
        if (is_array($productExistsArray) && ($_POST['changeStatus'] == "Deleted")) {
            for ($i = 0; $i < count($productExistsArray); $i++) {
                $businessName[] = $productExistsArray[$i]['businessName'];
            }
            $errCouldNotBusiness = $this->getLanguageValue("errCouldNotBusiness");
            if (isset($businessName))
                $this->setMessage($errCouldNotBusiness . implode(", ", $businessName), "error");
        } else if ($changestatus && $_POST['changeStatus'] == "Deleted") {
            $this->setMessage("language.msgBusinessDelete", "success");
        } else if ($changestatus) {
            $this->setMessage("language.msgStatus", "success");
        }
        echo 1;
    }
    //FUNCTION TO DELETE CITY
    public function AjaxDestroylocAction() {
        $ObjBusiness = new BusinessModel();
        $busLocID    = $this->getRequestValue('id');
        $page        = $this->getRequestValue('page');
        $businessID  = $this->getRequestValue('businessID');
        if ($busLocID > 0) {
            $destroyLoc = $ObjBusiness->destroyBusinessLocation($busLocID);
            $link       = "/business/location/id/" . $businessID . "/";
            if ($page)
                $link .= "page/" . $page . "/";
            if ($destroyLoc) {
                $this->setMessage("language.msgBusinessLocDelete", 3);
                $this->setRedirect($link);
            } else {
                $this->setMessage("language.msgStatus", "success");
                $this->setRedirect($link);
            }
        }
    }
    //END OF FUNCTION
    //FUNCTION to change the businee Status
    public function ajaxchangeStatusAction() {
        $ObjBusiness             = new BusinessModel();
        $_POST['changeStatus']   = $_POST['businesstatus'];
        $prevStatus              = $ObjBusiness->getBusinessStatus($_POST['businessID']);        
        $ObjControllerRef        = new ProductController();        
        $resChangeBusinessStatus = $ObjBusiness->changeBusinessStatus($_POST, $_POST['businessID']);
        if($prevStatus!=$_POST['changeStatus']) { 
            $this->saveActivity($_POST['businessID']);
        } 
    }
    public function saveActivity($businessID) {
         $ObjActivity     = new ActivityModel();
         $ObjActivity->saveActivity('B',$businessID);        
    }
    public function ajaxlocchangestatusAction() {
        $ObjBusiness                 = new BusinessModel();
        $_POST['changeStatus']       = $_POST['locStatus'];
        $_POST['businessLocationID'] = $_POST['businessLocationID'];
        $resChangeBusinessLocStatus  = $ObjBusiness->changeBusinessLocationStatus($_POST);
    }
    //FUNCTION TO DELETE CITY
    public function destroyreviewAction() {
        $ObjBusiness = new BusinessModel();
        $reviewID    = $this->getRequestValue('id');
        $status      = $this->getRequestValue('status');
        $busID       = $this->getRequestValue('busid');
        if ($busID != '') {
            $link = "/business/show/id/" . $busID . "/";
        } else {
            $link = "/business/showreview/";
        }
        if ($reviewID > 0) {
            $resDestroyReview = $ObjBusiness->changeReviewStatus($reviewID, $status);
            if ($resDestroyReview) {
                if ($status == 'delete') {
                    $this->setMessage("language.msgReviewDelete", 3);
                }
                $this->setRedirect($link);
            }
        }
    }
    //Approve Merchant Request
    public function approveMerchantAction() {
        $businessReqID = $this->getRequestValue('rid');
        $from          = $this->getRequestValue('from');
        if ($from == "list") {
            $this->ObjView->assign("fromSection", "list");
        }
        $this->ObjView->assign("showPrivilege", $this->ObjCommon->hasPrivilege('businessrequest/show/'));
        $this->editAction($businessReqID);
    }
    public function ajaxchangereviewstatusAction() {
        $ObjBusiness     = new BusinessModel();
        $reviewID        = $_POST['rid'];
        $status          = $_POST['status'];
        $reschangeStatus = $ObjBusiness->changeReviewStatus($reviewID, $status);
        $this->setMessage("language.msgReviewApproved", 3);
    }

    public function checkRegistrationNumExist($params)
    {
        $ObjBusiness        = new BusinessModel();
        $value = $params['value'];
        if($value){
            $res=  $ObjBusiness->checkRegistrationNumExist($value);
            if($res){
                    return false;
                }
                else{
                    return true;
                }
        }
    }
}