<?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: CommonController.php, v 1.2 2013/04/25 20:52:11
//
class CommonController {
    public $_dynamic_menu;
    public $objCache;
    public $ObjView;
    public $ObjSession;
    public $ObjCookie;
    public $_currentcurrency;
    public function __construct($ObjView, $ObjSession, $ObjCookie) {
        $this->ObjView    = $ObjView;
        $this->ObjSession = $ObjSession;
        $this->ObjCookie  = $ObjCookie;
        $this->objCache   = new Cache(CACHE_DRIVER); // Load Dynamic cache Library
        $this->checkSettingsTimeout();
        $this->init();
        if (DEVELOPER_MODE) {
            $theme = $this->getRequestValue('theme');
            if ($theme != '')
                $_SESSION['THEME'] = strtolower($theme);
        }
    }
    //to check time out settings
    public function checkSettingsTimeout() {
        $_settings = Registry::getInstance('_settings');
        $timeOut   = $_settings['security_settings']['security_user_timeout'];
        //$manageSessionID	= $this->ObjSession->getSessionID();		
        if ($this->ObjSession->getSession("TIMEOUT")) {
            $userTimeout  = $this->ObjSession->getSession("TIMEOUT");
            $session_life = time() - $userTimeout;
            if ($session_life > $timeOut && $timeOut != '') {
                $SessionDestroy = $this->ObjSession->unsetSession('TIMEOUT');
                $this->ObjSession->unsetSession("REGISTERED_USER_ID");
                if ($this->getRequestValue(1) == 'referrals' && $this->getRequestValue(2) == 'email') {
                    echo '<script type="text/javascript">parent.location.reload();parent.$.fancybox.close(); </script>';
                    exit;
                } else {
                    $this->setRedirect("index/");
                    exit;
                }
            }
        }
        $this->ObjSession->setSession("TIMEOUT", time());
    }
    //	initialize variables
    public function init() {
        $this->setLanguages();
        $this->setCommonSettings();
        $this->setUserAccess();
        $this->setCurrencyFormatPlugin();
        $this->setAddressFormatPlugin();
        $this->setCustomDateWithFormat();
        $this->setUrlFormatPlugin();
        $this->setRequestPathPlugin();
        $this->setCurrency();
    }
    //set languages
    public function setLanguages() {
        $ObjLanguage = new LanguageModel();
        if (!$resListLanguages = $this->objCache->get('f_lng_list')) {
            $resListLanguages = $ObjLanguage->listLanguages("", $status = "Active");
            $this->objCache->set('f_lng_list', $resListLanguages, CACHE_TTL_LEVEL_3);
        }
        $cookieLanguageID     = $this->ObjCookie->getCookie($this->ObjView->_section . '_CurrentLanguageID');
        $cookieLanguageStatus = false;
        foreach ($resListLanguages as $language) {
            if ($language['languageDefault'] == 'Yes') {
                $this->languageIDs['Default'] = $language['languageID'];
                $defaultLanguageDetails       = $language;
            }
            if ($language['languageID'] == $cookieLanguageID && $language['languageStatus'] == 'Active') {
                $cookieLanguageStatus   = true;
                $currentLanguageDetails = $ObjLanguage->getLanguageDetails($language['languageID']);
            }
            $this->languageIDs['All'][] = $language['languageID'];
        }
        if ($cookieLanguageID > 0 && $cookieLanguageStatus)
            $this->languageIDs['Current'] = $cookieLanguageID;
        else {
            $this->languageIDs['Current'] = $this->languageIDs['Default'];
            $currentLanguageDetails       = $defaultLanguageDetails;
        }
        $this->ObjView->languageIDs = $this->languageIDs;
        $this->ObjView->setCacheDir(__CORE_PUBLIC_FRONTEND_CACHE_PATH . "/" . $this->languageIDs['Current']);
        if (!$this->ObjView->_languageXML = $this->objCache->get('f_lng_xml_' . $this->languageIDs['Current'])) {
            $this->ObjView->_languageXML = $ObjLanguage->loadLanguageXMLtoArray(__CORE_PUBLIC_COMMON_FRONTEND_PATH . '/' . __DIR_LANGUAGE . '/' . $currentLanguageDetails['LanguageLCIDstring'] . '.xml');
            $this->objCache->set('f_lng_xml_' . $this->languageIDs['Current'], $this->ObjView->_languageXML, CACHE_TTL_LEVEL_3);
        }
        $this->ObjView->assign('language', $this->ObjView->_languageXML);
        $this->ObjView->assign('currentLanguageID', $this->languageIDs['Current']);
        $this->ObjView->assign('AjaxCurrLanguage', $currentLanguageDetails['LanguageLCIDstring']);
        $this->ObjView->assign('view_common_languages', $resListLanguages);
        $this->ObjView->assign('languageIDs', $this->languageIDs);
        $this->ObjView->assign("view_common_languageName", $currentLanguageDetails['languageName']);
        $this->ObjView->assign("view_common_languageImage", $currentLanguageDetails['languageImage']);
    }
    private function setCommonSettings() {
        /*
        SetHeader
        setServerSessionTimeZone
        checkFbLogin
        datePickerDate
        social Sharing Settings	
        setServerSessionTimeZone	- 	To set the Mysql server timezone 
        date_default_timezone_set	-	To set the PHP server timezone 
        */
        $ObjTimeZone                   = new TimezoneModel();
        $dateFormat                    = $this->getSettingValue('site_settings', 'date_format');
        $time_format                   = $this->getSettingValue('site_settings', 'time_format');
        $settingsSiteName              = $this->getSettingValue('site_settings', 'site_name');
        $defaultTimezone               = $this->getSettingValue('site_settings', 'default_timezone');
        $settingsGlobalMetaTitle       = $this->getSettingValue('seo_settings', 'global_meta_title');
        $settingsGlobalMetaDescription = $this->getSettingValue('seo_settings', 'global_meta_description');
        $settingsGlobalMetaKeywords    = $this->getSettingValue('seo_settings', 'global_meta_keywords');
        $settingsLinkedInPage          = $this->getSettingValue('seo_settings', 'linkedin_page');
        $settingsGoogleAnalytics       = $this->getSettingValue('seo_settings', 'google_analytics_id');
        $settingsCollectPhoneNumber    = $this->getSettingValue('product_cart_settings', 'collect_phone_number');
        $settingsFbEnableLogin         = $this->getSettingValue('social_media_settings', 'facebook_enable_login');
        $appID                         = $this->getSettingValue('social_media_settings', 'facebook_application_id');
        $settingsFacebookPage          = $this->getSettingValue('social_media_settings', 'facebook_page');
        $enableCharity                 = $this->getSettingValue('charity_settings', 'charity_enable');
        $settingsTwitterPage           = $this->getSettingValue('social_media_settings', 'twitter_page');
        $manageSessionID               = $this->ObjSession->getSessionID();
        $manageUserName                = $this->ObjSession->getSession("MANAGE_USER_NAME" . $manageSessionID);
        if (!$timeZoneRes = $this->objCache->get('f_tzone_detail_' . $defaultTimezone)) {
            $timeZoneRes = $ObjTimeZone->getTimezoneDetails($defaultTimezone, 'timeZoneDetail,timeZoneAbbreviation,timeZoneDiff');
            $this->objCache->set('f_tzone_detail_' . $defaultTimezone, $timeZoneRes, CACHE_TTL_LEVEL_2);
        }
        $setSessionTimeZone      = $ObjTimeZone->setServerSessionTimeZone('', $timeZoneRes['timeZoneDiff']);
        $settingsGlobalMetaTitle = (trim($settingsGlobalMetaTitle) == "") ? $settingsSiteName : $settingsGlobalMetaTitle;
        date_default_timezone_set($timeZoneRes['timeZoneDetail']);
        switch ($dateFormat) {
            case '%Y-%m-%d':
                $returnDateFormat = 'yy-mm-dd';
                break;
            case '%m/%d/%Y':
                $returnDateFormat = 'mm/dd/yy';
                break;
            case '%d-%m-%Y':
                $returnDateFormat = 'dd-mm-yy';
                break;
            default:
                $returnDateFormat = 'mm/dd/yy';
        }
        $this->ObjView->assign('settingsGoogleAnalytics', $settingsGoogleAnalytics);
        $this->ObjView->assign('settingsFacebookPage', $settingsFacebookPage);
        $this->ObjView->assign('settingsTwitterPage', $settingsTwitterPage);
        $this->ObjView->assign('settingsLinkedInPage', $settingsLinkedInPage);
        $this->ObjView->assign('datePickerDateFormat', $returnDateFormat);
        $this->ObjView->assign('date_format', $dateFormat);
        $this->ObjView->assign('time_format', $time_format);
        $this->ObjView->assign('timeZoneAbbreviation', $timeZoneRes['timeZoneAbbreviation']);
        $this->ObjView->assign('fbApplicationID', $appID);
        $this->ObjView->assign('enableFBlogin', $settingsFbEnableLogin);
        $this->ObjView->assign('view_common_manageUserName', $manageUserName);
        $this->ObjView->assign('commonSiteName', trim($settingsSiteName));
        $this->ObjView->assign('commonMetaTitle', $settingsGlobalMetaTitle);
        $this->ObjView->assign('commonMetaDescription', $settingsGlobalMetaDescription);
        $this->ObjView->assign('commonMetaKeywords', $settingsGlobalMetaKeywords);
        $this->ObjView->assign('collect_phone_number', $settingsCollectPhoneNumber);
        $this->ObjView->assign('enableCharity', $enableCharity);
        $this->ObjView->assign('nowdate', strtotime("now"));
        $this->ObjView->assign('commonYear', date("Y"));
    }
    //set user access 
    public function setUserAccess() {
        $frontendPublicBlockedSections = "User"; //FRONTEND_PUBLIC_BLOCKED_SECTIONS
        $frontendPublicBlockedSections = explode(',', $frontendPublicBlockedSections);
        $frontendPublicBlockedSections = @array_merge($frontendPublicBlockedSections);
        $registeredUserID              = $this->ObjSession->getSession("REGISTERED_USER_ID");
        if (!$registeredUserID && in_array($this->ObjView->_controller, $frontendPublicBlockedSections)) {
            $this->setRedirect("index/");
        } else if ($registeredUserID > 0) {
            $ObjUsers   = new UserModel();
            $userStatus = $ObjUsers->getUserStatus($registeredUserID);
            if ($userStatus != 'Active') {
                $registeredUserID = '';
                $this->ObjSession->unsetSession("REGISTERED_USER_ID");
                $this->ObjSession->unsetSession("REGISTERED_USER_IP");
                $this->ObjSession->unsetSession("REGISTERED_USER_NAME");
                $this->ObjSession->unsetSession("REGISTERED_USER_ACCESS_DATE_TIME");
                $this->ObjSession->unsetSession("REGISTERED_USER_EMAIL");
                $this->setRedirect("index/");
            } else {
                $registeredUserName  = $this->ObjSession->getSession("REGISTERED_USER_NAME");
                $registeredUserEmail = $this->ObjSession->getSession("REGISTERED_USER_EMAIL");
                $this->ObjView->assign("commonUserEmail", $registeredUserEmail);
                $this->ObjView->assign("commonUserID", $registeredUserID);
                $this->ObjView->assign("commonUserName", $registeredUserName);
            }
        }
    }
    //to set currency format
    public function setCurrencyFormatPlugin() {
        $ObjCurrency   = new CurrencyModel();
        $resCurrencies = $ObjCurrency->listCurrencies(NULL, NULL, NULL, 'No', '');
        if (count($resCurrencies) > 0) {
            foreach ($resCurrencies as $currency) {
                if ($currency['currencyDefault'] == 'Yes') {
                    $this->ObjView->_defaultCurrency = $currency['currencyID'];
                }
                $currencies[$currency['currencyID']] = $currency;
            }
        }
        $this->ObjView->_currencies = $currencies;
        $this->ObjView->registerPlugin("modifier", "price", array(
            $this->ObjView,
            "getFormattedCurrency"
        ));
    }
    //FUNCTION  TO SET ADDRESS FORMAT PLUGIN
    public function setAddressFormatPlugin() {
        $ObjCountry = new CountryModel();
        $this->ObjView->registerPlugin("modifier", "address_format", array(
            $ObjCountry,
            "getFormattedAddress"
        ));
    }
    //END OF FUNCTION 
    //to set url format 
    public function setUrlFormatPlugin() {
        $ObjTool = Registry::getInstance('Tool');
        $this->ObjView->registerPlugin("modifier", "encode_url", array(
            $ObjTool,
            "encodeUrlString"
        ));
        return '';
    }
    //date modifier for getting the custom date with system assigned format
    public function setCustomDateWithFormat() {
        $ObjSettings = new SettingsModel();
        $this->ObjView->registerPlugin("modifier", "customDate", array(
            $ObjSettings,
            "getFormattedDate"
        ));
        return '';
    }
    //to get querystring value
    public function getRequestValue($queryStringKey = 0) {
        $ObjRewrite = Registry::getInstance('Rewrite');
        if (is_integer($queryStringKey)) {
            return (trim($ObjRewrite->_queryString[$queryStringKey]));
        } else {
            $queryStringKeyNumber = (array_search($queryStringKey, $ObjRewrite->_queryString) + 1);
            return ($queryStringKeyNumber > 1) ? trim($ObjRewrite->_queryString[$queryStringKeyNumber]) : "";
        }
    }
    //to get setting value 
    public function getSettingValue($keyGroupID, $keyID = "") {
        $_settings                      = Registry::getInstance('_settings');
        $_settings[$keyGroupID]         = isset($_settings[$keyGroupID]) ? $_settings[$keyGroupID] : '';
        $_settings[$keyGroupID][$keyID] = isset($_settings[$keyGroupID][$keyID]) ? $_settings[$keyGroupID][$keyID] : '';
        return (($keyID == "") ? ($_settings[$keyGroupID]) : ($_settings[$keyGroupID][$keyID]));
    }
    //to set redirect url  
    public function setRedirect($location_url = '', $dynamic_url = "Yes") {
        if ($dynamic_url == "Yes") {
            if ($location_url == '') {
                $ObjRewrite   = Registry::getInstance('Rewrite');
                $location_url = implode($ObjRewrite->_queryDelimiter, $ObjRewrite->_queryString);
            }
            $location_url = $this->ObjView->_base_path . '/' . ltrim($location_url, '/');
        }
        header("Location:$location_url");
        exit;
    }
    //to decode url  string 
    public function decodeUrlString($urlString) {
        $ObjTool = Registry::getInstance('Tool');
        return $decodedUrlString = $ObjTool->decodeUrlString($urlString);
    }
    //To format date
    public function formatDate($date, $dateFormat = '', $timeFormat = '') {
        $_dateMap      = array(
            '%B %e, %Y' => 'F d, Y',
            '%A, %B %e, %Y' => 'l  F d, Y',
            '%m/%d/%Y' => 'm/d/Y',
            '%d/%m/%Y' => 'd/m/Y',
            '%d-%m-%Y' => 'd-m-Y',
            '%Y-%m-%d' => 'Y-m-d'
        );
        $_timeMap      = array(
            '%I:%M %p' => 'h:i A',
            '%l:%I %p' => 'g:i A',
            '%H:%M' => 'H:i'
        );
        $phpDateFormat = (isset($_dateMap[$dateFormat])) ? $_dateMap[$dateFormat] : '';
        $phpTimeFormat = (isset($_timeMap[$timeFormat])) ? $_timeMap[$timeFormat] : '';
        $format        = $phpDateFormat . ' ' . $phpTimeFormat;
        if ($format) {
            $date = new DateTime($date);
            return $date->format($format);
        } else {
            return $date;
        }
    }
    //to set Request path for category, product, page ,menu, blog
    public function setRequestPathPlugin() {
        $this->ObjView->registerPlugin("modifier", "sef_path", array(
            $this->ObjView,
            "getSefRequestPath"
        ));
    }
    public function setCommonSefPath($type, $idsArr = array()) {
        $settingsCatalogSef = $this->getSettingValue('seo_settings', 'product_sef_format');
        $ObjUrl             = new UrlrewriteModel();
        $resPaths           = $ObjUrl->listUrlRewritesForFrontend($this->languageIDs['Current'], $type, 1, $idsArr);
        foreach ($resPaths as $sef) {
            if ($settingsCatalogSef != 'Yes' && $sef['type'] == 'product' && $sef['parentID'] > 0) {
                //skip 
                continue;
            } else {
                $idPath                        = $sef['idPath'];
                $paths[$idPath]['requestPath'] = $sef['requestPath'];
            }
        }
        if (isset($paths)) {
            $uniqueSefArray          = array_filter($paths);
            $this->ObjView->_sefurls = $uniqueSefArray;
        }
    }
    public function setCurrency() {
        $this->ObjView->assign('cityDefCurrencyID', $this->ObjView->_defaultCurrency);
        $currentCurrencyID  = $this->ObjCookie->getCookie($this->ObjView->_section . '_currentCurrency');
        $currentCurrencyID  = ($currentCurrencyID>0)?$currentCurrencyID:$this->ObjView->_defaultCurrency;
        $this->_currentcurrency = $currentCurrencyID;
    }
}