<?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: CronController.php, v 1.0 2011/06/14 20:52:11
//
class CronController extends Controller {
    const SERVICE_VERSION = '2013-09-01';
    const REPORTS_SERVICE_VERSION = '2009-01-01';
    public function __construct() {
        parent::__construct();
        if ($this->getSettingValue('security_settings', 'cron_execution_ip_restriction') == 'Yes')
            $this->checkPermission();
    }
    public function indexAction() {
    }
    //To find date left 
    public function findDateLeft($fromDate, $toDate) {
        if ($fromDate >= $toDate) {
            return 0;
        }
        $diff        = strtotime($toDate) - strtotime($fromDate);
        $daysLeft    = floor(($diff / 60) / 60 / 24);
        $hoursLeft   = floor((($diff / 60) / 60) % 24);
        $minutesLeft = floor(($diff / 60) % 60);
        return array(
            'days' => $daysLeft,
            'hours' => $hoursLeft,
            'minutes' => $minutesLeft
        );
    }
    //End of function 
    public function formatAddress($productDetails) {
    }
    //TO SEND NEWS LETTER
    public function sendnewsletterAction() {
        $mail_settings                  = $this->getSettingValue('mail_settings');
        $mail_settings['smtp_password'] = $this->encryptDecrypt("decrypt", $mail_settings['smtp_password']);
        $sentMailLimit                  = $this->getSettingValue('product_cart_settings', 'cron_order_limit');
		$siteUrl 						= $this->getSettingValue('site_settings', 'global_http_url');
		$siteUrl                        = rtrim($siteUrl, '/');
        $ObjEmailqueue                  = new EmailqueueModel();
        $ObjMail                        = new Mail($mail_settings);
        $resEmailSent                   = $ObjEmailqueue->SendMails($ObjMail, $sentMailLimit,'',$siteUrl);
        if ($resEmailSent) {
            echo "Mail sent successfully to registered users";
        }
    }
    //End of function
    //Function for testing email tracking 
    //@usage -> Only for testing
    public function emailtrackAction() {
        $ObjMail = new ThirdPartyMailModel();
        $status  = $ObjMail->updateCampaigns();
    }
    public function timezonediffAction() {
        $ObjTimeZone     = new TimezoneModel();
        $defaultTimezone = $this->getSettingValue('site_settings', 'default_timezone');
        $ObjTimeZone->changeTimeZoneDiffWithDST();
        //reset frontend timezone detail cache variable
        $objCache = new Cache(CACHE_DRIVER);
        $objCache->delete('f_tzone_detail_' . $defaultTimezone);
    }
    public function updatevisitorlogAction() {
        $ObjLogModel         = new AnalyticsModel();
        $ObjEmailtemplate    = new EmailtemplateModel();
        $ObjProductList      = new ProductListModel();
        $log                 = '';
        //$last_updated_id		= $ObjLogModel->getLastUpdatedID();
        //$cron_limit			= 10;
        //$res_url_log_details 	= $ObjLogModel->setDummyData();
        $res_url_log_details = $ObjLogModel->getUlrLogDetails(0, 0);
        $mtime               = microtime();
        $mtime               = explode(" ", $mtime);
        $mtime               = $mtime[1] + $mtime[0];
        $starttime           = $mtime;
        $count               = 0;
        $log .= "<br>***********************************START***********************************</br>";
        echo '<pre>';
        if (count($res_url_log_details) > 0) {
            $stat_visitor_info_browser        = array();
            $stat_visitor_info_hour           = array();
            $stat_visitor_info_location       = array();
            $stat_visitor_info_os_bounce      = array();
            $stat_visitor_info_page_bounce    = array();
            $stat_visitor_info_traffic        = array();
            $stat_visitor_info_traffic_bounce = array();
            $stat_visitor_info_browser_bounce = array();
            $todays_user_ids                  = array();
            $todays_visitor_cookie_id         = array();
            $bounce_flag                      = 0;
            foreach ($res_url_log_details as $url_log_detail) {
                $temp_res                    = $ObjLogModel->getUlrLogDetailsSub($url_log_detail['visitorID']);
                $url_log_detail['urlID']     = $temp_res['urlID'];
                $url_log_detail['pageID']    = $temp_res['pageID'];
                $url_log_detail['visitTime'] = $temp_res['visitTime'];
                $result_data                 = array();
                $log .= "<br>Start Visitor " . $url_log_detail['visitorID'] . " Updation<br>";
                $result_data['pageCount'] = $ObjLogModel->getPagecount($url_log_detail['visitorID']);
                $log .= "<br>=====================Getting Page Count=====================<br><br>";
                $current_time_stamp = strtotime(date("Y-m-d H:i:s")); //[Mysql now in admin timezone]
                $cookie_life_time   = "5000"; //[in seconds]
                $last_active_time   = $url_log_detail['visitTime']; //Mysql time format
                $check_time_stamp   = strtotime(date("Y-m-d H:i:s", strtotime($cookie_life_time . " seconds", strtotime($last_active_time))));
                //Logged Out Time: By Comparing Users Last Visit Time + cookie life Time with current Time. If the sum of Last 
                //visit Time and cookie life Time exceeds the currunt time, then its considerd ad Logged Out so we can update the details
                if ($check_time_stamp < $current_time_stamp) //Consider the user as log out or visitor exited
                    {
                    if ($url_log_detail['userID'] > 0) {
                        $result_data['logOutTime'] = $last_active_time;
                        $log .= "<br>=====================Getting Log Out time =========================<br><br>";
                        //Logged Out Time
                    }
                    $result_data['exitTime'] = $last_active_time; //Exit Time of Visitor (Both Visitor and User)
                    $result_data['exitPage'] = $url_log_detail['pageID']; //Exit Page of Visitor (Both Visitor and User)
                    //also can update Total Time Spend 
                    $log .= "<br>=====================Getting Exit time  and exit page=====================<br><br>";
                } else {
                    $result_data['exitTime']   = $last_active_time;
                    $result_data['exitPage']   = $url_log_detail['pageID'];
                    $result_data['logOutTime'] = $last_active_time;
                }
                $hash_str                                       = $url_log_detail['entryDate'] . "-" . $url_log_detail['platform'];
                $hashKey                                        = $this->makeHAsh($hash_str);
                //$hashKey			= $hash_str;
                $seconds                                        = strtotime($last_active_time) - strtotime($url_log_detail['entryTime']);
                $seconds                                        = ($seconds > 0) ? $seconds : 0;
                $date_based_overview[$hashKey]['hashKey']       = $hashKey;
                $date_based_overview[$hashKey]['entryDate']     = $url_log_detail['entryDate'];
                $date_based_overview[$hashKey]['platform']      = $url_log_detail['platform'];
                $date_based_overview[$hashKey]['visitor']       = (isset($date_based_overview[$hashKey]['visitor']) ? $date_based_overview[$hashKey]['visitor'] : 0) + 1;
                $date_based_overview[$hashKey]['newVisitor']    = (isset($date_based_overview[$hashKey]['newVisitor']) ? $date_based_overview[$hashKey]['newVisitor'] : 0) + $url_log_detail['newVisit'];
                $date_based_overview[$hashKey]['orderPlaced']   = (isset($date_based_overview[$hashKey]['orderPlaced']) ? $date_based_overview[$hashKey]['orderPlaced'] : 0) + $url_log_detail['orderPlaced'];
                $date_based_overview[$hashKey]['orderAmount']   = (isset($date_based_overview[$hashKey]['orderAmount']) ? $date_based_overview[$hashKey]['orderAmount'] : 0) + $url_log_detail['orderAmount'];
                $date_based_overview[$hashKey]['doneSubscribe'] = (isset($date_based_overview[$hashKey]['doneSubscribe']) ? $date_based_overview[$hashKey]['doneSubscribe'] : 0) + $url_log_detail['doneSubscribe'];
                $date_based_overview[$hashKey]['doneSignUp']    = (isset($date_based_overview[$hashKey]['doneSignUp']) ? $date_based_overview[$hashKey]['doneSignUp'] : 0) + $url_log_detail['doneSignUp'];
                $date_based_overview[$hashKey]['visitDuration'] = (isset($date_based_overview[$hashKey]['visitDuration']) ? $date_based_overview[$hashKey]['visitDuration'] : 0) + $seconds;
                $date_based_overview[$hashKey]['pageCount']     = (isset($date_based_overview[$hashKey]['pageCount']) ? $date_based_overview[$hashKey]['pageCount'] : 0) + $result_data['pageCount'];
                if ($result_data['pageCount'] == 1) {
                    $date_based_overview[$hashKey]['bounceCount'] = (isset($date_based_overview[$hashKey]['bounceCount']) ? $date_based_overview[$hashKey]['bounceCount'] : 0) + 1;
                }
                if ($url_log_detail['userID'] > 0) {
                    $user_id_hash_str                                           = $url_log_detail['entryDate'] . "-" . $url_log_detail['userID'];
                    $user_id_hash                                               = $this->makeHAsh($user_id_hash_str);
                    $todays_user_ids[$hashKey][$url_log_detail['userID']]       = (isset($todays_user_ids[$hashKey][$url_log_detail['userID']]) ? $todays_user_ids[$hashKey][$url_log_detail['userID']] : 0) + 1;
                    $log_reg_user_id_params[$user_id_hash]['userID']            = $url_log_detail['userID'];
                    $log_reg_user_id_params[$user_id_hash]['visitor']           = (isset($log_reg_user_id_params[$user_id_hash]['visitor']) ? $log_reg_user_id_params[$user_id_hash]['visitor'] : 0) + 1;
                    $log_reg_user_id_params[$user_id_hash]['entryDate']         = $url_log_detail['entryDate'];
                    $log_reg_user_id_params[$user_id_hash]['orderPlaced']       = (isset($log_reg_user_id_params[$user_id_hash]['orderPlaced']) ? $log_reg_user_id_params[$user_id_hash]['orderPlaced'] : 0) + $url_log_detail['orderPlaced'];
                    $log_reg_user_id_params[$user_id_hash]['orderAmount']       = (isset($log_reg_user_id_params[$user_id_hash]['orderAmount']) ? $log_reg_user_id_params[$user_id_hash]['orderAmount'] : 0) + $url_log_detail['orderAmount'];
                    $log_reg_user_id_params[$user_id_hash]['doneSubscribe']     = (isset($log_reg_user_id_params[$user_id_hash]['doneSubscribe']) ? $log_reg_user_id_params[$user_id_hash]['doneSubscribe'] : 0) + $url_log_detail['doneSubscribe'];
                    $log_reg_user_id_params[$user_id_hash]['doneSignUp']        = (isset($log_reg_user_id_params[$user_id_hash]['doneSignUp']) ? $log_reg_user_id_params[$user_id_hash]['doneSignUp'] : 0) + $url_log_detail['doneSignUp'];
                    $log_reg_user_id_params[$user_id_hash]['pageCount']         = (isset($log_reg_user_id_params[$user_id_hash]['pageCount']) ? $log_reg_user_id_params[$user_id_hash]['pageCount'] : 0) + $result_data['pageCount'];
                    $login_seconds                                              = strtotime($result_data['logOutTime']) - strtotime($url_log_detail['loginTime']);
                    $log_reg_user_id_params[$user_id_hash]['loginTimeDuration'] = (isset($log_reg_user_id_params[$user_id_hash]['loginTimeDuration']) ? $log_reg_user_id_params[$user_id_hash]['loginTimeDuration'] : 0) + $login_seconds;
                } else {
                    $todays_visitor_cookie_id[$hashKey][$url_log_detail['visitorCookieID']] = (isset($todays_visitor_cookie_id[$hashKey][$url_log_detail['visitorCookieID']]) ? $todays_visitor_cookie_id[$hashKey][$url_log_detail['visitorCookieID']] : 0) + 1;
                    $log_guest_user_params['entryDate']                                     = $url_log_detail['entryDate'];
                    $log_guest_user_params['visitorCookieID']                               = $url_log_detail['visitorCookieID'];
                    //$ObjLogModel->logGuestUser($log_guest_user_params);
                }
                $browser_hash_str                                         = $url_log_detail['browserID'] . "-" . $url_log_detail['osID'] . "-" . $url_log_detail['entryDate'] . "-" . $url_log_detail['platform'];
                $hashKey                                                  = $this->makeHAsh($browser_hash_str);
                $stat_visitor_info_browser[$hashKey]['hashKey']           = $hashKey;
                $stat_visitor_info_browser[$hashKey]['browserID']         = $url_log_detail['browserID'];
                $stat_visitor_info_browser[$hashKey]['osID']              = $url_log_detail['osID'];
                $stat_visitor_info_browser[$hashKey]['entryDate']         = $url_log_detail['entryDate'];
                $stat_visitor_info_browser[$hashKey]['platform']          = $url_log_detail['platform'];
                $stat_visitor_info_browser[$hashKey]['visitor']           = (isset($stat_visitor_info_browser[$hashKey]['visitor']) ? $stat_visitor_info_browser[$hashKey]['visitor'] : 0) + 1;
                $stat_visitor_info_browser[$hashKey]['newVisitor']        = (isset($stat_visitor_info_browser[$hashKey]['newVisitor']) ? $stat_visitor_info_browser[$hashKey]['newVisitor'] : 0) + $url_log_detail['newVisit'];
                $stat_visitor_info_browser[$hashKey]['pageCount']         = (isset($stat_visitor_info_browser[$hashKey]['pageCount']) ? $stat_visitor_info_browser[$hashKey]['pageCount'] : 0) + $result_data['pageCount'];
                $stat_visitor_info_browser[$hashKey]['duration']          = (isset($stat_visitor_info_browser[$hashKey]['duration']) ? $stat_visitor_info_browser[$hashKey]['duration'] : 0) + $seconds;
                $stat_visitor_info_browser[$hashKey]['orderPlaced']       = (isset($stat_visitor_info_browser[$hashKey]['orderPlaced']) ? $stat_visitor_info_browser[$hashKey]['orderPlaced'] : 0) + $url_log_detail['orderPlaced'];
                $stat_visitor_info_browser[$hashKey]['orderAmount']       = (isset($stat_visitor_info_browser[$hashKey]['orderAmount']) ? $stat_visitor_info_browser[$hashKey]['orderAmount'] : 0) + $url_log_detail['orderAmount'];
                $stat_visitor_info_browser[$hashKey]['doneSignUp']        = (isset($stat_visitor_info_browser[$hashKey]['doneSignUp']) ? $stat_visitor_info_browser[$hashKey]['doneSignUp'] : 0) + $url_log_detail['doneSignUp'];
                $stat_visitor_info_browser[$hashKey]['doneSubscribe']     = (isset($stat_visitor_info_browser[$hashKey]['doneSubscribe']) ? $stat_visitor_info_browser[$hashKey]['doneSubscribe'] : 0) + $url_log_detail['doneSubscribe'];
                $hour_hash_str                                            = $url_log_detail['entryHour'] . "-" . $url_log_detail['entryWeek'] . "-" . $url_log_detail['countryID'] . "-" . $url_log_detail['cityID'] . "-" . $url_log_detail['entryDate'] . "-" . $url_log_detail['platform'];
                $hashKey                                                  = $this->makeHAsh($hour_hash_str);
                $stat_visitor_info_hour[$hashKey]['hashKey']              = $hashKey;
                $stat_visitor_info_hour[$hashKey]['entryDate']            = $url_log_detail['entryDate'];
                $stat_visitor_info_hour[$hashKey]['hour']                 = $url_log_detail['entryHour'];
                $stat_visitor_info_hour[$hashKey]['weekDay']              = $url_log_detail['entryWeek'];
                $stat_visitor_info_hour[$hashKey]['countryID']            = $url_log_detail['countryID'];
                $stat_visitor_info_hour[$hashKey]['cityID']               = $url_log_detail['cityID'];
                $stat_visitor_info_hour[$hashKey]['platform']             = $url_log_detail['platform'];
                $stat_visitor_info_hour[$hashKey]['visitor']              = (isset($stat_visitor_info_hour[$hashKey]['visitor']) ? $stat_visitor_info_hour[$hashKey]['visitor'] : 0) + 1;
                $stat_visitor_info_hour[$hashKey]['newVisitor']           = (isset($stat_visitor_info_hour[$hashKey]['newVisitor']) ? $stat_visitor_info_hour[$hashKey]['newVisitor'] : 0) + $url_log_detail['newVisit'];
                $stat_visitor_info_hour[$hashKey]['orderPlaced']          = (isset($stat_visitor_info_hour[$hashKey]['orderPlaced']) ? $stat_visitor_info_hour[$hashKey]['orderPlaced'] : 0) + $url_log_detail['orderPlaced'];
                $stat_visitor_info_hour[$hashKey]['orderAmount']          = (isset($stat_visitor_info_hour[$hashKey]['orderAmount']) ? $stat_visitor_info_hour[$hashKey]['orderAmount'] : 0) + $url_log_detail['orderAmount'];
                $stat_visitor_info_hour[$hashKey]['doneSignUp']           = (isset($stat_visitor_info_hour[$hashKey]['doneSignUp']) ? $stat_visitor_info_hour[$hashKey]['doneSignUp'] : 0) + $url_log_detail['doneSignUp'];
                $stat_visitor_info_hour[$hashKey]['doneSubscribe']        = (isset($stat_visitor_info_hour[$hashKey]['doneSubscribe']) ? $stat_visitor_info_hour[$hashKey]['doneSubscribe'] : 0) + $url_log_detail['doneSubscribe'];
                $hour_hash_str                                            = $url_log_detail['entryHour'] . "-" . $url_log_detail['entryDate'] . "-" . $url_log_detail['platform'];
                $hashKey                                                  = $this->makeHAsh($hour_hash_str);
                $stat_visitor_info_hour_ov[$hashKey]['hashKey']           = $hashKey;
                $stat_visitor_info_hour_ov[$hashKey]['entryDate']         = $url_log_detail['entryDate'];
                $stat_visitor_info_hour_ov[$hashKey]['hour']              = $url_log_detail['entryHour'];
                $stat_visitor_info_hour_ov[$hashKey]['platform']          = $url_log_detail['platform'];
                $stat_visitor_info_hour_ov[$hashKey]['visitor']           = (isset($stat_visitor_info_hour_ov[$hashKey]['visitor']) ? $stat_visitor_info_hour_ov[$hashKey]['visitor'] : 0) + 1;
                $stat_visitor_info_hour_ov[$hashKey]['newVisitor']        = (isset($stat_visitor_info_hour_ov[$hashKey]['newVisitor']) ? $stat_visitor_info_hour_ov[$hashKey]['newVisitor'] : 0) + $url_log_detail['newVisit'];
                $stat_visitor_info_hour_ov[$hashKey]['orderPlaced']       = (isset($stat_visitor_info_hour_ov[$hashKey]['orderPlaced']) ? $stat_visitor_info_hour_ov[$hashKey]['orderPlaced'] : 0) + $url_log_detail['orderPlaced'];
                $stat_visitor_info_hour_ov[$hashKey]['orderAmount']       = (isset($stat_visitor_info_hour_ov[$hashKey]['orderAmount']) ? $stat_visitor_info_hour_ov[$hashKey]['orderAmount'] : 0) + $url_log_detail['orderAmount'];
                $stat_visitor_info_hour_ov[$hashKey]['doneSignUp']        = (isset($stat_visitor_info_hour_ov[$hashKey]['doneSignUp']) ? $stat_visitor_info_hour_ov[$hashKey]['doneSignUp'] : 0) + $url_log_detail['doneSignUp'];
                $stat_visitor_info_hour_ov[$hashKey]['doneSubscribe']     = (isset($stat_visitor_info_hour_ov[$hashKey]['doneSubscribe']) ? $stat_visitor_info_hour_ov[$hashKey]['doneSubscribe'] : 0) + $url_log_detail['doneSubscribe'];
                $city_hash_str                                            = $url_log_detail['cityID'] . "-" . $url_log_detail['countryID'] . "-" . $url_log_detail['languageID'] . "-" . $url_log_detail['entryDate'] . "-" . $url_log_detail['platform'];
                $hashKey                                                  = $this->makeHAsh($city_hash_str);
                $stat_visitor_info_location[$hashKey]['hashKey']          = $hashKey;
                $stat_visitor_info_location[$hashKey]['entryDate']        = $url_log_detail['entryDate'];
                $stat_visitor_info_location[$hashKey]['languageID']       = $url_log_detail['languageID'];
                $stat_visitor_info_location[$hashKey]['countryID']        = $url_log_detail['countryID'];
                $stat_visitor_info_location[$hashKey]['cityID']           = $url_log_detail['cityID'];
                $stat_visitor_info_location[$hashKey]['platform']         = $url_log_detail['platform'];
                $stat_visitor_info_location[$hashKey]['visitor']          = (isset($stat_visitor_info_location[$hashKey]['visitor']) ? $stat_visitor_info_location[$hashKey]['visitor'] : 0) + 1;
                $stat_visitor_info_location[$hashKey]['newVisitor']       = (isset($stat_visitor_info_location[$hashKey]['newVisitor']) ? $stat_visitor_info_location[$hashKey]['newVisitor'] : 0) + $url_log_detail['newVisit'];
                $stat_visitor_info_location[$hashKey]['pageCount']        = (isset($stat_visitor_info_location[$hashKey]['pageCount']) ? $stat_visitor_info_location[$hashKey]['pageCount'] : 0) + $result_data['pageCount'];
                $stat_visitor_info_location[$hashKey]['duration']         = (isset($stat_visitor_info_location[$hashKey]['duration']) ? $stat_visitor_info_location[$hashKey]['duration'] : 0) + $seconds;
                $stat_visitor_info_location[$hashKey]['orderPlaced']      = (isset($stat_visitor_info_location[$hashKey]['orderPlaced']) ? $stat_visitor_info_location[$hashKey]['orderPlaced'] : 0) + $url_log_detail['orderPlaced'];
                $stat_visitor_info_location[$hashKey]['orderAmount']      = (isset($stat_visitor_info_location[$hashKey]['orderAmount']) ? $stat_visitor_info_location[$hashKey]['orderAmount'] : 0) + $url_log_detail['orderAmount'];
                $stat_visitor_info_location[$hashKey]['doneSignUp']       = (isset($stat_visitor_info_location[$hashKey]['doneSignUp']) ? $stat_visitor_info_location[$hashKey]['doneSignUp'] : 0) + $url_log_detail['doneSignUp'];
                $stat_visitor_info_location[$hashKey]['doneSubscribe']    = (isset($stat_visitor_info_location[$hashKey]['doneSubscribe']) ? $stat_visitor_info_location[$hashKey]['doneSubscribe'] : 0) + $url_log_detail['doneSubscribe'];
                $city_hash_str                                            = $url_log_detail['cityID'] . "-" . $url_log_detail['entryDate'] . "-" . $url_log_detail['platform'];
                $hashKey                                                  = $this->makeHAsh($city_hash_str);
                $stat_visitor_info_location_ov[$hashKey]['hashKey']       = $hashKey;
                $stat_visitor_info_location_ov[$hashKey]['entryDate']     = $url_log_detail['entryDate'];
                $stat_visitor_info_location_ov[$hashKey]['cityID']        = $url_log_detail['cityID'];
                $stat_visitor_info_location_ov[$hashKey]['platform']      = $url_log_detail['platform'];
                $stat_visitor_info_location_ov[$hashKey]['visitor']       = (isset($stat_visitor_info_location_ov[$hashKey]['visitor']) ? $stat_visitor_info_location_ov[$hashKey]['visitor'] : 0) + 1;
                $stat_visitor_info_location_ov[$hashKey]['newVisitor']    = (isset($stat_visitor_info_location_ov[$hashKey]['newVisitor']) ? $stat_visitor_info_location_ov[$hashKey]['newVisitor'] : 0) + $url_log_detail['newVisit'];
                $stat_visitor_info_location_ov[$hashKey]['pageCount']     = (isset($stat_visitor_info_location_ov[$hashKey]['pageCount']) ? $stat_visitor_info_location_ov[$hashKey]['pageCount'] : 0) + $result_data['pageCount'];
                $stat_visitor_info_location_ov[$hashKey]['duration']      = (isset($stat_visitor_info_location_ov[$hashKey]['duration']) ? $stat_visitor_info_location_ov[$hashKey]['duration'] : 0) + $seconds;
                $stat_visitor_info_location_ov[$hashKey]['orderPlaced']   = (isset($stat_visitor_info_location_ov[$hashKey]['orderPlaced']) ? $stat_visitor_info_location_ov[$hashKey]['orderPlaced'] : 0) + $url_log_detail['orderPlaced'];
                $stat_visitor_info_location_ov[$hashKey]['orderAmount']   = (isset($stat_visitor_info_location_ov[$hashKey]['orderAmount']) ? $stat_visitor_info_location_ov[$hashKey]['orderAmount'] : 0) + $url_log_detail['orderAmount'];
                $stat_visitor_info_location_ov[$hashKey]['doneSignUp']    = (isset($stat_visitor_info_location_ov[$hashKey]['doneSignUp']) ? $stat_visitor_info_location_ov[$hashKey]['doneSignUp'] : 0) + $url_log_detail['doneSignUp'];
                $stat_visitor_info_location_ov[$hashKey]['doneSubscribe'] = (isset($stat_visitor_info_location_ov[$hashKey]['doneSubscribe']) ? $stat_visitor_info_location_ov[$hashKey]['doneSubscribe'] : 0) + $url_log_detail['doneSubscribe'];
                if ($url_log_detail['referrerType'] != '' && $url_log_detail['referrerDetails'] != '') {
                    $traffic_hash_str                                       = $url_log_detail['cityID'] . "-" . $url_log_detail['countryID'] . "-" . $url_log_detail['referrerType'] . "-" . $url_log_detail['referrerDetails'] . "-" . $url_log_detail['entryDate'] . "-" . $url_log_detail['platform'];
                    $hashKey                                                = $this->makeHAsh($traffic_hash_str);
                    $stat_visitor_info_traffic[$hashKey]['hashKey']         = $hashKey;
                    $stat_visitor_info_traffic[$hashKey]['entryDate']       = $url_log_detail['entryDate'];
                    $stat_visitor_info_traffic[$hashKey]['referrerType']    = $url_log_detail['referrerType'];
                    $stat_visitor_info_traffic[$hashKey]['referrerDetails'] = $url_log_detail['referrerDetails'];
                    $stat_visitor_info_traffic[$hashKey]['countryID']       = $url_log_detail['countryID'];
                    $stat_visitor_info_traffic[$hashKey]['cityID']          = $url_log_detail['cityID'];
                    $stat_visitor_info_traffic[$hashKey]['platform']        = $url_log_detail['platform'];
                    $stat_visitor_info_traffic[$hashKey]['visitor']         = (isset($stat_visitor_info_traffic[$hashKey]['visitor']) ? $stat_visitor_info_traffic[$hashKey]['visitor'] : 0) + 1;
                    $stat_visitor_info_traffic[$hashKey]['newVisitor']      = (isset($stat_visitor_info_traffic[$hashKey]['newVisitor']) ? $stat_visitor_info_traffic[$hashKey]['newVisitor'] : 0) + $url_log_detail['newVisit'];
                    $stat_visitor_info_traffic[$hashKey]['pageCount']       = (isset($stat_visitor_info_traffic[$hashKey]['pageCount']) ? $stat_visitor_info_traffic[$hashKey]['pageCount'] : 0) + $result_data['pageCount'];
                    $stat_visitor_info_traffic[$hashKey]['duration']        = (isset($stat_visitor_info_traffic[$hashKey]['duration']) ? $stat_visitor_info_traffic[$hashKey]['duration'] : 0) + $seconds;
                    $stat_visitor_info_traffic[$hashKey]['orderPlaced']     = (isset($stat_visitor_info_traffic[$hashKey]['orderPlaced']) ? $stat_visitor_info_traffic[$hashKey]['orderPlaced'] : 0) + $url_log_detail['orderPlaced'];
                    $stat_visitor_info_traffic[$hashKey]['orderAmount']     = (isset($stat_visitor_info_traffic[$hashKey]['orderAmount']) ? $stat_visitor_info_traffic[$hashKey]['orderAmount'] : 0) + $url_log_detail['orderAmount'];
                    $stat_visitor_info_traffic[$hashKey]['doneSignUp']      = (isset($stat_visitor_info_traffic[$hashKey]['doneSignUp']) ? $stat_visitor_info_traffic[$hashKey]['doneSignUp'] : 0) + $url_log_detail['doneSignUp'];
                    $stat_visitor_info_traffic[$hashKey]['doneSubscribe']   = (isset($stat_visitor_info_traffic[$hashKey]['doneSubscribe']) ? $stat_visitor_info_traffic[$hashKey]['doneSubscribe'] : 0) + $url_log_detail['doneSubscribe'];
                } else if ($url_log_detail['searchEngineName'] == '' && $url_log_detail['referrerWebSite'] == '') {
                    $direct_traffic_hash_str                                     = $url_log_detail['cityID'] . "-" . $url_log_detail['countryID'] . "-" . $url_log_detail['entryDate'] . "-" . $url_log_detail['platform'];
                    $hashKey                                                     = $this->makeHAsh($direct_traffic_hash_str);
                    $stat_visitor_info_direct_traffic[$hashKey]['hashKey']       = $hashKey;
                    $stat_visitor_info_direct_traffic[$hashKey]['entryDate']     = $url_log_detail['entryDate'];
                    $stat_visitor_info_direct_traffic[$hashKey]['countryID']     = $url_log_detail['countryID'];
                    $stat_visitor_info_direct_traffic[$hashKey]['cityID']        = $url_log_detail['cityID'];
                    $stat_visitor_info_direct_traffic[$hashKey]['platform']      = $url_log_detail['platform'];
                    $stat_visitor_info_direct_traffic[$hashKey]['visitor']       = (isset($stat_visitor_info_direct_traffic[$hashKey]['visitor']) ? $stat_visitor_info_direct_traffic[$hashKey]['visitor'] : 0) + 1;
                    $stat_visitor_info_direct_traffic[$hashKey]['newVisitor']    = (isset($stat_visitor_info_direct_traffic[$hashKey]['newVisitor']) ? $stat_visitor_info_direct_traffic[$hashKey]['newVisitor'] : 0) + $url_log_detail['newVisit'];
                    $stat_visitor_info_direct_traffic[$hashKey]['pageCount']     = (isset($stat_visitor_info_direct_traffic[$hashKey]['pageCount']) ? $stat_visitor_info_direct_traffic[$hashKey]['pageCount'] : 0) + $result_data['pageCount'];
                    $stat_visitor_info_direct_traffic[$hashKey]['duration']      = (isset($stat_visitor_info_direct_traffic[$hashKey]['duration']) ? $stat_visitor_info_direct_traffic[$hashKey]['duration'] : 0) + $seconds;
                    $stat_visitor_info_direct_traffic[$hashKey]['orderPlaced']   = (isset($stat_visitor_info_direct_traffic[$hashKey]['orderPlaced']) ? $stat_visitor_info_direct_traffic[$hashKey]['orderPlaced'] : 0) + $url_log_detail['orderPlaced'];
                    $stat_visitor_info_direct_traffic[$hashKey]['orderAmount']   = (isset($stat_visitor_info_direct_traffic[$hashKey]['orderAmount']) ? $stat_visitor_info_direct_traffic[$hashKey]['orderAmount'] : 0) + $url_log_detail['orderAmount'];
                    $stat_visitor_info_direct_traffic[$hashKey]['doneSignUp']    = (isset($stat_visitor_info_direct_traffic[$hashKey]['doneSignUp']) ? $stat_visitor_info_direct_traffic[$hashKey]['doneSignUp'] : 0) + $url_log_detail['doneSignUp'];
                    $stat_visitor_info_direct_traffic[$hashKey]['doneSubscribe'] = (isset($stat_visitor_info_direct_traffic[$hashKey]['doneSubscribe']) ? $stat_visitor_info_direct_traffic[$hashKey]['doneSubscribe'] : 0) + $url_log_detail['doneSubscribe'];
                } else if ($url_log_detail['referrerWebSite'] != '' && $url_log_detail['searchEngineName'] == '' && $url_log_detail['referrerType'] == '') {
                    $traffic_hash_str                                           = $url_log_detail['cityID'] . "-" . $url_log_detail['countryID'] . "-" . $url_log_detail['referrerWebSite'] . "-" . $url_log_detail['entryDate'] . "-" . $url_log_detail['platform'];
                    $hashKey                                                    = $this->makeHAsh($traffic_hash_str);
                    $stat_visitor_info_traffic_web[$hashKey]['hashKey']         = $hashKey;
                    $stat_visitor_info_traffic_web[$hashKey]['entryDate']       = $url_log_detail['entryDate'];
                    $stat_visitor_info_traffic_web[$hashKey]['referrerWebSite'] = $url_log_detail['referrerWebSite'];
                    $stat_visitor_info_traffic_web[$hashKey]['countryID']       = $url_log_detail['countryID'];
                    $stat_visitor_info_traffic_web[$hashKey]['cityID']          = $url_log_detail['cityID'];
                    $stat_visitor_info_traffic_web[$hashKey]['platform']        = $url_log_detail['platform'];
                    $stat_visitor_info_traffic_web[$hashKey]['visitor']         = (isset($stat_visitor_info_traffic_web[$hashKey]['visitor']) ? $stat_visitor_info_traffic_web[$hashKey]['visitor'] : 0) + 1;
                    $stat_visitor_info_traffic_web[$hashKey]['newVisitor']      = (isset($stat_visitor_info_traffic_web[$hashKey]['newVisitor']) ? $stat_visitor_info_traffic_web[$hashKey]['newVisitor'] : 0) + $url_log_detail['newVisit'];
                    $stat_visitor_info_traffic_web[$hashKey]['pageCount']       = (isset($stat_visitor_info_traffic_web[$hashKey]['pageCount']) ? $stat_visitor_info_traffic_web[$hashKey]['pageCount'] : 0) + $result_data['pageCount'];
                    $stat_visitor_info_traffic_web[$hashKey]['duration']        = (isset($stat_visitor_info_traffic_web[$hashKey]['duration']) ? $stat_visitor_info_traffic_web[$hashKey]['duration'] : 0) + $seconds;
                    $stat_visitor_info_traffic_web[$hashKey]['orderPlaced']     = (isset($stat_visitor_info_traffic_web[$hashKey]['orderPlaced']) ? $stat_visitor_info_traffic_web[$hashKey]['orderPlaced'] : 0) + $url_log_detail['orderPlaced'];
                    $stat_visitor_info_traffic_web[$hashKey]['orderAmount']     = (isset($stat_visitor_info_traffic_web[$hashKey]['orderAmount']) ? $stat_visitor_info_traffic_web[$hashKey]['orderAmount'] : 0) + $url_log_detail['orderAmount'];
                    $stat_visitor_info_traffic_web[$hashKey]['doneSignUp']      = (isset($stat_visitor_info_traffic_web[$hashKey]['doneSignUp']) ? $stat_visitor_info_traffic_web[$hashKey]['doneSignUp'] : 0) + $url_log_detail['doneSignUp'];
                    $stat_visitor_info_traffic_web[$hashKey]['doneSubscribe']   = (isset($stat_visitor_info_traffic_web[$hashKey]['doneSubscribe']) ? $stat_visitor_info_traffic_web[$hashKey]['doneSubscribe'] : 0) + $url_log_detail['doneSubscribe'];
                } else {
                    if ($url_log_detail['searchKeyWord'] != '') {
                        $traffic_hash_str                                        = $url_log_detail['cityID'] . "-" . $url_log_detail['countryID'] . "-" . $url_log_detail['searchKeyWord'] . "-" . $url_log_detail['entryDate'] . "-" . $url_log_detail['platform'];
                        $hashKey                                                 = $this->makeHAsh($traffic_hash_str);
                        $stat_visitor_info_traffic_sk[$hashKey]['hashKey']       = $hashKey;
                        $stat_visitor_info_traffic_sk[$hashKey]['entryDate']     = $url_log_detail['entryDate'];
                        $stat_visitor_info_traffic_sk[$hashKey]['searchKeyWord'] = $url_log_detail['searchKeyWord'];
                        $stat_visitor_info_traffic_sk[$hashKey]['countryID']     = $url_log_detail['countryID'];
                        $stat_visitor_info_traffic_sk[$hashKey]['cityID']        = $url_log_detail['cityID'];
                        $stat_visitor_info_traffic_sk[$hashKey]['platform']      = $url_log_detail['platform'];
                        $stat_visitor_info_traffic_sk[$hashKey]['visitor']       = (isset($stat_visitor_info_traffic_sk[$hashKey]['visitor']) ? $stat_visitor_info_traffic_sk[$hashKey]['visitor'] : 0) + 1;
                        $stat_visitor_info_traffic_sk[$hashKey]['newVisitor']    = (isset($stat_visitor_info_traffic_sk[$hashKey]['newVisitor']) ? $stat_visitor_info_traffic_sk[$hashKey]['newVisitor'] : 0) + $url_log_detail['newVisit'];
                        $stat_visitor_info_traffic_sk[$hashKey]['pageCount']     = (isset($stat_visitor_info_traffic_sk[$hashKey]['pageCount']) ? $stat_visitor_info_traffic_sk[$hashKey]['pageCount'] : 0) + $result_data['pageCount'];
                        $stat_visitor_info_traffic_sk[$hashKey]['duration']      = (isset($stat_visitor_info_traffic_sk[$hashKey]['duration']) ? $stat_visitor_info_traffic_sk[$hashKey]['duration'] : 0) + $seconds;
                        $stat_visitor_info_traffic_sk[$hashKey]['orderPlaced']   = (isset($stat_visitor_info_traffic_sk[$hashKey]['orderPlaced']) ? $stat_visitor_info_traffic_sk[$hashKey]['orderPlaced'] : 0) + $url_log_detail['orderPlaced'];
                        $stat_visitor_info_traffic_sk[$hashKey]['orderAmount']   = (isset($stat_visitor_info_traffic_sk[$hashKey]['orderAmount']) ? $stat_visitor_info_traffic_sk[$hashKey]['orderAmount'] : 0) + $url_log_detail['orderAmount'];
                        $stat_visitor_info_traffic_sk[$hashKey]['doneSignUp']    = (isset($stat_visitor_info_traffic_sk[$hashKey]['doneSignUp']) ? $stat_visitor_info_traffic_sk[$hashKey]['doneSignUp'] : 0) + $url_log_detail['doneSignUp'];
                        $stat_visitor_info_traffic_sk[$hashKey]['doneSubscribe'] = (isset($stat_visitor_info_traffic_sk[$hashKey]['doneSubscribe']) ? $stat_visitor_info_traffic_sk[$hashKey]['doneSubscribe'] : 0) + $url_log_detail['doneSubscribe'];
                    }
                    if ($url_log_detail['searchEngineName'] != '') {
                        $traffic_hash_str                                           = $url_log_detail['cityID'] . "-" . $url_log_detail['countryID'] . "-" . "-" . $url_log_detail['searchEngineName'] . "-" . $url_log_detail['entryDate'] . "-" . $url_log_detail['platform'];
                        $hashKey                                                    = $this->makeHAsh($traffic_hash_str);
                        $stat_visitor_info_traffic_se[$hashKey]['hashKey']          = $hashKey;
                        $stat_visitor_info_traffic_se[$hashKey]['entryDate']        = $url_log_detail['entryDate'];
                        $stat_visitor_info_traffic_se[$hashKey]['searchEngineName'] = $url_log_detail['searchEngineName'];
                        $stat_visitor_info_traffic_se[$hashKey]['countryID']        = $url_log_detail['countryID'];
                        $stat_visitor_info_traffic_se[$hashKey]['cityID']           = $url_log_detail['cityID'];
                        $stat_visitor_info_traffic_se[$hashKey]['platform']         = $url_log_detail['platform'];
                        $stat_visitor_info_traffic_se[$hashKey]['visitor']          = (isset($stat_visitor_info_traffic_se[$hashKey]['visitor']) ? $stat_visitor_info_traffic_se[$hashKey]['visitor'] : 0) + 1;
                        $stat_visitor_info_traffic_se[$hashKey]['newVisitor']       = (isset($stat_visitor_info_traffic_se[$hashKey]['newVisitor']) ? $stat_visitor_info_traffic_se[$hashKey]['newVisitor'] : 0) + $url_log_detail['newVisit'];
                        $stat_visitor_info_traffic_se[$hashKey]['pageCount']        = (isset($stat_visitor_info_traffic_se[$hashKey]['pageCount']) ? $stat_visitor_info_traffic_se[$hashKey]['pageCount'] : 0) + $result_data['pageCount'];
                        $stat_visitor_info_traffic_se[$hashKey]['duration']         = (isset($stat_visitor_info_traffic_se[$hashKey]['duration']) ? $stat_visitor_info_traffic_se[$hashKey]['duration'] : 0) + $seconds;
                        $stat_visitor_info_traffic_se[$hashKey]['orderPlaced']      = (isset($stat_visitor_info_traffic_se[$hashKey]['orderPlaced']) ? $stat_visitor_info_traffic_se[$hashKey]['orderPlaced'] : 0) + $url_log_detail['orderPlaced'];
                        $stat_visitor_info_traffic_se[$hashKey]['orderAmount']      = (isset($stat_visitor_info_traffic_se[$hashKey]['orderAmount']) ? $stat_visitor_info_traffic_se[$hashKey]['orderAmount'] : 0) + $url_log_detail['orderAmount'];
                        $stat_visitor_info_traffic_se[$hashKey]['doneSignUp']       = (isset($stat_visitor_info_traffic_se[$hashKey]['doneSignUp']) ? $stat_visitor_info_traffic_se[$hashKey]['doneSignUp'] : 0) + $url_log_detail['doneSignUp'];
                        $stat_visitor_info_traffic_se[$hashKey]['doneSubscribe']    = (isset($stat_visitor_info_traffic_se[$hashKey]['doneSubscribe']) ? $stat_visitor_info_traffic_se[$hashKey]['doneSubscribe'] : 0) + $url_log_detail['doneSubscribe'];
                    }
                }
                $bounce_browser_hash_str = $url_log_detail['browserID'] . "-" . $url_log_detail['countryID'] . "-" . $url_log_detail['cityID'] . "-" . $url_log_detail['entryDate'] . "-" . $url_log_detail['platform'];
                $hashKey_browser         = $this->makeHAsh($bounce_browser_hash_str);
                $bounce_os_hash_str      = $url_log_detail['osID'] . "-" . $url_log_detail['countryID'] . "-" . $url_log_detail['cityID'] . "-" . $url_log_detail['entryDate'] . "-" . $url_log_detail['platform'];
                $hashKey_os              = $this->makeHAsh($bounce_os_hash_str);
                $bounce_page_hash_str    = $url_log_detail['pageID'] . "-" . $url_log_detail['countryID'] . "-" . $url_log_detail['cityID'] . "-" . $url_log_detail['entryDate'] . "-" . $url_log_detail['platform'];
                $hashKey_page            = $this->makeHAsh($bounce_page_hash_str);
                $bounce_traffic_hash_str = $url_log_detail['referrerType'] . "-" . $url_log_detail['referrerDetails'] . "-" . $url_log_detail['referrerWebSite'] . "-" . $url_log_detail['countryID'] . "-" . $url_log_detail['cityID'] . "-" . $url_log_detail['entryDate'] . "-" . $url_log_detail['platform'];
                $hashKey_traffic         = $this->makeHAsh($bounce_traffic_hash_str);
                $bounce_flag             = 1;
                if ($result_data['pageCount'] <= 1) {
                    $stat_visitor_info_browser_bounce[$hashKey_browser]['bounceVisitor'] = (isset($stat_visitor_info_browser_bounce[$hashKey_browser]['bounceVisitor']) ? $stat_visitor_info_browser_bounce[$hashKey_browser]['bounceVisitor'] : 0) + 1;
                    $stat_visitor_info_os_bounce[$hashKey_os]['bounceVisitor']           = (isset($stat_visitor_info_os_bounce[$hashKey_os]['bounceVisitor']) ? $stat_visitor_info_os_bounce[$hashKey_os]['bounceVisitor'] : 0) + 1;
                    $stat_visitor_info_page_bounce[$hashKey_page]['bounceVisitor']       = (isset($stat_visitor_info_page_bounce[$hashKey_page]['bounceVisitor']) ? $stat_visitor_info_page_bounce[$hashKey_page]['bounceVisitor'] : 0) + 1;
                    $stat_visitor_info_traffic_bounce[$hashKey_traffic]['bounceVisitor'] = (isset($stat_visitor_info_traffic_bounce[$hashKey_traffic]['bounceVisitor']) ? $stat_visitor_info_traffic_bounce[$hashKey_traffic]['bounceVisitor'] : 0) + 1;
                }
                $stat_visitor_info_browser_bounce[$hashKey_browser]['hashKey']         = $hashKey_browser;
                $stat_visitor_info_browser_bounce[$hashKey_browser]['countryID']       = $url_log_detail['countryID'];
                $stat_visitor_info_browser_bounce[$hashKey_browser]['cityID']          = $url_log_detail['cityID'];
                $stat_visitor_info_browser_bounce[$hashKey_browser]['platform']        = $url_log_detail['platform'];
                $stat_visitor_info_browser_bounce[$hashKey_browser]['entryDate']       = $url_log_detail['entryDate'];
                $stat_visitor_info_browser_bounce[$hashKey_browser]['browserID']       = $url_log_detail['browserID'];
                $stat_visitor_info_browser_bounce[$hashKey_browser]['visitor']         = (isset($stat_visitor_info_browser_bounce[$hashKey_browser]['visitor']) ? $stat_visitor_info_browser_bounce[$hashKey_browser]['visitor'] : 0) + 1;
                $stat_visitor_info_os_bounce[$hashKey_os]['hashKey']                   = $hashKey_os;
                $stat_visitor_info_os_bounce[$hashKey_os]['countryID']                 = $url_log_detail['countryID'];
                $stat_visitor_info_os_bounce[$hashKey_os]['cityID']                    = $url_log_detail['cityID'];
                $stat_visitor_info_os_bounce[$hashKey_os]['platform']                  = $url_log_detail['platform'];
                $stat_visitor_info_os_bounce[$hashKey_os]['entryDate']                 = $url_log_detail['entryDate'];
                $stat_visitor_info_os_bounce[$hashKey_os]['osID']                      = $url_log_detail['osID'];
                $stat_visitor_info_os_bounce[$hashKey_os]['visitor']                   = (isset($stat_visitor_info_os_bounce[$hashKey_os]['visitor']) ? $stat_visitor_info_os_bounce[$hashKey_os]['visitor'] : 0) + 1;
                $stat_visitor_info_page_bounce[$hashKey_page]['hashKey']               = $hashKey_page;
                $stat_visitor_info_page_bounce[$hashKey_page]['countryID']             = $url_log_detail['countryID'];
                $stat_visitor_info_page_bounce[$hashKey_page]['cityID']                = $url_log_detail['cityID'];
                $stat_visitor_info_page_bounce[$hashKey_page]['platform']              = $url_log_detail['platform'];
                $stat_visitor_info_page_bounce[$hashKey_page]['entryDate']             = $url_log_detail['entryDate'];
                $stat_visitor_info_page_bounce[$hashKey_page]['pageID']                = $url_log_detail['pageID'];
                $stat_visitor_info_page_bounce[$hashKey_page]['visitor']               = (isset($stat_visitor_info_page_bounce[$hashKey_page]['visitor']) ? $stat_visitor_info_page_bounce[$hashKey_page]['visitor'] : 0) + 1;
                $stat_visitor_info_traffic_bounce[$hashKey_traffic]['hashKey']         = $hashKey_traffic;
                $stat_visitor_info_traffic_bounce[$hashKey_traffic]['countryID']       = $url_log_detail['countryID'];
                $stat_visitor_info_traffic_bounce[$hashKey_traffic]['cityID']          = $url_log_detail['cityID'];
                $stat_visitor_info_traffic_bounce[$hashKey_traffic]['platform']        = $url_log_detail['platform'];
                $stat_visitor_info_traffic_bounce[$hashKey_traffic]['entryDate']       = $url_log_detail['entryDate'];
                $stat_visitor_info_traffic_bounce[$hashKey_traffic]['referrerType']    = $url_log_detail['referrerType'];
                $stat_visitor_info_traffic_bounce[$hashKey_traffic]['referrerDetails'] = $url_log_detail['referrerDetails'];
                $stat_visitor_info_traffic_bounce[$hashKey_traffic]['referrerWebSite'] = $url_log_detail['referrerWebSite'];
                $stat_visitor_info_traffic_bounce[$hashKey_traffic]['visitor']         = (isset($stat_visitor_info_traffic_bounce[$hashKey_traffic]['visitor']) ? $stat_visitor_info_traffic_bounce[$hashKey_traffic]['visitor'] : 0) + 1;
                $checkVisitorSearch                                                    = $ObjLogModel->checkVisitorSearchExist($url_log_detail['visitorID']);
                if ($checkVisitorSearch > 0) {
                    $ObjLogModel->logVisitorSearchDetails($url_log_detail['visitorID']);
                }
                $log .= "<br>=====================Updating details...........=====================<br><br>";
                $count++;
                $log .= "<br> End Of Visitor " . $url_log_detail['visitorID'] . "<br>==========================================================================<br><br>";
                $lastExeID = $url_log_detail['visitorID'];
                unset($result_data);
                unset($url_log_detail);
            }
            $resultCronExicution = $ObjLogModel->saveCronExicution($count, $lastExeID);
            $log .= "<br>***********************************END***********************************</br>";
        } else {
            $log .= "<br> Oops No active log deatils are found<br/><br/>";
            $log .= "<br>***********************************END***********************************</br>";
        }
        //print_r($date_based_overview);
        if (isset($date_based_overview) && count($date_based_overview) > 0) {
            foreach ($date_based_overview as $key => $value) {
                $todays_visitor_cookie_id[$key]                         = (isset($todays_visitor_cookie_id[$key]) ? $todays_visitor_cookie_id[$key] : array());
                $todays_user_ids[$key]                                  = (isset($todays_user_ids[$key]) ? $todays_user_ids[$key] : array());
                $date_based_overview_final_array[$key]                  = $value;
                $date_based_overview_final_array[$key]['uniqueVisitor'] = count($todays_visitor_cookie_id[$key]) + count($todays_user_ids[$key]);
            }
            unset($date_based_overview);
            $ObjLogModel->logDateBasedOverviewDetails($date_based_overview_final_array);
            unset($date_based_overview_final_array);
        }
        /*
        $unique_visitor_cookie_id_count	= $ObjLogModel->getUniqueVisitorUserIDCount();
        $unique_visitor_cookie_id_count	= $ObjLogModel->getUniqueVisitorCookieIDCount();
        $overview_sum_values			= $ObjLogModel->getOverviewSumValues();
        */
        //print_r($todays_user_ids);
        //print_r($overview_sum_values);
        //print_r($date_based_overview_final_array);
        if (isset($log_reg_user_id_params) && count($log_reg_user_id_params) > 0) {
            foreach ($log_reg_user_id_params as $key => $value) {
                $value['loginTimeDuration'] = ($value['loginTimeDuration'] > 0) ? $value['loginTimeDuration'] : 0;
                $productReviews             = $ObjLogModel->getUserProductReviewCount($value['userID'], $value['entryDate']);
                $businessReviews            = $ObjLogModel->getUserBusinessReviewCount($value['userID'], $value['entryDate']);
                $usersFollowBusiness        = $ObjLogModel->getUserBusinessFollowCount($value['userID'], $value['entryDate']);
                $refered_user_id            = $ObjLogModel->getUserReferralsCount($value['userID'], $value['entryDate']);
                if (isset($refered_user_id) && $refered_user_id > 0) {
                    $ObjLogModel->logRegUserReferralEngagement($refered_user_id, 1, ANALYTICS_USER_REFERRAL_POINT, $value['entryDate']);
                }
                $rank                                                = ($productReviews * ANALYTICS_USER_DEAL_REVIEW_POINT) + ($value['doneSubscribe'] * ANALYTICS_USER_SUBSCRIBE_POINT) + ($businessReviews * ANALYTICS_USER_BUSINESS_REVIEW_POINT) + ($usersFollowBusiness * ANALYTICS_USER_BUSINESS_FOLLOW_POINT);
                $log_reg_user_id_params[$key]['loginTimeDuration']   = $value['loginTimeDuration'];
                $log_reg_user_id_params[$key]['productReviews']      = $productReviews;
                $log_reg_user_id_params[$key]['businessReviews']     = $businessReviews;
                $log_reg_user_id_params[$key]['usersFollowBusiness'] = $usersFollowBusiness;
                $log_reg_user_id_params[$key]['referralsCount']      = 0;
                $log_reg_user_id_params[$key]['rank']                = $rank;
            }
            $split_up_array = array_chunk($log_reg_user_id_params, 500, true);
            unset($log_reg_user_id_params);
            if (count($split_up_array) > 0) {
                foreach ($split_up_array as $key => $value) {
                    $ObjLogModel->logRegUser($value);
                    $ObjLogModel->logRegUserEngagement($value);
                }
                unset($split_up_array);
            }
            unset($log_reg_user_id_params);
        }
        if (isset($stat_visitor_info_browser) && count($stat_visitor_info_browser) > 0) {
            $split_up_array = array_chunk($stat_visitor_info_browser, 500, true);
            unset($stat_visitor_info_browser);
            if (count($split_up_array) > 0) {
                foreach ($split_up_array as $key => $value) {
                    $ObjLogModel->logBrowserDetails($value);
                }
                unset($split_up_array);
            }
        }
        if (isset($stat_visitor_info_hour) && count($stat_visitor_info_hour) > 0) {
            $split_up_array = array_chunk($stat_visitor_info_hour, 500, true);
            unset($stat_visitor_info_hour);
            if (count($split_up_array) > 0) {
                foreach ($split_up_array as $key => $value) {
                    $ObjLogModel->logHourDetails($value);
                }
                unset($split_up_array);
            }
        }
        if (isset($stat_visitor_info_hour_ov) && count($stat_visitor_info_hour_ov) > 0) {
            $split_up_array = array_chunk($stat_visitor_info_hour_ov, 500, true);
            unset($stat_visitor_info_hour_ov);
            if (count($split_up_array) > 0) {
                foreach ($split_up_array as $key => $value) {
                    $ObjLogModel->logHourOverviewDetails($value);
                }
                unset($split_up_array);
            }
        }
        if (isset($stat_visitor_info_location) && count($stat_visitor_info_location) > 0) {
            $split_up_array = array_chunk($stat_visitor_info_location, 500, true);
            unset($stat_visitor_info_location);
            if (count($split_up_array) > 0) {
                foreach ($split_up_array as $key => $value) {
                    $ObjLogModel->logLocationDetails($value);
                }
                unset($split_up_array);
            }
        }
        if (isset($stat_visitor_info_location_ov) && count($stat_visitor_info_location_ov) > 0) {
            $split_up_array = array_chunk($stat_visitor_info_location_ov, 500, true);
            unset($stat_visitor_info_location_ov);
            if (count($split_up_array) > 0) {
                foreach ($split_up_array as $key => $value) {
                    $ObjLogModel->logLocationOverviewDetails($value);
                }
                unset($split_up_array);
            }
        }
        if (isset($stat_visitor_info_traffic) && count($stat_visitor_info_traffic) > 0) {
            $split_up_array = array_chunk($stat_visitor_info_traffic, 500, true);
            unset($stat_visitor_info_traffic);
            if (count($split_up_array) > 0) {
                foreach ($split_up_array as $key => $value) {
                    $ObjLogModel->logTrafficDetails($value);
                }
                unset($split_up_array);
            }
        }
        if (isset($stat_visitor_info_direct_traffic) && count($stat_visitor_info_direct_traffic) > 0) {
            $split_up_array = array_chunk($stat_visitor_info_direct_traffic, 500, true);
            unset($stat_visitor_info_direct_traffic);
            if (count($split_up_array) > 0) {
                foreach ($split_up_array as $key => $value) {
                    $ObjLogModel->logDirectTrafficDetails($value);
                }
                unset($split_up_array);
            }
        }
        if (isset($stat_visitor_info_traffic_sk) && count($stat_visitor_info_traffic_sk) > 0) {
            $split_up_array = array_chunk($stat_visitor_info_traffic_sk, 500, true);
            unset($stat_visitor_info_traffic_sk);
            if (count($split_up_array) > 0) {
                foreach ($split_up_array as $key => $value) {
                    $ObjLogModel->logSearchKeywordTrafficDetails($value);
                }
                unset($split_up_array);
            }
        }
        if (isset($stat_visitor_info_traffic_se) && count($stat_visitor_info_traffic_se) > 0) {
            $split_up_array = array_chunk($stat_visitor_info_traffic_se, 500, true);
            unset($stat_visitor_info_traffic_se);
            if (count($split_up_array) > 0) {
                foreach ($split_up_array as $key => $value) {
                    $ObjLogModel->logSearchEnginenameTrafficDetails($value);
                }
                unset($split_up_array);
            }
        }
        if (isset($stat_visitor_info_traffic_web) && count($stat_visitor_info_traffic_web) > 0) {
            $split_up_array = array_chunk($stat_visitor_info_traffic_web, 500, true);
            unset($stat_visitor_info_traffic_web);
            if (count($split_up_array) > 0) {
                foreach ($split_up_array as $key => $value) {
                    $ObjLogModel->logRefWebSiteTrafficDetails($value);
                }
                unset($split_up_array);
            }
        }
        if (isset($bounce_flag) && $bounce_flag == 1) {
            if (isset($stat_visitor_info_browser_bounce)) {
                $split_up_array = array_chunk($stat_visitor_info_browser_bounce, 500, true);
                unset($stat_visitor_info_browser_bounce);
                if (count($split_up_array) > 0) {
                    foreach ($split_up_array as $key => $value) {
                        $ObjLogModel->logBounceBrowserDetails($value);
                    }
                    unset($split_up_array);
                }
            }
            if (isset($stat_visitor_info_os_bounce)) {
                $split_up_array = array_chunk($stat_visitor_info_os_bounce, 500, true);
                unset($stat_visitor_info_os_bounce);
                if (count($split_up_array) > 0) {
                    foreach ($split_up_array as $key => $value) {
                        $ObjLogModel->logBounceOsDetails($value);
                    }
                    unset($split_up_array);
                }
            }
            if (isset($stat_visitor_info_page_bounce)) {
                $split_up_array = array_chunk($stat_visitor_info_page_bounce, 500, true);
                unset($stat_visitor_info_page_bounce);
                if (count($split_up_array) > 0) {
                    foreach ($split_up_array as $key => $value) {
                        $ObjLogModel->logBouncePageDetails($value);
                    }
                    unset($split_up_array);
                }
            }
            if (isset($stat_visitor_info_traffic_bounce)) {
                $split_up_array = array_chunk($stat_visitor_info_traffic_bounce, 500, true);
                unset($stat_visitor_info_traffic_bounce);
                if (count($split_up_array) > 0) {
                    foreach ($split_up_array as $key => $value) {
                        $ObjLogModel->logBounceTrafficDetails($value);
                    }
                    unset($split_up_array);
                }
            }
        }
        $popularityDayLimit   = $this->getSettingValue('product_cart_settings', 'product_popularity_date_limit');
        $dateFrom             = date('Y-m-d', strtotime('-' . $popularityDayLimit . ' days'));
        /* =======================================================================*/
        $resProductPopularity = $ObjProductList->getProductPopularity($dateFrom);
        if (count($resProductPopularity) > 0) {
            foreach ($resProductPopularity as $key => $value) {
                $ObjProductList->updateProductPopularityCount($value['productID'], $value['totalPopularity'], $value['boughtPopularity']);
            }
        }
        /* =======================================================================*/
        if (isset($lastExeID) && $lastExeID > 0)
            $result = $ObjLogModel->clearExicutedRows($lastExeID);
        //echo $log;
        echo '<pre>';
        //print_r($date_based_overview);
        //print_r($stat_visitor_info_browser_bounce);
        //print_r($stat_visitor_info_os_bounce);
        //print_r($stat_visitor_info_page_bounce);
        //print_r($stat_visitor_info_traffic_bounce);
        $mtime     = microtime();
        $mtime     = explode(" ", $mtime);
        $mtime     = $mtime[1] + $mtime[0];
        $endtime   = $mtime;
        $totaltime = ($endtime - $starttime);
        echo "This page was created in " . $totaltime . " seconds";
        echo "<pre><br>Cron Execution Completed .......<br/><br/><br>***********************************END***********************************";
    }
    public function clearlogdataAction() {
        $ObjLogModel = new AnalyticsModel();
        $ObjLogModel->clearlogdata();
    }
    public function updatevisitorlogyearAction() {
        $ObjLogModel         = new AnalyticsModel();
        $last_updated_id     = $ObjLogModel->getLastUpdatedID('analytics_location_year');
        $res_url_log_details = $ObjLogModel->getUlrLogDetailsYear($last_updated_id, 'stat_info_location', 20000);
        $visitCount          = $res_url_log_details->num_rows;
        if ($visitCount > 0) {
            $stat_visitor_info_location = array();
            for ($i = 0; $i < $visitCount; $i++) {
                $url_log_detail                                        = $res_url_log_details->fetch_array(MYSQLI_ASSOC);
                $city_hash_str                                         = $url_log_detail['cityID'] . "-" . $url_log_detail['countryID'] . "-" . $url_log_detail['languageID'] . "-" . $url_log_detail['year'] . "-" . $url_log_detail['month'] . "-" . $url_log_detail['platform'];
                $hashKey                                               = $this->makeHAsh($city_hash_str);
                $stat_visitor_info_location[$hashKey]['hashKey']       = $hashKey;
                $stat_visitor_info_location[$hashKey]['year']          = $url_log_detail['year'];
                $stat_visitor_info_location[$hashKey]['month']         = $url_log_detail['month'];
                $stat_visitor_info_location[$hashKey]['languageID']    = $url_log_detail['languageID'];
                $stat_visitor_info_location[$hashKey]['countryID']     = $url_log_detail['countryID'];
                $stat_visitor_info_location[$hashKey]['cityID']        = $url_log_detail['cityID'];
                $stat_visitor_info_location[$hashKey]['platform']      = $url_log_detail['platform'];
                $stat_visitor_info_location[$hashKey]['visitor']       = (isset($stat_visitor_info_location[$hashKey]['visitor']) ? $stat_visitor_info_location[$hashKey]['visitor'] : 0) + $url_log_detail['visitor'];
                $stat_visitor_info_location[$hashKey]['newVisitor']    = (isset($stat_visitor_info_location[$hashKey]['newVisitor']) ? $stat_visitor_info_location[$hashKey]['newVisitor'] : 0) + $url_log_detail['newVisitor'];
                $stat_visitor_info_location[$hashKey]['pageCount']     = (isset($stat_visitor_info_location[$hashKey]['pageCount']) ? $stat_visitor_info_location[$hashKey]['pageCount'] : 0) + $url_log_detail['pageCount'];
                $stat_visitor_info_location[$hashKey]['duration']      = (isset($stat_visitor_info_location[$hashKey]['duration']) ? $stat_visitor_info_location[$hashKey]['duration'] : 0) + $url_log_detail['duration'];
                $stat_visitor_info_location[$hashKey]['orderPlaced']   = (isset($stat_visitor_info_location[$hashKey]['orderPlaced']) ? $stat_visitor_info_location[$hashKey]['orderPlaced'] : 0) + $url_log_detail['orderPlaced'];
                $stat_visitor_info_location[$hashKey]['orderAmount']   = (isset($stat_visitor_info_location[$hashKey]['orderAmount']) ? $stat_visitor_info_location[$hashKey]['orderAmount'] : 0) + $url_log_detail['orderAmount'];
                $stat_visitor_info_location[$hashKey]['doneSignUp']    = (isset($stat_visitor_info_location[$hashKey]['doneSignUp']) ? $stat_visitor_info_location[$hashKey]['doneSignUp'] : 0) + $url_log_detail['doneSignUp'];
                $stat_visitor_info_location[$hashKey]['doneSubscribe'] = (isset($stat_visitor_info_location[$hashKey]['doneSubscribe']) ? $stat_visitor_info_location[$hashKey]['doneSubscribe'] : 0) + $url_log_detail['doneSubscribe'];
                $last_updated_location                                 = $url_log_detail['id'];
                unset($url_log_detail);
            }
            $res_url_log_details->free();
        }
        $last_updated_id     = $ObjLogModel->getLastUpdatedID('analytics_hour_year');
        $res_url_log_details = $ObjLogModel->getUlrLogDetailsYear($last_updated_id, 'stat_info_hour', 20000);
        $visitCount          = $res_url_log_details->num_rows;
        if ($visitCount > 0) {
            $stat_visitor_info_hour = array();
            for ($i = 0; $i < $visitCount; $i++) {
                $url_log_detail                                    = $res_url_log_details->fetch_array(MYSQLI_ASSOC);
                $hour_hash_str                                     = $url_log_detail['hour'] . "-" . $url_log_detail['weekDay'] . "-" . $url_log_detail['countryID'] . "-" . $url_log_detail['cityID'] . "-" . $url_log_detail['year'] . "-" . $url_log_detail['month'] . "-" . $url_log_detail['platform'];
                $hashKey                                           = $this->makeHAsh($hour_hash_str);
                $stat_visitor_info_hour[$hashKey]['hashKey']       = $hashKey;
                $stat_visitor_info_hour[$hashKey]['year']          = $url_log_detail['year'];
                $stat_visitor_info_hour[$hashKey]['month']         = $url_log_detail['month'];
                $stat_visitor_info_hour[$hashKey]['hour']          = $url_log_detail['hour'];
                $stat_visitor_info_hour[$hashKey]['weekDay']       = $url_log_detail['weekDay'];
                $stat_visitor_info_hour[$hashKey]['countryID']     = $url_log_detail['countryID'];
                $stat_visitor_info_hour[$hashKey]['cityID']        = $url_log_detail['cityID'];
                $stat_visitor_info_hour[$hashKey]['platform']      = $url_log_detail['platform'];
                $stat_visitor_info_hour[$hashKey]['visitor']       = (isset($stat_visitor_info_hour[$hashKey]['visitor']) ? $stat_visitor_info_hour[$hashKey]['visitor'] : 0) + $url_log_detail['visitor'];
                $stat_visitor_info_hour[$hashKey]['newVisitor']    = (isset($stat_visitor_info_hour[$hashKey]['newVisitor']) ? $stat_visitor_info_hour[$hashKey]['newVisitor'] : 0) + $url_log_detail['newVisitor'];
                $stat_visitor_info_hour[$hashKey]['orderPlaced']   = (isset($stat_visitor_info_hour[$hashKey]['orderPlaced']) ? $stat_visitor_info_hour[$hashKey]['orderPlaced'] : 0) + $url_log_detail['orderPlaced'];
                $stat_visitor_info_hour[$hashKey]['orderAmount']   = (isset($stat_visitor_info_hour[$hashKey]['orderAmount']) ? $stat_visitor_info_hour[$hashKey]['orderAmount'] : 0) + $url_log_detail['orderAmount'];
                $stat_visitor_info_hour[$hashKey]['doneSignUp']    = (isset($stat_visitor_info_hour[$hashKey]['doneSignUp']) ? $stat_visitor_info_hour[$hashKey]['doneSignUp'] : 0) + $url_log_detail['doneSignUp'];
                $stat_visitor_info_hour[$hashKey]['doneSubscribe'] = (isset($stat_visitor_info_hour[$hashKey]['doneSubscribe']) ? $stat_visitor_info_hour[$hashKey]['doneSubscribe'] : 0) + $url_log_detail['doneSubscribe'];
                $last_updated_hour                                 = $url_log_detail['id'];
                unset($url_log_detail);
            }
            $res_url_log_details->free();
        }
        //echo '<pre>';print_r($stat_visitor_info_hour);
        $last_updated_id     = $ObjLogModel->getLastUpdatedID('analytics_browser_year');
        $res_url_log_details = $ObjLogModel->getUlrLogDetailsYear($last_updated_id, 'stat_info_browser', 20000);
        $visitCount          = $res_url_log_details->num_rows;
        if ($visitCount > 0) {
            $stat_visitor_info_browser = array();
            for ($i = 0; $i < $visitCount; $i++) {
                $url_log_detail                                       = $res_url_log_details->fetch_array(MYSQLI_ASSOC);
                $hour_hash_str                                        = $url_log_detail['browserID'] . "-" . $url_log_detail['osID'] . "-" . $url_log_detail['year'] . "-" . $url_log_detail['month'] . "-" . $url_log_detail['platform'];
                $hashKey                                              = $this->makeHAsh($hour_hash_str);
                $stat_visitor_info_browser[$hashKey]['hashKey']       = $hashKey;
                $stat_visitor_info_browser[$hashKey]['year']          = $url_log_detail['year'];
                $stat_visitor_info_browser[$hashKey]['month']         = $url_log_detail['month'];
                $stat_visitor_info_browser[$hashKey]['browserID']     = $url_log_detail['browserID'];
                $stat_visitor_info_browser[$hashKey]['osID']          = $url_log_detail['osID'];
                $stat_visitor_info_browser[$hashKey]['platform']      = $url_log_detail['platform'];
                $stat_visitor_info_browser[$hashKey]['visitor']       = (isset($stat_visitor_info_browser[$hashKey]['visitor']) ? $stat_visitor_info_browser[$hashKey]['visitor'] : 0) + $url_log_detail['visitor'];
                $stat_visitor_info_browser[$hashKey]['newVisitor']    = (isset($stat_visitor_info_browser[$hashKey]['newVisitor']) ? $stat_visitor_info_browser[$hashKey]['newVisitor'] : 0) + $url_log_detail['newVisitor'];
                $stat_visitor_info_browser[$hashKey]['orderPlaced']   = (isset($stat_visitor_info_browser[$hashKey]['orderPlaced']) ? $stat_visitor_info_browser[$hashKey]['orderPlaced'] : 0) + $url_log_detail['orderPlaced'];
                $stat_visitor_info_browser[$hashKey]['orderAmount']   = (isset($stat_visitor_info_browser[$hashKey]['orderAmount']) ? $stat_visitor_info_browser[$hashKey]['orderAmount'] : 0) + $url_log_detail['orderAmount'];
                $stat_visitor_info_browser[$hashKey]['doneSignUp']    = (isset($stat_visitor_info_browser[$hashKey]['doneSignUp']) ? $stat_visitor_info_browser[$hashKey]['doneSignUp'] : 0) + $url_log_detail['doneSignUp'];
                $stat_visitor_info_browser[$hashKey]['doneSubscribe'] = (isset($stat_visitor_info_browser[$hashKey]['doneSubscribe']) ? $stat_visitor_info_browser[$hashKey]['doneSubscribe'] : 0) + $url_log_detail['doneSubscribe'];
                $stat_visitor_info_browser[$hashKey]['duration']      = (isset($stat_visitor_info_browser[$hashKey]['duration']) ? $stat_visitor_info_browser[$hashKey]['duration'] : 0) + $url_log_detail['duration'];
                $stat_visitor_info_browser[$hashKey]['pageCount']     = (isset($stat_visitor_info_browser[$hashKey]['pageCount']) ? $stat_visitor_info_browser[$hashKey]['pageCount'] : 0) + $url_log_detail['pageCount'];
                $last_updated_browser                                 = $url_log_detail['id'];
                unset($url_log_detail);
            }
            $res_url_log_details->free();
        }
        $last_updated_id     = $ObjLogModel->getLastUpdatedID('analytics_direct_traffic_year');
        $res_url_log_details = $ObjLogModel->getUlrLogDetailsYear($last_updated_id, 'stat_info_direct_traffic', 20000);
        $visitCount          = $res_url_log_details->num_rows;
        if ($visitCount > 0) {
            $stat_visitor_info_direct_traffic = array();
            for ($i = 0; $i < $visitCount; $i++) {
                $url_log_detail                                              = $res_url_log_details->fetch_array(MYSQLI_ASSOC);
                $hour_hash_str                                               = $url_log_detail['countryID'] . "-" . $url_log_detail['cityID'] . "-" . $url_log_detail['year'] . "-" . $url_log_detail['month'] . "-" . $url_log_detail['platform'];
                $hashKey                                                     = $this->makeHAsh($hour_hash_str);
                $stat_visitor_info_direct_traffic[$hashKey]['hashKey']       = $hashKey;
                $stat_visitor_info_direct_traffic[$hashKey]['year']          = $url_log_detail['year'];
                $stat_visitor_info_direct_traffic[$hashKey]['month']         = $url_log_detail['month'];
                $stat_visitor_info_direct_traffic[$hashKey]['countryID']     = $url_log_detail['countryID'];
                $stat_visitor_info_direct_traffic[$hashKey]['cityID']        = $url_log_detail['cityID'];
                $stat_visitor_info_direct_traffic[$hashKey]['platform']      = $url_log_detail['platform'];
                $stat_visitor_info_direct_traffic[$hashKey]['visitor']       = (isset($stat_visitor_info_direct_traffic[$hashKey]['visitor']) ? $stat_visitor_info_direct_traffic[$hashKey]['visitor'] : 0) + $url_log_detail['visitor'];
                $stat_visitor_info_direct_traffic[$hashKey]['newVisitor']    = (isset($stat_visitor_info_direct_traffic[$hashKey]['newVisitor']) ? $stat_visitor_info_direct_traffic[$hashKey]['newVisitor'] : 0) + $url_log_detail['newVisitor'];
                $stat_visitor_info_direct_traffic[$hashKey]['orderPlaced']   = (isset($stat_visitor_info_direct_traffic[$hashKey]['orderPlaced']) ? $stat_visitor_info_direct_traffic[$hashKey]['orderPlaced'] : 0) + $url_log_detail['orderPlaced'];
                $stat_visitor_info_direct_traffic[$hashKey]['orderAmount']   = (isset($stat_visitor_info_direct_traffic[$hashKey]['orderAmount']) ? $stat_visitor_info_direct_traffic[$hashKey]['orderAmount'] : 0) + $url_log_detail['orderAmount'];
                $stat_visitor_info_direct_traffic[$hashKey]['doneSignUp']    = (isset($stat_visitor_info_direct_traffic[$hashKey]['doneSignUp']) ? $stat_visitor_info_direct_traffic[$hashKey]['doneSignUp'] : 0) + $url_log_detail['doneSignUp'];
                $stat_visitor_info_direct_traffic[$hashKey]['doneSubscribe'] = (isset($stat_visitor_info_direct_traffic[$hashKey]['doneSubscribe']) ? $stat_visitor_info_direct_traffic[$hashKey]['doneSubscribe'] : 0) + $url_log_detail['doneSubscribe'];
                $stat_visitor_info_direct_traffic[$hashKey]['duration']      = (isset($stat_visitor_info_direct_traffic[$hashKey]['duration']) ? $stat_visitor_info_direct_traffic[$hashKey]['duration'] : 0) + $url_log_detail['duration'];
                $stat_visitor_info_direct_traffic[$hashKey]['pageCount']     = (isset($stat_visitor_info_direct_traffic[$hashKey]['pageCount']) ? $stat_visitor_info_direct_traffic[$hashKey]['pageCount'] : 0) + $url_log_detail['pageCount'];
                $last_updated_direct_traffic                                 = $url_log_detail['id'];
                unset($url_log_detail);
            }
            $res_url_log_details->free();
        }
        $last_updated_id     = $ObjLogModel->getLastUpdatedID('analytics_traffic_year');
        $res_url_log_details = $ObjLogModel->getUlrLogDetailsYear($last_updated_id, 'stat_info_traffic', 20000);
        $visitCount          = $res_url_log_details->num_rows;
        if ($visitCount > 0) {
            $stat_visitor_info_traffic = array();
            for ($i = 0; $i < $visitCount; $i++) {
                $url_log_detail                                         = $res_url_log_details->fetch_array(MYSQLI_ASSOC);
                $hour_hash_str                                          = $url_log_detail['referrerType'] . "-" . $url_log_detail['referrerDetails'] . "-" . $url_log_detail['countryID'] . "-" . $url_log_detail['cityID'] . "-" . $url_log_detail['year'] . "-" . $url_log_detail['month'] . "-" . $url_log_detail['platform'];
                $hashKey                                                = $this->makeHAsh($hour_hash_str);
                $stat_visitor_info_traffic[$hashKey]['hashKey']         = $hashKey;
                $stat_visitor_info_traffic[$hashKey]['year']            = $url_log_detail['year'];
                $stat_visitor_info_traffic[$hashKey]['month']           = $url_log_detail['month'];
                $stat_visitor_info_traffic[$hashKey]['countryID']       = $url_log_detail['countryID'];
                $stat_visitor_info_traffic[$hashKey]['cityID']          = $url_log_detail['cityID'];
                $stat_visitor_info_traffic[$hashKey]['referrerType']    = $url_log_detail['referrerType'];
                $stat_visitor_info_traffic[$hashKey]['referrerDetails'] = $url_log_detail['referrerDetails'];
                $stat_visitor_info_traffic[$hashKey]['platform']        = $url_log_detail['platform'];
                $stat_visitor_info_traffic[$hashKey]['visitor']         = (isset($stat_visitor_info_traffic[$hashKey]['visitor']) ? $stat_visitor_info_traffic[$hashKey]['visitor'] : 0) + $url_log_detail['visitor'];
                $stat_visitor_info_traffic[$hashKey]['newVisitor']      = (isset($stat_visitor_info_traffic[$hashKey]['newVisitor']) ? $stat_visitor_info_traffic[$hashKey]['newVisitor'] : 0) + $url_log_detail['newVisitor'];
                $stat_visitor_info_traffic[$hashKey]['orderPlaced']     = (isset($stat_visitor_info_traffic[$hashKey]['orderPlaced']) ? $stat_visitor_info_traffic[$hashKey]['orderPlaced'] : 0) + $url_log_detail['orderPlaced'];
                $stat_visitor_info_traffic[$hashKey]['orderAmount']     = (isset($stat_visitor_info_traffic[$hashKey]['orderAmount']) ? $stat_visitor_info_traffic[$hashKey]['orderAmount'] : 0) + $url_log_detail['orderAmount'];
                $stat_visitor_info_traffic[$hashKey]['doneSignUp']      = (isset($stat_visitor_info_traffic[$hashKey]['doneSignUp']) ? $stat_visitor_info_traffic[$hashKey]['doneSignUp'] : 0) + $url_log_detail['doneSignUp'];
                $stat_visitor_info_traffic[$hashKey]['doneSubscribe']   = (isset($stat_visitor_info_traffic[$hashKey]['doneSubscribe']) ? $stat_visitor_info_traffic[$hashKey]['doneSubscribe'] : 0) + $url_log_detail['doneSubscribe'];
                $stat_visitor_info_traffic[$hashKey]['duration']        = (isset($stat_visitor_info_traffic[$hashKey]['duration']) ? $stat_visitor_info_traffic[$hashKey]['duration'] : 0) + $url_log_detail['duration'];
                $stat_visitor_info_traffic[$hashKey]['pageCount']       = (isset($stat_visitor_info_traffic[$hashKey]['pageCount']) ? $stat_visitor_info_traffic[$hashKey]['pageCount'] : 0) + $url_log_detail['pageCount'];
                $last_updated_traffic                                   = $url_log_detail['id'];
                unset($url_log_detail);
            }
            $res_url_log_details->free();
        }
        $last_updated_id     = $ObjLogModel->getLastUpdatedID('analytics_traffic_ref_website_year');
        $res_url_log_details = $ObjLogModel->getUlrLogDetailsYear($last_updated_id, 'stat_info_traffic_ref_website', 20000);
        $visitCount          = $res_url_log_details->num_rows;
        if ($visitCount > 0) {
            $stat_visitor_info_traffic_web = array();
            for ($i = 0; $i < $visitCount; $i++) {
                $url_log_detail                                             = $res_url_log_details->fetch_array(MYSQLI_ASSOC);
                $hour_hash_str                                              = $url_log_detail['referrerWebSite'] . "-" . $url_log_detail['countryID'] . "-" . $url_log_detail['cityID'] . "-" . $url_log_detail['year'] . "-" . $url_log_detail['month'] . "-" . $url_log_detail['platform'];
                $hashKey                                                    = $this->makeHAsh($hour_hash_str);
                $stat_visitor_info_traffic_web[$hashKey]['hashKey']         = $hashKey;
                $stat_visitor_info_traffic_web[$hashKey]['year']            = $url_log_detail['year'];
                $stat_visitor_info_traffic_web[$hashKey]['month']           = $url_log_detail['month'];
                $stat_visitor_info_traffic_web[$hashKey]['countryID']       = $url_log_detail['countryID'];
                $stat_visitor_info_traffic_web[$hashKey]['cityID']          = $url_log_detail['cityID'];
                $stat_visitor_info_traffic_web[$hashKey]['referrerWebSite'] = $url_log_detail['referrerWebSite'];
                $stat_visitor_info_traffic_web[$hashKey]['platform']        = $url_log_detail['platform'];
                $stat_visitor_info_traffic_web[$hashKey]['visitor']         = (isset($stat_visitor_info_traffic_web[$hashKey]['visitor']) ? $stat_visitor_info_traffic_web[$hashKey]['visitor'] : 0) + $url_log_detail['visitor'];
                $stat_visitor_info_traffic_web[$hashKey]['newVisitor']      = (isset($stat_visitor_info_traffic_web[$hashKey]['newVisitor']) ? $stat_visitor_info_traffic_web[$hashKey]['newVisitor'] : 0) + $url_log_detail['newVisitor'];
                $stat_visitor_info_traffic_web[$hashKey]['orderPlaced']     = (isset($stat_visitor_info_traffic_web[$hashKey]['orderPlaced']) ? $stat_visitor_info_traffic_web[$hashKey]['orderPlaced'] : 0) + $url_log_detail['orderPlaced'];
                $stat_visitor_info_traffic_web[$hashKey]['orderAmount']     = (isset($stat_visitor_info_traffic_web[$hashKey]['orderAmount']) ? $stat_visitor_info_traffic_web[$hashKey]['orderAmount'] : 0) + $url_log_detail['orderAmount'];
                $stat_visitor_info_traffic_web[$hashKey]['doneSignUp']      = (isset($stat_visitor_info_traffic_web[$hashKey]['doneSignUp']) ? $stat_visitor_info_traffic_web[$hashKey]['doneSignUp'] : 0) + $url_log_detail['doneSignUp'];
                $stat_visitor_info_traffic_web[$hashKey]['doneSubscribe']   = (isset($stat_visitor_info_traffic_web[$hashKey]['doneSubscribe']) ? $stat_visitor_info_traffic_web[$hashKey]['doneSubscribe'] : 0) + $url_log_detail['doneSubscribe'];
                $stat_visitor_info_traffic_web[$hashKey]['duration']        = (isset($stat_visitor_info_traffic_web[$hashKey]['duration']) ? $stat_visitor_info_traffic_web[$hashKey]['duration'] : 0) + $url_log_detail['duration'];
                $stat_visitor_info_traffic_web[$hashKey]['pageCount']       = (isset($stat_visitor_info_traffic_web[$hashKey]['pageCount']) ? $stat_visitor_info_traffic_web[$hashKey]['pageCount'] : 0) + $url_log_detail['pageCount'];
                $last_updated_traffic_ref_website                           = $url_log_detail['id'];
                unset($url_log_detail);
            }
            $res_url_log_details->free();
        }
        $last_updated_id     = $ObjLogModel->getLastUpdatedID('analytics_traffic_search_enginename_year');
        $res_url_log_details = $ObjLogModel->getUlrLogDetailsYear($last_updated_id, 'stat_info_traffic_search_enginename', 20000);
        $visitCount          = $res_url_log_details->num_rows;
        if ($visitCount > 0) {
            $stat_visitor_info_traffic_se = array();
            for ($i = 0; $i < $visitCount; $i++) {
                $url_log_detail                                             = $res_url_log_details->fetch_array(MYSQLI_ASSOC);
                $hour_hash_str                                              = $url_log_detail['searchEngineName'] . "-" . $url_log_detail['countryID'] . "-" . $url_log_detail['cityID'] . "-" . $url_log_detail['year'] . "-" . $url_log_detail['month'] . "-" . $url_log_detail['platform'];
                $hashKey                                                    = $this->makeHAsh($hour_hash_str);
                $stat_visitor_info_traffic_se[$hashKey]['hashKey']          = $hashKey;
                $stat_visitor_info_traffic_se[$hashKey]['year']             = $url_log_detail['year'];
                $stat_visitor_info_traffic_se[$hashKey]['month']            = $url_log_detail['month'];
                $stat_visitor_info_traffic_se[$hashKey]['countryID']        = $url_log_detail['countryID'];
                $stat_visitor_info_traffic_se[$hashKey]['cityID']           = $url_log_detail['cityID'];
                $stat_visitor_info_traffic_se[$hashKey]['searchEngineName'] = $url_log_detail['searchEngineName'];
                $stat_visitor_info_traffic_se[$hashKey]['platform']         = $url_log_detail['platform'];
                $stat_visitor_info_traffic_se[$hashKey]['visitor']          = (isset($stat_visitor_info_traffic_se[$hashKey]['visitor']) ? $stat_visitor_info_traffic_se[$hashKey]['visitor'] : 0) + $url_log_detail['visitor'];
                $stat_visitor_info_traffic_se[$hashKey]['newVisitor']       = (isset($stat_visitor_info_traffic_se[$hashKey]['newVisitor']) ? $stat_visitor_info_traffic_se[$hashKey]['newVisitor'] : 0) + $url_log_detail['newVisitor'];
                $stat_visitor_info_traffic_se[$hashKey]['orderPlaced']      = (isset($stat_visitor_info_traffic_se[$hashKey]['orderPlaced']) ? $stat_visitor_info_traffic_se[$hashKey]['orderPlaced'] : 0) + $url_log_detail['orderPlaced'];
                $stat_visitor_info_traffic_se[$hashKey]['orderAmount']      = (isset($stat_visitor_info_traffic_se[$hashKey]['orderAmount']) ? $stat_visitor_info_traffic_se[$hashKey]['orderAmount'] : 0) + $url_log_detail['orderAmount'];
                $stat_visitor_info_traffic_se[$hashKey]['doneSignUp']       = (isset($stat_visitor_info_traffic_se[$hashKey]['doneSignUp']) ? $stat_visitor_info_traffic_se[$hashKey]['doneSignUp'] : 0) + $url_log_detail['doneSignUp'];
                $stat_visitor_info_traffic_se[$hashKey]['doneSubscribe']    = (isset($stat_visitor_info_traffic_se[$hashKey]['doneSubscribe']) ? $stat_visitor_info_traffic_se[$hashKey]['doneSubscribe'] : 0) + $url_log_detail['doneSubscribe'];
                $stat_visitor_info_traffic_se[$hashKey]['duration']         = (isset($stat_visitor_info_traffic_se[$hashKey]['duration']) ? $stat_visitor_info_traffic_se[$hashKey]['duration'] : 0) + $url_log_detail['duration'];
                $stat_visitor_info_traffic_se[$hashKey]['pageCount']        = (isset($stat_visitor_info_traffic_se[$hashKey]['pageCount']) ? $stat_visitor_info_traffic_se[$hashKey]['pageCount'] : 0) + $url_log_detail['pageCount'];
                $last_updated_traffic_search_enginename                     = $url_log_detail['id'];
                unset($url_log_detail);
            }
            $res_url_log_details->free();
        }
        $last_updated_id     = $ObjLogModel->getLastUpdatedID('analytics_traffic_search_keyword_year');
        $res_url_log_details = $ObjLogModel->getUlrLogDetailsYear($last_updated_id, 'stat_info_traffic_search_keyword', 20000);
        $visitCount          = $res_url_log_details->num_rows;
        if ($visitCount > 0) {
            $stat_visitor_info_traffic_sk = array();
            for ($i = 0; $i < $visitCount; $i++) {
                $url_log_detail                                          = $res_url_log_details->fetch_array(MYSQLI_ASSOC);
                $hour_hash_str                                           = $url_log_detail['searchKeyWord'] . "-" . $url_log_detail['countryID'] . "-" . $url_log_detail['cityID'] . "-" . $url_log_detail['year'] . "-" . $url_log_detail['month'] . "-" . $url_log_detail['platform'];
                $hashKey                                                 = $this->makeHAsh($hour_hash_str);
                $stat_visitor_info_traffic_sk[$hashKey]['hashKey']       = $hashKey;
                $stat_visitor_info_traffic_sk[$hashKey]['year']          = $url_log_detail['year'];
                $stat_visitor_info_traffic_sk[$hashKey]['month']         = $url_log_detail['month'];
                $stat_visitor_info_traffic_sk[$hashKey]['countryID']     = $url_log_detail['countryID'];
                $stat_visitor_info_traffic_sk[$hashKey]['cityID']        = $url_log_detail['cityID'];
                $stat_visitor_info_traffic_sk[$hashKey]['searchKeyWord'] = $url_log_detail['searchKeyWord'];
                $stat_visitor_info_traffic_sk[$hashKey]['platform']      = $url_log_detail['platform'];
                $stat_visitor_info_traffic_sk[$hashKey]['visitor']       = (isset($stat_visitor_info_traffic_sk[$hashKey]['visitor']) ? $stat_visitor_info_traffic_sk[$hashKey]['visitor'] : 0) + $url_log_detail['visitor'];
                $stat_visitor_info_traffic_sk[$hashKey]['newVisitor']    = (isset($stat_visitor_info_traffic_sk[$hashKey]['newVisitor']) ? $stat_visitor_info_traffic_sk[$hashKey]['newVisitor'] : 0) + $url_log_detail['newVisitor'];
                $stat_visitor_info_traffic_sk[$hashKey]['orderPlaced']   = (isset($stat_visitor_info_traffic_sk[$hashKey]['orderPlaced']) ? $stat_visitor_info_traffic_sk[$hashKey]['orderPlaced'] : 0) + $url_log_detail['orderPlaced'];
                $stat_visitor_info_traffic_sk[$hashKey]['orderAmount']   = (isset($stat_visitor_info_traffic_sk[$hashKey]['orderAmount']) ? $stat_visitor_info_traffic_sk[$hashKey]['orderAmount'] : 0) + $url_log_detail['orderAmount'];
                $stat_visitor_info_traffic_sk[$hashKey]['doneSignUp']    = (isset($stat_visitor_info_traffic_sk[$hashKey]['doneSignUp']) ? $stat_visitor_info_traffic_sk[$hashKey]['doneSignUp'] : 0) + $url_log_detail['doneSignUp'];
                $stat_visitor_info_traffic_sk[$hashKey]['doneSubscribe'] = (isset($stat_visitor_info_traffic_sk[$hashKey]['doneSubscribe']) ? $stat_visitor_info_traffic_sk[$hashKey]['doneSubscribe'] : 0) + $url_log_detail['doneSubscribe'];
                $stat_visitor_info_traffic_sk[$hashKey]['duration']      = (isset($stat_visitor_info_traffic_sk[$hashKey]['duration']) ? $stat_visitor_info_traffic_sk[$hashKey]['duration'] : 0) + $url_log_detail['duration'];
                $stat_visitor_info_traffic_sk[$hashKey]['pageCount']     = (isset($stat_visitor_info_traffic_sk[$hashKey]['pageCount']) ? $stat_visitor_info_traffic_sk[$hashKey]['pageCount'] : 0) + $url_log_detail['pageCount'];
                $last_updated_traffic_search_keyword                     = $url_log_detail['id'];
                unset($url_log_detail);
            }
            $res_url_log_details->free();
        }
        $last_updated_id     = $ObjLogModel->getLastUpdatedID('analytics_browser_bounce_year');
        $res_url_log_details = $ObjLogModel->getUlrLogDetailsYear($last_updated_id, 'stat_info_browser_bounce', 20000);
        $visitCount          = $res_url_log_details->num_rows;
        if ($visitCount > 0) {
            $stat_visitor_info_browser_bounce = array();
            for ($i = 0; $i < $visitCount; $i++) {
                $url_log_detail                                              = $res_url_log_details->fetch_array(MYSQLI_ASSOC);
                $hour_hash_str                                               = $url_log_detail['browserID'] . "-" . $url_log_detail['countryID'] . "-" . $url_log_detail['cityID'] . "-" . $url_log_detail['year'] . "-" . $url_log_detail['month'] . "-" . $url_log_detail['platform'];
                $hashKey                                                     = $this->makeHAsh($hour_hash_str);
                $stat_visitor_info_browser_bounce[$hashKey]['hashKey']       = $hashKey;
                $stat_visitor_info_browser_bounce[$hashKey]['year']          = $url_log_detail['year'];
                $stat_visitor_info_browser_bounce[$hashKey]['month']         = $url_log_detail['month'];
                $stat_visitor_info_browser_bounce[$hashKey]['countryID']     = $url_log_detail['countryID'];
                $stat_visitor_info_browser_bounce[$hashKey]['cityID']        = $url_log_detail['cityID'];
                $stat_visitor_info_browser_bounce[$hashKey]['browserID']     = $url_log_detail['browserID'];
                $stat_visitor_info_browser_bounce[$hashKey]['platform']      = $url_log_detail['platform'];
                $stat_visitor_info_browser_bounce[$hashKey]['visitor']       = (isset($stat_visitor_info_browser_bounce[$hashKey]['visitor']) ? $stat_visitor_info_browser_bounce[$hashKey]['visitor'] : 0) + $url_log_detail['visitor'];
                $stat_visitor_info_browser_bounce[$hashKey]['bounceVisitor'] = (isset($stat_visitor_info_browser_bounce[$hashKey]['bounceVisitor']) ? $stat_visitor_info_browser_bounce[$hashKey]['bounceVisitor'] : 0) + $url_log_detail['bounceVisitor'];
                $last_updated_browser_bounce                                 = $url_log_detail['id'];
                unset($url_log_detail);
            }
            $res_url_log_details->free();
        }
        $last_updated_id     = $ObjLogModel->getLastUpdatedID('analytics_os_bounce_year');
        $res_url_log_details = $ObjLogModel->getUlrLogDetailsYear($last_updated_id, 'stat_info_os_bounce', 20000);
        $visitCount          = $res_url_log_details->num_rows;
        if ($visitCount > 0) {
            $stat_visitor_info_os_bounce = array();
            for ($i = 0; $i < $visitCount; $i++) {
                $url_log_detail                                         = $res_url_log_details->fetch_array(MYSQLI_ASSOC);
                $hour_hash_str                                          = $url_log_detail['osID'] . "-" . $url_log_detail['countryID'] . "-" . $url_log_detail['cityID'] . "-" . $url_log_detail['year'] . "-" . $url_log_detail['month'] . "-" . $url_log_detail['platform'];
                $hashKey                                                = $this->makeHAsh($hour_hash_str);
                $stat_visitor_info_os_bounce[$hashKey]['hashKey']       = $hashKey;
                $stat_visitor_info_os_bounce[$hashKey]['year']          = $url_log_detail['year'];
                $stat_visitor_info_os_bounce[$hashKey]['month']         = $url_log_detail['month'];
                $stat_visitor_info_os_bounce[$hashKey]['countryID']     = $url_log_detail['countryID'];
                $stat_visitor_info_os_bounce[$hashKey]['cityID']        = $url_log_detail['cityID'];
                $stat_visitor_info_os_bounce[$hashKey]['osID']          = $url_log_detail['osID'];
                $stat_visitor_info_os_bounce[$hashKey]['platform']      = $url_log_detail['platform'];
                $stat_visitor_info_os_bounce[$hashKey]['visitor']       = (isset($stat_visitor_info_os_bounce[$hashKey]['visitor']) ? $stat_visitor_info_os_bounce[$hashKey]['visitor'] : 0) + $url_log_detail['visitor'];
                $stat_visitor_info_os_bounce[$hashKey]['bounceVisitor'] = (isset($stat_visitor_info_os_bounce[$hashKey]['bounceVisitor']) ?: 0) + $url_log_detail['bounceVisitor'];
                $last_updated_os_bounce                                 = $url_log_detail['id'];
                unset($url_log_detail);
            }
            $res_url_log_details->free();
        }
        $last_updated_id     = $ObjLogModel->getLastUpdatedID('analytics_page_bounce_year');
        $res_url_log_details = $ObjLogModel->getUlrLogDetailsYear($last_updated_id, 'stat_info_page_bounce', 20000);
        $visitCount          = $res_url_log_details->num_rows;
        if ($visitCount > 0) {
            $stat_visitor_info_page_bounce = array();
            for ($i = 0; $i < $visitCount; $i++) {
                $url_log_detail                                           = $res_url_log_details->fetch_array(MYSQLI_ASSOC);
                $hour_hash_str                                            = $url_log_detail['pageID'] . "-" . $url_log_detail['countryID'] . "-" . $url_log_detail['cityID'] . "-" . $url_log_detail['year'] . "-" . $url_log_detail['month'] . "-" . $url_log_detail['platform'];
                $hashKey                                                  = $this->makeHAsh($hour_hash_str);
                $stat_visitor_info_page_bounce[$hashKey]['hashKey']       = $hashKey;
                $stat_visitor_info_page_bounce[$hashKey]['year']          = $url_log_detail['year'];
                $stat_visitor_info_page_bounce[$hashKey]['month']         = $url_log_detail['month'];
                $stat_visitor_info_page_bounce[$hashKey]['countryID']     = $url_log_detail['countryID'];
                $stat_visitor_info_page_bounce[$hashKey]['cityID']        = $url_log_detail['cityID'];
                $stat_visitor_info_page_bounce[$hashKey]['pageID']        = $url_log_detail['pageID'];
                $stat_visitor_info_page_bounce[$hashKey]['platform']      = $url_log_detail['platform'];
                $stat_visitor_info_page_bounce[$hashKey]['visitor']       = (isset($stat_visitor_info_page_bounce[$hashKey]['visitor']) ? $stat_visitor_info_page_bounce[$hashKey]['visitor'] : 0) + $url_log_detail['visitor'];
                $stat_visitor_info_page_bounce[$hashKey]['bounceVisitor'] = (isset($stat_visitor_info_page_bounce[$hashKey]['bounceVisitor']) ? $stat_visitor_info_page_bounce[$hashKey]['bounceVisitor'] : 0) + $url_log_detail['bounceVisitor'];
                $last_updated_page_bounce                                 = $url_log_detail['id'];
                unset($url_log_detail);
            }
            $res_url_log_details->free();
        }
        $last_updated_id     = $ObjLogModel->getLastUpdatedID('analytics_traffic_bounce_year');
        $res_url_log_details = $ObjLogModel->getUlrLogDetailsYear($last_updated_id, 'stat_info_traffic_bounce', 20000);
        $visitCount          = $res_url_log_details->num_rows;
        if ($visitCount > 0) {
            $stat_visitor_info_traffic_bounce = array();
            for ($i = 0; $i < $visitCount; $i++) {
                $url_log_detail                                                = $res_url_log_details->fetch_array(MYSQLI_ASSOC);
                $hour_hash_str                                                 = $url_log_detail['referrerWebSite'] . "-" . $url_log_detail['referrerDetails'] . "-" . $url_log_detail['referrerType'] . "-" . $url_log_detail['countryID'] . "-" . $url_log_detail['cityID'] . "-" . $url_log_detail['year'] . "-" . $url_log_detail['month'] . "-" . $url_log_detail['platform'];
                $hashKey                                                       = $this->makeHAsh($hour_hash_str);
                $stat_visitor_info_traffic_bounce[$hashKey]['hashKey']         = $hashKey;
                $stat_visitor_info_traffic_bounce[$hashKey]['year']            = $url_log_detail['year'];
                $stat_visitor_info_traffic_bounce[$hashKey]['month']           = $url_log_detail['month'];
                $stat_visitor_info_traffic_bounce[$hashKey]['countryID']       = $url_log_detail['countryID'];
                $stat_visitor_info_traffic_bounce[$hashKey]['cityID']          = $url_log_detail['cityID'];
                $stat_visitor_info_traffic_bounce[$hashKey]['referrerType']    = $url_log_detail['referrerType'];
                $stat_visitor_info_traffic_bounce[$hashKey]['referrerDetails'] = $url_log_detail['referrerDetails'];
                $stat_visitor_info_traffic_bounce[$hashKey]['referrerWebSite'] = $url_log_detail['referrerWebSite'];
                $stat_visitor_info_traffic_bounce[$hashKey]['platform']        = $url_log_detail['platform'];
                $stat_visitor_info_traffic_bounce[$hashKey]['visitor']         = (isset($stat_visitor_info_traffic_bounce[$hashKey]['visitor']) ? $stat_visitor_info_traffic_bounce[$hashKey]['visitor'] : 0) + $url_log_detail['visitor'];
                $stat_visitor_info_traffic_bounce[$hashKey]['bounceVisitor']   = (isset($stat_visitor_info_traffic_bounce[$hashKey]['bounceVisitor']) ? $stat_visitor_info_traffic_bounce[$hashKey]['bounceVisitor'] : 0) + $url_log_detail['bounceVisitor'];
                $last_updated_traffic_bounce                                   = $url_log_detail['id'];
                unset($url_log_detail);
            }
            $res_url_log_details->free();
        }
        //echo '<pre>';print_r($stat_visitor_info_traffic_bounce);
        if (isset($stat_visitor_info_location) && count($stat_visitor_info_location) > 0) {
            $count          = count($stat_visitor_info_location);
            $split_up_array = array_chunk($stat_visitor_info_location, 500, true);
            unset($stat_visitor_info_location);
            if (count($split_up_array) > 0) {
                foreach ($split_up_array as $key => $value) {
                    $ObjLogModel->logLocationDetailsYear($value);
                }
                unset($split_up_array);
            }
            $ObjLogModel->saveCronExicution($count, $last_updated_location, 'analytics_location_year');
            echo "<pre><br> stat_visitor_info_location Reduced .......";
        }
        if (isset($stat_visitor_info_hour) && count($stat_visitor_info_hour) > 0) {
            $count          = count($stat_visitor_info_hour);
            $split_up_array = array_chunk($stat_visitor_info_hour, 500, true);
            unset($stat_visitor_info_hour);
            if (count($split_up_array) > 0) {
                foreach ($split_up_array as $key => $value) {
                    $ObjLogModel->logHourDetailsYear($value);
                }
                unset($split_up_array);
            }
            $ObjLogModel->saveCronExicution($count, $last_updated_hour, 'analytics_hour_year');
            echo "<pre><br> stat_visitor_info_hour Reduced .......";
        }
        if (isset($stat_visitor_info_browser) && count($stat_visitor_info_browser) > 0) {
            $count          = count($stat_visitor_info_browser);
            $split_up_array = array_chunk($stat_visitor_info_browser, 500, true);
            unset($stat_visitor_info_browser);
            if (count($split_up_array) > 0) {
                foreach ($split_up_array as $key => $value) {
                    $ObjLogModel->logBrowserDetailsYear($value);
                }
                unset($split_up_array);
            }
            $ObjLogModel->saveCronExicution($count, $last_updated_browser, 'analytics_browser_year');
            echo "<pre><br> stat_visitor_info_browser Reduced .......";
        }
        if (isset($stat_visitor_info_direct_traffic) && count($stat_visitor_info_direct_traffic) > 0) {
            $count          = count($stat_visitor_info_direct_traffic);
            $split_up_array = array_chunk($stat_visitor_info_direct_traffic, 500, true);
            unset($stat_visitor_info_direct_traffic);
            if (count($split_up_array) > 0) {
                foreach ($split_up_array as $key => $value) {
                    $ObjLogModel->logDirectTrafficDetailsYear($value);
                }
                unset($split_up_array);
            }
            $ObjLogModel->saveCronExicution($count, $last_updated_direct_traffic, 'analytics_direct_traffic_year');
            echo "<pre><br> stat_visitor_info_direct_traffic Reduced .......";
        }
        if (isset($stat_visitor_info_traffic) && count($stat_visitor_info_traffic) > 0) {
            $count          = count($stat_visitor_info_traffic);
            $split_up_array = array_chunk($stat_visitor_info_traffic, 500, true);
            unset($stat_visitor_info_traffic);
            if (count($split_up_array) > 0) {
                foreach ($split_up_array as $key => $value) {
                    $ObjLogModel->logTrafficDetailsYear($value);
                }
                unset($split_up_array);
            }
            $ObjLogModel->saveCronExicution($count, $last_updated_traffic, 'analytics_traffic_year');
            echo "<pre><br> stat_visitor_info_traffic Reduced .......";
        }
        if (isset($stat_visitor_info_traffic_web) && count($stat_visitor_info_traffic_web) > 0) {
            $count          = count($stat_visitor_info_traffic_web);
            $split_up_array = array_chunk($stat_visitor_info_traffic_web, 500, true);
            unset($stat_visitor_info_traffic_web);
            if (count($split_up_array) > 0) {
                foreach ($split_up_array as $key => $value) {
                    $ObjLogModel->logRefWebSiteTrafficDetailsYear($value);
                }
                unset($split_up_array);
            }
            $ObjLogModel->saveCronExicution($count, $last_updated_traffic_ref_website, 'analytics_traffic_ref_website_year');
            echo "<pre><br> stat_visitor_info_traffic_web Reduced .......";
        }
        if (isset($stat_visitor_info_traffic_sk) && count($stat_visitor_info_traffic_sk) > 0) {
            $count          = count($stat_visitor_info_traffic_sk);
            $split_up_array = array_chunk($stat_visitor_info_traffic_sk, 500, true);
            unset($stat_visitor_info_traffic_sk);
            if (count($split_up_array) > 0) {
                foreach ($split_up_array as $key => $value) {
                    $ObjLogModel->logSearchKeywordTrafficDetailsYear($value);
                }
                unset($split_up_array);
            }
            $ObjLogModel->saveCronExicution($count, $last_updated_traffic_search_keyword, 'analytics_traffic_search_keyword_year');
            echo "<pre><br> stat_visitor_info_traffic_sk Reduced .......";
        }
        if (isset($stat_visitor_info_traffic_se) && count($stat_visitor_info_traffic_se) > 0) {
            $count          = count($stat_visitor_info_traffic_se);
            $split_up_array = array_chunk($stat_visitor_info_traffic_se, 500, true);
            unset($stat_visitor_info_traffic_se);
            if (count($split_up_array) > 0) {
                foreach ($split_up_array as $key => $value) {
                    $ObjLogModel->logSearchEnginenameTrafficDetailsYear($value);
                }
                unset($split_up_array);
            }
            $ObjLogModel->saveCronExicution($count, $last_updated_traffic_search_enginename, 'analytics_traffic_search_enginename_year');
            echo "<pre><br> stat_visitor_info_traffic_se Reduced .......";
        }
        if (isset($stat_visitor_info_browser_bounce) && count($stat_visitor_info_browser_bounce) > 0) {
            $count          = count($stat_visitor_info_browser_bounce);
            $split_up_array = array_chunk($stat_visitor_info_browser_bounce, 500, true);
            unset($stat_visitor_info_browser_bounce);
            if (count($split_up_array) > 0) {
                foreach ($split_up_array as $key => $value) {
                    $ObjLogModel->logBounceBrowserDetailsYear($value);
                }
                unset($split_up_array);
            }
            $ObjLogModel->saveCronExicution($count, $last_updated_browser_bounce, 'analytics_browser_bounce_year');
            echo "<pre><br> stat_visitor_info_browser_bounce Reduced .......";
        }
        if (isset($stat_visitor_info_os_bounce) && count($stat_visitor_info_os_bounce) > 0) {
            $count          = count($stat_visitor_info_os_bounce);
            $split_up_array = array_chunk($stat_visitor_info_os_bounce, 500, true);
            unset($stat_visitor_info_os_bounce);
            if (count($split_up_array) > 0) {
                foreach ($split_up_array as $key => $value) {
                    $ObjLogModel->logBounceOsDetailsYear($value);
                }
                unset($split_up_array);
            }
            $ObjLogModel->saveCronExicution($count, $last_updated_os_bounce, 'analytics_os_bounce_year');
            echo "<pre><br> stat_visitor_info_os_bounce Reduced .......";
        }
        if (isset($stat_visitor_info_page_bounce) && count($stat_visitor_info_page_bounce) > 0) {
            $count          = count($stat_visitor_info_page_bounce);
            $split_up_array = array_chunk($stat_visitor_info_page_bounce, 500, true);
            unset($stat_visitor_info_page_bounce);
            if (count($split_up_array) > 0) {
                foreach ($split_up_array as $key => $value) {
                    $ObjLogModel->logBouncePageDetailsYear($value);
                }
                unset($split_up_array);
            }
            $ObjLogModel->saveCronExicution($count, $last_updated_page_bounce, 'analytics_page_bounce_year');
            echo "<pre><br> stat_visitor_info_page_bounce Reduced .......";
        }
        if (isset($stat_visitor_info_traffic_bounce) && count($stat_visitor_info_traffic_bounce) > 0) {
            $count          = count($stat_visitor_info_traffic_bounce);
            $split_up_array = array_chunk($stat_visitor_info_traffic_bounce, 500, true);
            unset($stat_visitor_info_traffic_bounce);
            if (count($split_up_array) > 0) {
                foreach ($split_up_array as $key => $value) {
                    $ObjLogModel->logBounceTrafficDetailsYear($value);
                }
                unset($split_up_array);
            }
            $ObjLogModel->saveCronExicution($count, $last_updated_traffic_bounce, 'analytics_traffic_bounce_year');
            echo "<pre><br> stat_visitor_info_traffic_bounce Reduced .......";
        }
        echo "<pre><br>Cron Execution Completed .......<br/><br/><br>***********************************END***********************************";
    }
    //For testing only
    public function dummyAction() {
        $ObjLog = new AnalyticsModel();
        for ($i = 0; $i < 500; $i++) {
            $str = $this->generateRandomString();
            if ($j == 0) {
                $currentURL = "en/" . $str . ".htm";
                $pageName   = "Catalog";
                $pageID     = $ObjLog->addStatPage($currentURL, ucfirst($pageName));
                $j++;
            } else if ($j == 1) {
                $currentURL = "search/keyword=" . $str . "&amp;in=1";
                $pageName   = "CatalogSearch";
                $pageID     = $ObjLog->addStatPage($currentURL, ucfirst($pageName));
                $j++;
            } else {
                $currentURL = "" . $str . ".htm";
                $pageName   = "Product";
                $pageID     = $ObjLog->addStatPage($currentURL, ucfirst($pageName));
                $j++;
            }
            if ($j == 3)
                $j = 0;
        }
    }
    //For testing only
    public function generateRandomString($length = 10) {
        $characters   = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $randomString;
    }
    public function microtime_float() {
        list($msec, $sec) = explode(' ', microtime());
        $microtime = (float) $msec + (float) $sec;
        return $microtime;
    }
    //For testing purpose only
    public function deleteAllCampaignAction() {
        $settings['api_key']            = $this->getSettingValue('third_paty_mail_settings', 'campaign_api_key');
        $settings['api_key']            = $this->encryptDecrypt("decrypt", $settings['api_key']);
        $settings['user_name']          = $this->getSettingValue('third_paty_mail_settings', 'campaign_user_name');
        $settings['user_name']          = $this->encryptDecrypt("decrypt", $settings['user_name']);
        $settings['password']           = $this->getSettingValue('third_paty_mail_settings', 'campaign_password');
        $settings['password']           = $this->encryptDecrypt("decrypt", $settings['password']);
        $settings['campaign']           = $this->getSettingValue('third_paty_mail_settings', 'campaign_name');
        $settings['api_client_id']      = $this->getSettingValue('third_paty_mail_settings', 'campaign_client_id');
        $settings['api_client_id']      = $this->encryptDecrypt("decrypt", $settings['api_client_id']);
        $confirmationMail               = $this->getSettingValue('site_settings', 'global_notification_email');
        $settings['confirmation_email'] = $confirmationMail;
        try {
            $ObjCampaign = new Campaign($settings);
        }
        catch (Exception $e) {
            $msg = $e->getMessage();
            return "Error : " . $msg;
        }
        $res = $ObjCampaign->deleteAllCampaign();
    }
    //Create sitemap	
    public function createSitemapAction() {
        $this->setRedirect("/sitemap/generate");
    }
    public function updateCurrencyRatesAction() {
        $ObjCurrency               = new CurrencyModel();
        $resDefaultCurrencyDetails = $ObjCurrency->getDefaultCurrencyDetails();
        $currencyID                = $resDefaultCurrencyDetails['currencyID'];
        try {
            $ObjCurrency->updateCurrencyExchRateUsingAPI($currencyID);
            echo "updated";
        }
        catch (Exception $exc) {
            echo "error occured";
        }
    }
    //Check the permission to execute the cron
    private function checkPermission() {
        $systemIPAddress = $this->getIpAddress();
        $allowedIPs      = explode(',', $this->getSettingValue('security_settings', 'cron_execution_allowed_ips'));
        foreach ($allowedIPs as $index => $ip)
            $allowedIPs[$index] = trim($ip);
        if (!in_array($systemIPAddress, $allowedIPs)) {
            echo "You have no permission to execute the cron";
            exit;
        }
    }
    
    
    public function insertProductImagesAction() {
        $ObjExim = new EximModel();
        $folderName = $this->getRequestValue('foldername');
        if ($ObjExim->fn_get_image_cron_status() != 'locked')
            $ObjExim->fn_insert_images_cron($folderName);
    }
	public function userProfileAction() { 
		$ObjUserprofile 				= new UserprofileModel();

		 $params =   array(
			'ObjView'  =>  $this->ObjView
		);	
		$resCron   	= $ObjUserprofile->setCronForUserProfile($params);
		echo "<br>User Profile updated";
		exit;
	}
	public function updateProductDealAction() {
        $ObjProduct = new ProductModel();
        $cronResult = $ObjProduct->updateProductDeal();
		echo "<pre><br>Cron Execution Completed .......<br/><br/><br>***********************************END***********************************";
    }    

    public function getOrdersByNextToken($nextToken,$param)
    {
        $param['Action']           = 'ListOrdersByNextToken'; 
        $param['NextToken']        = $nextToken;
        $array = $this->signatureAndResponseOrders($param);
        $orders = $array['ListOrdersByNextTokenResult']['Orders']['Order'];
        $nextToken = $array['ListOrdersByNextTokenResult']['NextToken'];
        if(!empty($orders)){
           $this->processOrder($orders);
        } else {
             echo "No response for next token orders list";
        }
        if(!empty($nextToken)){
            $this->getOrdersByNextToken($nextToken,$param);
        }
    }
    public function processOrder($orders)
    {
         $ObjOrder = new OrderModel();
            $latestOrders = array();
            $orderitemsarray=array();
            $tempArray = array();
        $keyinc = 0;
        // check for multiple orders
        if(isset($orders['AmazonOrderId']) && $orders['AmazonOrderId']!=''){
            $tempArray = $orders;
            $orders = array(); 
            $orders[] = $tempArray;
        }
       foreach($orders as $key=>$order){
            // SKU manipulation to map the product //
           $orderitemsarray = $this->getorderDet($order['AmazonOrderId']);
          // $fSKU 			= $orderitemsarray['SellerSKU'];
           //$splitedSKU 	= explode('-',$fSKU);
          // $splitedSKU2	= substr($splitedSKU[1], 0, 2); 
        //   $productSKU 	= $splitedSKU[0].'-'.$splitedSKU2;
   // ITEMS ARRAY
        //   $sqlpdet  = "select * from dp_product_options where optionSKU='".$productSKU."' AND productOptionStatus='Active' and productOptionDefault='Yes'";
         //  $repdet                             = $ObjOrder->cronReadValue($sqlpdet);
          // if($repdet['productOptionID']>0){
               $latestOrders[$keyinc]['order'] = $order;
               $latestOrders[$keyinc]['items'] = $orderitemsarray;
               $keyinc++;
          // } else {
          //     echo "Not getting product details for ".$order['AmazonOrderId']." sku - ".$fSKU;
         //  }
        }
        $log = '';
        $ObjState = new StateModel();
        $languageIDs             			= $this->ObjView->languageIDs;
        foreach($latestOrders as $mwsorders){
            $mwsorder = $mwsorders['order'];
            $mwsorder['items'] = $mwsorders['items'];
            $order = $orderarray= array();            
            $order['promoID'] 					= 0;
            $order['orderPromoCode'] 			= '';
            $order['userCreditAmount'] 			= 0;
            $order['orderPaymentMethodName'] 	= 'Amazon';
            $order['paymentType'] 				= 'AUTH_CAPTURE';
            $order['paymentSettingsGroupID']    = '0';
            $order['userCheckoutEmail'] = $mwsorder['BuyerEmail'];
            $ShippingAddress = $mwsorder['ShippingAddress'];
            $fullname = explode(' ',$ShippingAddress['Name']);
            $firstname = isset($fullname[0])?$fullname[0]:'';
            $lastname = isset($fullname[1])?$fullname[1]:'';
            $countryCode 	= $ShippingAddress['CountryCode'];
            if($countryCode=='IN'){
                    $countryId = '99';
            }
            else{
                    $countryId = '0';
            }
            $stateName 	 	= $ShippingAddress['StateOrRegion']; 
            $ShippingAddress['AddressLine1'] = str_replace("'",'',$ShippingAddress['AddressLine1']);
            $ShippingAddress['AddressLine2'] = str_replace("'",'',$ShippingAddress['AddressLine2']);
            $countryStateID = $ObjState->getStateIDByName($stateName,$languageIDs,$countryId);
            $arrAddress = array(
                        'billingFirstName'  => trim(addslashes($firstname)),
                        'billingLastName'   => trim(addslashes($lastname)),
                        'billingAddress'    => trim(addslashes($ShippingAddress['AddressLine1'])),
                        'billingAddress1'   => trim(addslashes($ShippingAddress['AddressLine2'])),
                        'billingCity' 	    => trim(addslashes($ShippingAddress['City'])),
                        'billingProvince'   => '',
                        'billingZip' 	    => trim(addslashes($ShippingAddress['PostalCode'])),
                        'billingState' 	    => trim(addslashes((isset($countryStateID) ? $countryStateID : 0))),
                        'billingCountry'    => $countryId,
                        'billingPhone' 	    => trim(addslashes($ShippingAddress['Phone'])),
                        'billingEmail' 	    => trim(addslashes($mwsorder['BuyerEmail'])) ,
                        'billingDifferent'=>0
                );
            $arrAddress1 = array(
                        'shippingFname'     => trim(addslashes($firstname)),
                        'shippingLname'     => trim(addslashes($lastname)),
                        'shippingAddress'   => trim(addslashes($ShippingAddress['AddressLine1'])),
                        'shippingAddress1'  => trim(addslashes($ShippingAddress['AddressLine2'])),
                        'shippingCity' 	    => trim(addslashes($ShippingAddress['City'])),
                        'shippingProvince'  => '',
                        'shippingZip' 	    => trim(addslashes($ShippingAddress['PostalCode'])),
                        'shippingPhone' 	=> trim($ShippingAddress['Phone']),
                        'shippingStateID' 	=> trim((isset($countryStateID) ? $countryStateID : 0)),
                        'shippingCountryID' => $countryId,
                        
                );
            $order['billingAddress']            = $this->escape(serialize($arrAddress), FALSE, FALSE);
            $order['shippingDeliveryAddress']   = $this->escape(serialize($arrAddress1), FALSE, FALSE);
            $order['netpayOrderID'] 			= 0;
            $order['netpayPaymentType'] 		= '';
            $order['orderHold'] 				= 'No';
            $order['currencyID'] 				= $this->ObjView->_defaultCurrency;

            $order['userID'] 					= 0;

            $order['orderStatus'] = 'Process';
            $order['paymentStatus'] = 'Received';
            $order['dynamicOrderStatus'] = 'order-received';            
            $order['mPlaceOrderStatus'] = $mwsorder['OrderStatus'];

            $order['orderSource'] = 'amazon';
            //$order['mPlaceOrderID'] = $mwsorder['AmazonOrderId'];
            $tempitemArray = array();
        // check for multiple orders
         if(isset($mwsorder['items']['OrderItemId']) && $mwsorder['items']['OrderItemId']!='' ){
           //  $masterOrderID 	=	$ObjOrder->checkMPlaceOrderIdExist($mwsorder['AmazonOrderId'],'amazon');
           // if($masterOrderID=='')
           // {
           //     $log .= "<br />order created for mplaceid = ".$mwsorder['AmazonOrderId'];
           //     $orderarray = $this->setOrderArray($order,$mwsorder['items'],$mwsorders);
               // echo "<pre>";print_r($orderarray);exit;
           //     $ObjOrder->createOrder($orderarray);
           // } else {
                // $log .= "<br />order exists for mplaceid = ".$mwsorder['AmazonOrderId'];
           // }
             //NO MULTIPLE ITEMS IN ONE ORDER 
            $tempitemArray = $mwsorder['items'];
            $mwsorder['items'] = array(); 
            $mwsorder['items'][] = $tempitemArray;
        } //else {
          //  echo "Cann't fetch the details of Order item for mplaceid = ".$mwsorder['AmazonOrderId'];
       // }
           //NO MULTIPLE ITEMS IN ONE ORDER 
        foreach ($mwsorder['items'] as $orderitems){                   
            $masterOrderID 	=	$ObjOrder->checkMPlaceOrderIdExist($orderitems['OrderItemId'],'amazon');
            if($masterOrderID=='')
            {
                $orderarray = $this->setOrderArray($order,$orderitems,$mwsorders);
                //echo "<pre>";print_r($orderarray);
                if(!empty($orderarray)){
                    $log .= "<br />order created for mplaceid = ".$orderitems['OrderItemId'];
                    $ObjOrder->createOrder($orderarray);
                }
            }else {
                 $log .= "<br />order exists for mplaceid = ".$orderitems['OrderItemId'];
            }
        }
            
          
        }
        echo $log;
       exit; 
    }
    public function setOrderArray($order,$mwsorderitem,$mwsorder)
    {
        $ObjOrder = new OrderModel();
        $ObjUrl     		= new UrlrewriteModel();
        $cartcurrencyId = $this->ObjView->_defaultCurrency;
        $defaultCurrencyId = $this->ObjView->_defaultCurrency;
        $userCreditAmount = 0;
        $order['masterOrderQty'] = $mwsorderitem['QuantityOrdered'];
        $order['mPlaceOrderID'] = $mwsorderitem['OrderItemId'];
        $order['shippingAmount'] = $mwsorderitem['ShippingPrice']['Amount']+$mwsorderitem['ShippingTax']['Amount'];
        $order['orderTaxAmount'] = 0;//$mwsorderitem['ItemTax']['Amount'];
        $order['orderTotalAmount'] = $mwsorderitem['ShippingTax']['Amount'] 
                + $mwsorderitem['GiftWrapTax']['Amount'] 
                + $mwsorderitem['ShippingPrice']['Amount']
                + $mwsorderitem['GiftWrapPrice']['Amount']
                + $mwsorderitem['ItemPrice']['Amount']
                + $mwsorderitem['ItemTax']['Amount']
                - $mwsorderitem['ShippingDiscount']['Amount']
                - $mwsorderitem['PromotionDiscount']['Amount'];
        $order['orderSubtotal'] =$order['orderTotalAmount'];//$mwsorderitem['ItemPrice']['Amount'];
        $order['orderPromoDiscountAmount'] = $mwsorderitem['PromotionDiscount']['Amount'];
        $order['convertedMasterOrderSubTotalAmount'] = $this->ObjView->convertValueCustom($order['orderSubtotal'], $cartcurrencyId, $defaultCurrencyId);
        $order['convertedMasterOrderTotalAmount']    = $this->ObjView->convertValueCustom($order['orderTotalAmount'], $cartcurrencyId, $defaultCurrencyId);
        $order['convertedOrderPromoDiscountAmount']  = $this->ObjView->convertValueCustom($order['orderPromoDiscountAmount'], $cartcurrencyId, $defaultCurrencyId);
        $order['convertedOrderUserCreditAmount']     = $this->ObjView->convertValueCustom($userCreditAmount, $cartcurrencyId, $defaultCurrencyId);
        $order['orderCommissionAmount']     = 0;
        $order['orderOtherServiceCharge']   = 0;
        $order['orderPaymentGatewayCharge'] = 0;
        $business_id                        = 1;
        $order['businessPayment']           = $order['orderTotalAmount'];
        $order['convertedBusinessPayment']  = $this->ObjView->convertValueCustom($order['businessPayment'], $cartcurrencyId, $defaultCurrencyId);
            
        // TO DO
        $items = array();
	$serializedData = array();
					   
	$keyn=0;
        // SKU manipulation to map the product //
        $productSKU 			= '865865865';//$mwsorderitem['SellerSKU'];
        					
        //echo $productSKU;
        // ITEMS ARRAY
                $sqlpdet                            = "select * from dp_product_options where optionSKU='".$productSKU."' AND productOptionStatus='Active' and productOptionDefault='Yes'";
                $repdet                             = $ObjOrder->cronReadValue($sqlpdet);
		if($repdet['productOptionID']>0){
                    $sqldet                             = "select *,tax.taxRate 
                                                                                                from dp_products p 
                                                                                                left join dp_tax_rates tax 
                                                                                                        on (p.taxClassID =  tax.taxClassID) 
                                                                                                join dp_product_details pd 
                                                                                                        on (p.productID=pd.productID and pd.languageID='1') 
                                                                                                where 
                                                                                                        p.productID='".$repdet['productID']."'";
                $redet                              = $ObjOrder->cronReadValue($sqldet);
                $GST 								= round($redet['taxRate'],2);
                $items[$keyn]['productOptionID']    = $repdet['productOptionID'];
                $items[$keyn]['productID']          = $repdet['productID'];
                $items[$keyn]['orderItemPrice']     = $order['orderSubtotal'];//$mwsorderitem['ItemPrice']['Amount'];
                $items[$keyn]['actualPrice']        = $order['orderSubtotal'];//$mwsorderitem['ItemPrice']['Amount'];
                $items[$keyn]['orderItemQuantity']  = $mwsorderitem['QuantityOrdered'];
                $items[$keyn]['orderItemSubtotal']  = $order['orderSubtotal'];
                $items[$keyn]['productOptionName']  = $redet['productTitle'];
							
		$sqlUpd = "update dp_product_options set  soldQuantity = (( (CAST(soldQuantity AS  UNSIGNED INTEGER)) 
                                                                + ( CAST('" . $mwsorderitem['QuantityOrdered'] . "' AS  UNSIGNED INTEGER))  )) where productOptionID='".$repdet['productOptionID']."' and productID='".$repdet['productID']."'";

                $ObjOrder->cronSetQuery($sqlUpd);

                $sqlUpd = "update dp_products set productSoldQuantity  = (( (CAST(productSoldQuantity AS  UNSIGNED INTEGER)) 
                                                                + ( CAST('" . $mwsorderitem['QuantityOrdered'] . "' AS  UNSIGNED INTEGER))  )) where productID='".$redet['productID']."'";                  


                $ObjOrder->cronSetQuery($sqlUpd);
							
                $serializedData['itemDetails']['user']['productOptionName']        = $redet['productTitle'];
                $serializedData['itemDetails']['user']['productTitle']             = $redet['productTitle'];
                $serializedData['itemDetails']['admin']['productOptionName']       = $redet['productTitle'];
                $serializedData['itemDetails']['admin']['productTitle']            = $redet['productTitle'];
                $serializedData['productOptionName']        = $redet['productTitle'];
                $serializedData['productTitle']             = $redet['productTitle'];
                $serializedData['imagePath']                = $redet['productImage'];
                $serializedData['orderCommissionAmount']    = 0;
                $serializedData['orderOtherServiceCharge']  = 0;
                $serializedData['promoCode']                = 0;
                $serializedData['orderPromoDiscountAmount'] =  $mwsorderitem['PromotionDiscount']['Amount'];
                $serializedData['orderItemQuantity']        = $mwsorderitem['QuantityOrdered'];
                $serializedData['orderItemSubtotal']        = number_format($order['orderSubtotal'], 5, '.', '');
                $serializedData['orderItemTotal']           = number_format($order['orderTotalAmount'], 5, '.', '');
                $serializedData['unitPrice']                = number_format($order['orderSubtotal'], 5, '.', '');
                $serializedData['productCommissionRate']    = 0;
                $serializedData['businessKey']              = 'pcj-jewelleries';
                $serializedData['productImage']             = $redet['productImage'];
                $serializedData['productDefaultCurrency']   = 1;
                $serializedData['orderTaxAmount']           = 0;//$mwsorderitem['ItemTax']['Amount'];
                $serializedData['shippingAmount']           = $order['shippingAmount'];
                $serializedData['productDispatchTime']      = $redet['productDispatchTime'];
                $serializedData['measurementLength']        = 0;
                $serializedData['measurementWeight']        = 0;
                $serializedData['packageWeight']            = 0;
                $serializedData['packageLength']            = 0;
                $serializedData['packageWidth']             = 0;
                $serializedData['packageHeight']            = 0;
							
                $resUrl                                     = $ObjUrl->getRequestPathByIdPath(1, 'product' . '/' . $redet['productID'] . '/');
                $serializedData['productURL']               = $resUrl['requestPath'];
                $serializedData['productSKU']               = $productSKU; //$fItems->sku;
                $serializedData['GST']               		= $GST;
                $serializedData['combinationValues']        = array();
               // $serializedData['customOptionValues']       = $custOptionVal;
                $postData['combinationHash'] 				= '';
                $postData['optionsHash']                    = '';
                $serializedData['combinationHash']          = '';
                $postData['promoCode']                      = '';

                $items[$keyn]['itemDetails']                = serialize($serializedData);
					   
                $order['items'][$business_id]['subItem']       = $items;
                $order['items'][$business_id]['orderTaxAmount']       = 0;//$mwsorderitem['ItemTax']['Amount'];
                $order['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['subTotal'] = $this->ObjView->convertValueCustom($order['orderSubtotal'], $cartcurrencyId, $defaultCurrencyId);                
                $order['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['serviceCharge'] = $this->ObjView->convertValueCustom($order['orderOtherServiceCharge'], $cartcurrencyId, $defaultCurrencyId);                
                $order['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['commission'] = $this->ObjView->convertValueCustom($order['orderCommissionAmount'], $cartcurrencyId, $defaultCurrencyId);                
                $order['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['ccCharge'] = $this->ObjView->convertValueCustom($order['orderPaymentGatewayCharge'], $cartcurrencyId, $defaultCurrencyId);               
                $order['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['tax'] = $this->ObjView->convertValueCustom($order['orderTaxAmount'], $cartcurrencyId, $defaultCurrencyId);                
                $order['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['shippingAmount'] = $this->ObjView->convertValueCustom($order['shippingAmount'], $cartcurrencyId, $defaultCurrencyId);                
                $order['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['businessPayment'] = $this->ObjView->convertValueCustom($order['businessPayment'], $cartcurrencyId, $defaultCurrencyId);                
                $order['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['orderTotalAmount'] = $this->ObjView->convertValueCustom($order['orderTotalAmount'], $cartcurrencyId, $defaultCurrencyId);
                $order['items'][$business_id]['orderBasedUnserializedData']['MarketPlaceDetails']['admin']	= (array)$mwsorder;
						
                return $order;
                } else {
                    echo "Not getting product details for ".$order['AmazonOrderId']." sku - ".$fSKU;
                    return array();
                }					
                
    }
    public function updateMplaceOrder($orders,$nextToken='' )
    {
        $ObjOrder = new OrderModel();
        $tempArray = $tempitemArray = array();
        $mwsorder['items'] = array();
        // check for multiple orders
        if(isset($orders['AmazonOrderId']) && $orders['AmazonOrderId']!=''){
            $tempArray = $orders;
            $orders = array(); 
            $orders[] = $tempArray;
        }
        foreach($orders as $key=>$mwsorder)
        {
            $mwsorder['items'] = $this->getorderDet($mwsorder['AmazonOrderId']);
            if(isset($mwsorder['items']['OrderItemId']) && $mwsorder['items']['OrderItemId']!='' ){
           
             //NO MULTIPLE ITEMS IN ONE ORDER 
            $tempitemArray = $mwsorder['items'];
            $mwsorder['items'] = array(); 
            $mwsorder['items'][] = $tempitemArray;
            }
            foreach ($mwsorder['items'] as $orderitems){      
                 $masterOrderID 	=	$ObjOrder->checkMPlaceOrderIdExist($orderitems['OrderItemId'],'amazon');
               // $masterOrderID 	=	$ObjOrder->checkMPlaceOrderIdExist($mwsorder['AmazonOrderId'],'amazon');
                 $getcurrentstatus = $ObjOrder->getMPlaceOrderStatus($orderitems['OrderItemId'],'amazon');
                if($masterOrderID!=='')
                {
                    if($mwsorder['OrderStatus']=='Shipped')
                        $dynamicOrderStatus = 'order-shipped';
                    else if($mwsorder['OrderStatus']=='Canceled')
                        $dynamicOrderStatus = 'cancelled';
                    else if($mwsorder['OrderStatus']=='Unfulfillable')
                        $dynamicOrderStatus = 'cancelled';
                    else if($mwsorder['OrderStatus']=='PendingAvailability')
                        $dynamicOrderStatus = 'pending';                    
                    if($getcurrentstatus!=$dynamicOrderStatus){
                        echo "<br/> Order status changed for mplaceorder ".$orderitems['OrderItemId']." (".$masterOrderID.")to ".$mwsorder['OrderStatus'];
                        $ObjOrder->changeMWSMplaceOrderStatus($mwsorder['OrderStatus'],$dynamicOrderStatus,$masterOrderID);
                    }
                }
            }
        }
        // NEXT TOKEN
         if(!empty($nextToken)){
            $this->updateMWSOrdersAction($nextToken);
        }
    }

    public function scheduletrackingAction()
    {
        //SCHEDULE REPORT FOR EASY SHIP DATA
        $param = array();        
        $param['Action']           = 'ManageReportSchedule';        
        $param['ReportType'] = '_GET_EASYSHIP_PICKEDUP_'; 
        $param['Schedule'] = '_15_MINUTES_';
        $response = $this->signatureAndResponseReports($param);

        $parsed_xml = simplexml_load_string($response);
        $array = json_decode(json_encode($parsed_xml), TRUE);
        echo "<pre>";print_r($array);exit;
    }
    public function processMiniInfoAction() {
        $ObjExim                                = new EximModel();
        $ObjCustom                              = new CustomOptionModel(); 
        $languageIDs                            = $this->ObjView->languageIDs;   
        $languageIDs['AllList']                 = $languageIDs['All'];
        $languageIDsTemp                        = $languageIDs;
        $languageIDsTemp['Current']             = $languageIDs['Default'];
        
        $ObjProduct                             = new ProductModel();
        $ObjCosy                             	= new CosyModel();
        $handleCsv  = '';
        $fileExists = 0;
        //$siteUrl                = $this->getSettingValue('site_settings', 'global_http_url');
        $siteUrl                = 'https://www.findyourmini.ae/';
		
        $siteUrl                = rtrim($siteUrl, "/");
        $fs_data                = scandir(__DIR_EXIM . '/mini-profile/');

        if (!empty($fs_data)) {                    
            foreach ($fs_data as $file) {
                if (strtolower(substr($file, -4)) == ".csv" || strtolower(substr($file, -4))=='xlsx') {
                    $handleCsv     = $siteUrl.'/public/uploads/exim/mini-profile/'.$file;//fopen(__CORE_PUBLIC_PATH . "/uploads/exim/autoline/".$file, "r");
                    $fileExists    = 1;
                }                           
            }
        }               
        if($fileExists>0) {		
                        require_once __ROOT_PATH."/vendor/phpoffice/phpexcel/Classes/PHPExcel.php";
                        //$tmpfname = "test.xlsx";
                        //$url = "http://spreadsheetpage.com/downloads/xl/worksheet%20functions.xlsx";                
                        $url            = $handleCsv;                        
                        $filecontent    = file_get_contents($url);
                        $tmpfname       = tempnam(sys_get_temp_dir(),"tmpxls");
                        file_put_contents($tmpfname,$filecontent);

                        $excelReader = PHPExcel_IOFactory::createReaderForFile($tmpfname);
                        $excelObj    = $excelReader->load($tmpfname);
                        $worksheet   = $excelObj->getSheet(0);
                        $lastRow     = $worksheet->getHighestRow();

                        $bonnetCodes   = array();
                        $stripeCodes   = array();
			$counter     = 0;      
                        $prodIDs     = array();			
                        $prodCustArr = array();
                        $combAttr    = array();

                        for ($row = 2; $row <= $lastRow; $row++) { 
                                $params                 =   array();
                                $params['vehicle']      =   $worksheet->getCell('A'.$row)->getValue();
                                $params['variant']      =   $worksheet->getCell('B'.$row)->getValue();
                                $params['bonnetStripes']=   $worksheet->getCell('D'.$row)->getValue();
                                $params['bonnetDesc']   =   $worksheet->getCell('E'.$row)->getValue();
                                $params['roofcapcode']  =   $worksheet->getCell('F'.$row)->getValue();
                                $params['roofDesc']     =   $worksheet->getCell('G'.$row)->getValue();
                                //echo "<pre>";print_r($params);exit;
                                

								if(!empty($params['bonnetStripes'])) {
									$bonnetCodes[] =  $params['bonnetStripes'];
								}
								if(!empty($params['roofcapcode'])) {
									$stripeCodes[] =  $params['roofcapcode'];
								}
								
                                $params['sku']  =   $params['variant']."-";                                
                                $productExists  =   $ObjProduct->isProductSkuAlreadyExists($params['sku'],  NULL, '', '','Yes','Yes');
                                $productID      =   !empty($productExists) ? $productExists['productID']:0;
                                 
                                if($productID>0) {
                                    $prodIDs[]   = $productID;   
                                    //save custom options                                 
                                    $custValues  = array("Stripe","Roof");
                                    $paramCustArray = array();
                                    $paramVariantArray = array();
                                    $paramscosy        = array();
                                    $addCustOptVar     = 0;
                                    $tempVar           = '';
                                    foreach($custValues as $keyc=>$cust) {
                                        $paramCustArray['customOptionName'] = $cust;
                                        $paramCustArray['isGlobal']         = 1;
                                        $checkGlobal = $ObjCustom->checkProductCustomOption($languageIDsTemp,$paramCustArray['customOptionName'],$productID);
                                        $customOptionID = 0; 
                                        $custInsArr  = array();
                                        $processOption = 0;
                                        if($params['bonnetDesc']!='' && $paramCustArray['customOptionName']=='Stripe') {
                                            $processOption = 1;
                                        } elseif($paramCustArray['customOptionName']=='Roof' && !empty($params['roofDesc'])) {
                                            $processOption = 1;
                                        }
                                        if($processOption>0) {
                                            $custInsArr['customOptionName'] = $paramCustArray['customOptionName'];
                                            $custInsArr['inputType']        = 'select';
                                            $custInsArr['validateRuleRequired'] = 'Yes';
                                            $custInsArr['validationMessage'] = $this->getLanguageValue("errPleaseSelect")." ".$paramCustArray['customOptionName'];
                                            $custInsArr['status'] = 'A';//($params['status']=='S' && $params['availcode']=='A')?'A':'I';
                                            $custInsArr['productID'] = $productID;
                                            if(!empty($checkGlobal)) {
                                                $customOptionID = $checkGlobal['customOptionID'];
                                                $custInsArr['customOptionID']   = $customOptionID;
                                            } else {
                                                $customOptionID = 0;                                            
                                                $custInsArr['customOptionID']   = $customOptionID;  
                                                $customOptionID = $ObjCustom->saveCustomOptions($languageIDsTemp,$custInsArr,'Yes','No');
                                                $custInsArr['customOptionID']   = $customOptionID;  
                                                //$ObjProduct->updateProductStatus('Review',$productID);
                                            }            
                                        }
                                        $paramVariantArray['customOptionID']            = $customOptionID;
                                        $paramVariantArray['customOptionVariantCode']   = ($cust=='Stripe')?$params['bonnetStripes']:$params['roofcapcode'];                                        
                                        if($customOptionID>0 && !empty($paramVariantArray['customOptionVariantCode'])) {
                                            
                                            if(empty($prodCustArr[$productID][$customOptionID])) {
                                                $cusKey = 0;
                                            } else {
                                                $cusKey = count($prodCustArr[$productID][$customOptionID]);
                                            }
                                            
                                            //check code exists
                                            $checkCustOptVariant = $ObjCustom->listOptionVariant($languageIDsTemp,$paramVariantArray);                                               
                                            if(!empty($checkCustOptVariant)) {
                                                $custInsArr['attrOptionsGroup'][0]['customOptionVariantID'] = $checkCustOptVariant[0]['customOptionVariantID'];
                                                $sortOrder                                                  = $checkCustOptVariant[0]['sortOrder'];                                               
                                                $custInsArr['attrOptionsGroup'][0]['isDefault']             = $checkCustOptVariant[0]['isDefault'];
                                                $prevIsDefault                                              = $checkCustOptVariant[0]['isDefault'];
                                            } else {
                                                
                                                $custInsArr['attrOptionsGroup'][0]['customOptionVariantID'] = -1;
                                                if($keyc<=0) {
                                                    $sortOrder                                            = $ObjCustom->getMaxVariantSortOrder($customOptionID);                                                    
                                                } else {
                                                    $sortOrder                                            = $sortOrder + 1;
                                                }
                                                $isDefault                                                = $ObjCustom->getIsDefaultVariant($customOptionID,'','A');
                                                $custInsArr['attrOptionsGroup'][0]['isDefault']           = (!empty($isDefault))?0:1;
                                                //$ObjProduct->updateProductStatus('Review',$productID);  
                                            }
                                            //save custom options
                                            $custInsArr['attrOptionsGroup'][0]['varValue']        = ($cust=='Stripe')?$params['bonnetDesc']:$params['roofDesc'];
                                            $custInsArr['attrOptionsGroup'][0]['vsbID']           = $params['vehicle'];
                                            $custInsArr['attrOptionsGroup'][0]['bmwcode']         = $productExists['bmwCode'];
                                            $custInsArr['attrOptionsGroup'][0]['variantCode']     = $paramVariantArray['customOptionVariantCode'];
                                            $custInsArr['attrOptionsGroup'][0]['priceDiff']       = 0;
                                            $custInsArr['attrOptionsGroup'][0]['priceDiffType']   = 'N';
                                            $custInsArr['attrOptionsGroup'][0]['weightDiff']      = 0;
                                            $custInsArr['attrOptionsGroup'][0]['weightDiffType']  = 'N';                                            
                                            $custInsArr['attrOptionsGroup'][0]['sortOrder']       = $sortOrder;   
                                            $custInsArr['attrOptionsGroup'][0]['varStatus']       = 'A';
                                            $savedVariantID = $ObjCustom->saveCustomOptions($languageIDsTemp,$custInsArr,'Yes','Yes');
                                            $tempVar = ($tempVar=='') ? $savedVariantID:$tempVar."_".$savedVariantID;
                                            $prodCustArr[$productID][$customOptionID][$cusKey]               = $savedVariantID;     
                                            if(empty($checkCustOptVariant)) {                                                
                                                $addCustOptVar                      = $addCustOptVar+1;   
                                                $ObjCosy->stripeBonnetUpdate($params['variant'],$params['bonnetStripes'],$params['roofcapcode']);
                                                 
                                            } else {
                                                if($prevIsDefault==1 && $custInsArr['attrOptionsGroup'][0]['isDefault']==0)  {                                                        
                                                    $isDefaultRec                                                = $ObjCustom->getIsDefaultVariant($customOptionID,$checkCustOptVariant[0]['customOptionVariantID']);
                                                    if(empty($isDefaultRec)) {
                                                        #update isdefault of another variant as 1
                                                        $ObjCustom->updateIsDefaultVariant($customOptionID);

                                                    } 
                                                }
                                            }
                                            #check isDefault exists for variant
                                            $checkDefault = $ObjCustom->getIsDefaultVariant($customOptionID,'','A');
                                            $ObjCustom->updateIsDefaultVariant($customOptionID,'','Inactive');
                                            if(empty($checkDefault)) {
                                                #update isdefault of another variant as 1
                                                $ObjCustom->updateIsDefaultVariant($customOptionID);
                                            }
                                            
                                            
                                        }
                                        //save 
                                    }
                                    if(!empty($tempVar)) {
                                        $combStatus          = 'A';
                                        $checkComb           = $ObjProduct->checkMiniCombinationsExists($productID,$params['bonnetStripes'],$params['roofcapcode'],$combStatus,$params['vehicle'],'Check');

                                        if($checkComb<=0) {
                                            //save combinations
                                            if($tempVar!='') {                                            
                                               $custCombID = $ObjProduct->saveCombinationsMini($productID,$params['bonnetStripes'],$params['roofcapcode'],$tempVar,$combStatus,$params['vehicle']);
                                            }                                        
                                       } else {    
                                           $custCombID = $checkComb;                                            
                                           //$ObjProduct->updateCombinationStatus($checkComb,$combStatus);                                            
                                       }
                                       if(empty($combAttr[$productID])) {
                                           $combKey = 0;
                                       } else {
                                           $combKey = count($combAttr[$productID]);
                                       }
                                       if($custCombID>0) {
                                           $combAttr[$productID][$combKey]                = $custCombID;  
                                       }
                                    }
                                }
								
								
                        }
                        if(!empty($prodIDs)) {                           
                            foreach($prodIDs as $pids) {
                                    if(!empty($combAttr[$pids])) {                            
                                        $ObjProduct->updateCombinationStatus($combAttr[$pids],$pids,'Mini');   
                                    }
                                    if(!empty($prodCustArr[$pids])) { 
                                        foreach($prodCustArr[$pids] as $key=>$datavar) {
                                            //foreach($datavar as $varids) {
                                                $ObjProduct->updateVariantStatus($key,$datavar); 
                                            //}
                                        }
                                       
                                    }        
                            }
                        }
                        
                         echo "Stripe and roof information imported successfully";exit;
         }
    }
	public function autolineProcessAction() {
        $ObjExim                                = new EximModel();
        $languageIDs                            = $this->ObjView->languageIDs;   
        $languageIDs['AllList']                 = $languageIDs['All'];
        
        $ObjProduct                             = new ProductModel();
        $ObjBusiness                            = new BusinessModel();
        $ObjBrand                               = new BrandModel();
        $ObjProductCategory                     = new ProductCategoryModel();
        $ObjAttr                                = new AttributeModel();
        $SefModel                               = new SefModel();
        $Urlrewrite                             = new UrlrewriteModel();
        $ObjCustom                              = new CustomOptionModel();                                
        $product_sef_format                     = $this->getSettingValue('seo_settings', 'product_sef_format');
        $product_sef_format                     = isset($product_sef_format)  ? $product_sef_format   : false;
        //URL Rewrite Settings	
        $settingsUrlSuffix                      = $this->getSettingValue("seo_settings", "product_url_suffix");
        
        $handleCsv  = '';
        $fileExists = 0;
        //$siteUrl                                = $this->getSettingValue('site_settings', 'global_http_url');
        $siteUrl               					= 'https://www.findyourmini.ae/';
		$siteUrl                                = rtrim($siteUrl, "/");
        $fs_data                                = scandir(__DIR_EXIM . '/stock-update/');
        if (!empty($fs_data)) {                    
            foreach ($fs_data as $file) {
                if (strtolower(substr($file, -4)) == ".csv") {
                    $handleCsv     = __ROOT_PATH.'/public/uploads/exim/stock-update/'.$file;//$siteUrl.'/public/uploads/exim/stock-update/'.$file;//fopen(__CORE_PUBLIC_PATH . "/uploads/exim/stock-update/".$file, "r");
                    $fileExists    = 1;
                }                           
            }
        }                    
         if($fileExists>0) {		
                        /*require_once __ROOT_PATH."/vendor/phpoffice/phpexcel/Classes/PHPExcel.php";                                 
                        $url            = $handleCsv;
                        $filecontent    = file_get_contents($url);
                        $tmpfname       = tempnam(sys_get_temp_dir(),"tmpxls");
                        file_put_contents($tmpfname,$filecontent);

                        $excelReader = PHPExcel_IOFactory::createReaderForFile($tmpfname);
                        $excelObj    = $excelReader->load($tmpfname);
                        $worksheet   = $excelObj->getSheet(0);
                        $lastRow     = $worksheet->getHighestRow();*/
                        $ObjCsv      = new Csv();                       
                        $url         = $handleCsv;                
                        $ObjCsv->auto($url);
                        $resData     = $ObjCsv->data;
                        
                        $catMis      = array();
                        $prodIDs     = array();
			$counter     = 0;
                        $prodCustArr = array();
                        $combAttr    = array();
                        //echo "<pre>";print_r($resData);exit;
                        //for ($row = 2; $row <= $lastRow; $row++) {                        
                        foreach($resData as $csvdata) {  
                            
                                $params                 =   array();
                                
                                $params['vsb']          =   $csvdata['VSB'];
                                $params['franchisee']   =   $csvdata['Fran'];
                                $params['model']        =   $csvdata['Model'];
                                $params['skucode']      =   $csvdata['Variant'];
                                $params['bmwcode']      =   $csvdata['4-digit Variant for BMW'];
                                $params['optname']      =   $csvdata['Vehicle Description(Variant Name)'];
                                $params['shortdesc']    =   $csvdata['Model Name'];
                                $params['series']       =   $csvdata['Series'];
                                $params['exteriorcode'] =   $csvdata['Exterior -Paint Code'];
                                $params['exteriorname'] =   $csvdata['Exterior Colour-Paint'];
                                $params['interiorcode'] =   $csvdata['Upholstery Code'];
                                $params['interiorname'] =   $csvdata['Upholstery'];
                                $params['status']       =   $csvdata['Status-Stock or Order'];
                                $params['availcode']    =   $csvdata['Availablity Code'];
                                $params['modelyear']    =   $csvdata['ModelYear'];
                                $params['bodyStyle']    =   $csvdata['BodyStyle'];
                                $params['price']        =   $csvdata['List Price with VAT'];
                                
                                //echo "<pre>";print_r($params);exit;
								
								if($params['skucode']!=''){
								
                                $params['sku']  =   $params['skucode']."-".$params['modelyear'];
                                $productExists  =   $ObjProduct->isProductSkuAlreadyExists($params['sku'],  NULL, '', '','Yes');
                                $productID      =   !empty($productExists) ? $productExists['productID']:0;
                                $productOptionID=   !empty($productExists) ? $productExists['productOptionID']:'';
                                $productOptionStatus=   !empty($productExists) ? $productExists['productOptionStatus']:'Active';
                                $productOptionDefault=   !empty($productExists) ? $productExists['productOptionDefault']:'Yes';
                                $params['oldProductUrl'] = !empty($productExists) ? $productExists['productUrl']:'Yes';
                                //get business
                                $languageIDsTemp            =   $languageIDs;
                                $languageIDsTemp['Current'] =   $languageIDs['Default'];
                                //$businessDet            =   $ObjBusiness->listBusiness($languageIDsTemp, 0, 1, 'Active');
								$businessID 			=	$ObjBusiness->getBusinessKey();
                                $brandParams['languageIDs'] = $languageIDsTemp;
                                $brandParams['brandName']   = $params['franchisee'];
                                $brandDetails               =   $ObjBrand->getBrand($brandParams);                                
                                $params['businessID']   =   $businessID;//$businessDet[0]['businessID'];
                                $params['brandID']      =   $brandDetails['brandID'];    
                                
								if($params['sku']=='KU21B-2018') { }
                                
								if($brandDetails['brandID']==2) {
                                    $params['productDefaultCurrency']      =   $this->ObjView->_defaultCurrency;
                                    $params['productMinBuyLimit']          =   1;
                                    $params['InventoryTrackLevel']         =   'No';
                                    $params['productTitle']                =   $params['optname'];
                                    $params['productShortDescription']     =   $params['shortdesc'];     
                                    $params['productDescription']          =   $params['shortdesc'];
                                    $params['financeAvail']                =   'Yes';
                                    $params['leaseAvail']                  =   'Yes';
                                    $params['enableMultipleOptions']       =   'No';
                                    $params['productAddedBy']              =   'Admin';                                
                                    if($productID<=0) {
                                        $add                               =   'Yes';
                                        $params['productStatus']           =   'Review';                                    
                                    } else {
                                        $add                               =   'No';
                                       
                                        if($productExists['productStatus']=='Inactive' || $productExists['productStatus']=='Deleted') {
                                            $ObjProduct->updateProductStatus('Active',$productID);
                                        }
                                    }
                                    $params['attributeSetID']              =   1;
                                    $params['productTimeZone']             =   $this->getSettingValue('site_settings', 'default_timezone');
                                    $params['productUrl']                  =   $this->ObjCommon->generateKey("product", $params['productTitle']);
                                    $params['shortdesckey']                =   $this->ObjCommon->generateKey("product", $params['shortdesc']);
                                    if($productOptionID>0) {
                                        $params['productOptionsGroup'][0]['option_id']                  = $productOptionID;
                                    }
                                    $params['productOptionsGroup'][0]['realOptionCount']            = 1;
                                    $params['productOptionsGroup'][0]['productOptionName']          = $params['productTitle'];
                                    $params['productOptionsGroup'][0]['optionSKU']                  = $params['sku'];
                                    $params['productOptionsGroup'][0]['optionBarCode']              = '';
                                    $params['productOptionsGroup'][0]['productOptionRegularPrice']  = $params['price'];
                                    $params['productOptionsGroup'][0]['productOptionProductPrice']  = $params['price'];
                                    $params['productOptionsGroup'][0]['productOptionStatus']        = $productOptionStatus;
                                    $params['productOptionsGroup'][0]['defaultOpion']               = $productOptionDefault;
                                    $params['productOptionsGroup'][0]['packageWeight'] = '';
                                    $params['productOptionsGroup'][0]['packageLength'] = '';
                                    $params['productOptionsGroup'][0]['packageWidth']  = '';
                                    $params['productOptionsGroup'][0]['packageHeight'] = '';
                                    $params['productOptionsGroup'][0]['productOptionImageSort'] = '';
                                    $params['productOptionsGroup'][0]['vsb'] = $params['vsb'];
                                    $params['productOptionsGroup'][0]['modelCode']  = $params['model'];
                                    $params['productOptionsGroup'][0]['bmwCode']    = $params['bmwcode'];
                                    $params['productOptionsGroup'][0]['modelYear']  = $params['modelyear'];

                                    $params['productOptionsGroup'][0]['tier_price'] = array();
                                    $productCategoryIDs  = array();
                                    //echo "<pre>";print_r($params);exit;
                                    $catIDs = '';
                                    $getCategoryInfo              = $ObjProductCategory->getCategoryInfo($languageIDsTemp, 0, strtolower($params['series']), $fields = array(),'Y',$params['skucode']);
                                    $productCategoryID            =0;

                                    if(empty($getCategoryInfo)) {
                                        $catKey = '';

                                        if(strtolower($params['series'])=='i-series') {

                                            if(strpos($params['optname'],"i8")>0) {
                                               $catKey = "i8";
                                            }elseif(strpos($params['optname'],"i3")>0) {
                                               $catKey = "i3";
                                            } 
                                            if($catKey!='') {
                                                $getCategoryInfo              = $ObjProductCategory->getCategoryInfo($languageIDsTemp, 0, strtolower($catKey), $fields = array(),'Y');                                            
                                            }
                                        } 
                                    }  
                                    if(!empty($getCategoryInfo)) {
                                        $productCategoryID          = $getCategoryInfo['productCategoryID'];
                                    }                                
                                    $catIDs = $productCategoryID;
                                    if($productCategoryID>0) {
                                        /*$getParents                     = $ObjProductCategory->getAllParentIDs($productCategoryID,1);
                                        if(!empty($getParents)) {
                                            foreach($getParents as $pa) {
                                                $catIDs = !empty($catIDs) ? $catIDs.",".$pa['categoryID']:$pa['categoryID'];
                                            }
                                        }*/
                                    } else {
                                        $catMis[]  = 'Series: -'.$params['series'].' | Variant: -'.$params['skucode'];
                                    }
                                    $productCategoryIDs[]  = $catIDs;
                                    $params['productCategoryID'] = $productCategoryIDs;          
                                    //echo "<pre>";print_r($params);exit;
                                    $productID = $ObjProduct->saveProduct($languageIDsTemp,$params,$productID, '', true,'','Yes');  

                                    if($productID>0) {
                                        //echo $productID."<br>";
                                        //save custom options        
                                        /*if(empty($prodIDs) || (!empty($prodIDs) && !in_array($productID,$prodIDs))) {
                                            #delete custom options
                                            $ObjProduct->deleteCustomOptions($productID,$languageIDsTemp['Current']);
                                        }*/                                               
                                        $prodIDs[]   = $productID;            
                                        $custValues  = array("Color","Upholstery");
                                        $paramCustArray = array();
                                        $paramVariantArray = array();
                                        $paramscosy        = array();
                                        $addCustOptVar     = 0;
                                        $tempVar           = '';
                                        foreach($custValues as $keyc=>$cust) {
                                            $paramCustArray['customOptionName'] = $cust;
                                            $paramCustArray['isGlobal']         = 1;
                                            $checkGlobal = $ObjCustom->checkProductCustomOption($languageIDsTemp,$paramCustArray['customOptionName'],$productID);

                                            $custInsArr  = array();
                                            $custInsArr['customOptionName'] = $paramCustArray['customOptionName'];
                                            $custInsArr['inputType']        = 'select';
                                            $custInsArr['validateRuleRequired'] = 'Yes';
                                            $custInsArr['validationMessage'] = $this->getLanguageValue("errPleaseSelect")." ".$paramCustArray['customOptionName'];
                                            $custInsArr['status'] = 'A';//($params['status']=='S' && $params['availcode']=='A')?'A':'I';
                                            $custInsArr['productID'] = $productID;
                                            if(!empty($checkGlobal)) {
                                                $customOptionID = $checkGlobal['customOptionID'];
                                                $custInsArr['customOptionID']   = $customOptionID;
                                                
                                            } else {
                                                $customOptionID = 0;                                            
                                                $custInsArr['customOptionID']   = $customOptionID;  
                                                $customOptionID = $ObjCustom->saveCustomOptions($languageIDsTemp,$custInsArr,'Yes','No');
                                                $custInsArr['customOptionID']   = $customOptionID;  
                                                $ObjProduct->updateProductStatus('Review',$productID);
                                            }                                                    
                                            if($customOptionID>0) {
                                                if(empty($prodCustArr[$productID][$customOptionID])) {
                                                    $cusKey = 0;
                                                } else {
                                                    $cusKey = count($prodCustArr[$productID][$customOptionID]);
                                                }
                                                $paramVariantArray['customOptionID']            = $customOptionID;
                                                $paramVariantArray['customOptionVariantCode']   = ($cust=='Color')?$params['exteriorcode']:$params['interiorcode'];
                                                //check code exists
                                                $checkCustOptVariant = $ObjCustom->listOptionVariant($languageIDsTemp,$paramVariantArray);                                               
                                                if(!empty($checkCustOptVariant)) {
                                                    $custInsArr['attrOptionsGroup'][0]['customOptionVariantID'] = $checkCustOptVariant[0]['customOptionVariantID'];
                                                    $sortOrder                                                  = $checkCustOptVariant[0]['sortOrder'];   
                                                    $prevIsDefault                                              = $checkCustOptVariant[0]['isDefault'];
                                                    $custInsArr['attrOptionsGroup'][0]['isDefault']             = ($params['status']=='S' && $params['availcode']=='A')?$checkCustOptVariant[0]['isDefault']:0;
                                                    
                                                } else {

                                                    $custInsArr['attrOptionsGroup'][0]['customOptionVariantID'] = -1;
                                                    if($keyc<=0) {
                                                        $sortOrder                                            = $ObjCustom->getMaxVariantSortOrder($customOptionID);                                                    
                                                    } else {
                                                        $sortOrder                                            = $sortOrder + 1;
                                                    }
                                                    $isDefault                                                = $ObjCustom->getIsDefaultVariant($customOptionID);
                                                    $custInsArr['attrOptionsGroup'][0]['isDefault']           = (!empty($isDefault))?0:1;
                                                    $ObjProduct->updateProductStatus('Review',$productID);

                                                }

                                                $custInsArr['attrOptionsGroup'][0]['varValue']        = ($cust=='Color')?$params['exteriorname']:$params['interiorname'];
                                                $custInsArr['attrOptionsGroup'][0]['vsbID']           = $params['vsb'];
                                                $custInsArr['attrOptionsGroup'][0]['bmwcode']         = $params['bmwcode'];
                                                $custInsArr['attrOptionsGroup'][0]['variantCode']     = $paramVariantArray['customOptionVariantCode'];
                                                $custInsArr['attrOptionsGroup'][0]['priceDiff']       = 0;
                                                $custInsArr['attrOptionsGroup'][0]['priceDiffType']   = 'N';
                                                $custInsArr['attrOptionsGroup'][0]['weightDiff']      = 0;
                                                $custInsArr['attrOptionsGroup'][0]['weightDiffType']  = 'N';                                            
                                                $custInsArr['attrOptionsGroup'][0]['sortOrder']       = $sortOrder;   
                                                $custInsArr['attrOptionsGroup'][0]['varStatus']       = ($params['status']=='S' && $params['availcode']=='A')?'A':'I';
                                                $savedVariantID = $ObjCustom->saveCustomOptions($languageIDsTemp,$custInsArr,'Yes','Yes');
                                                $tempVar = ($tempVar=='') ? $savedVariantID:$tempVar."_".$savedVariantID;
                                                $prodCustArr[$productID][$customOptionID][$cusKey]               = $savedVariantID;     
                                                if(empty($checkCustOptVariant)) {                                                
                                                    $addCustOptVar                      = $addCustOptVar+1;                                               
                                                } else {
                                                    if($prevIsDefault==1 && $custInsArr['attrOptionsGroup'][0]['isDefault']==0)  {                                                        
                                                        $isDefaultRec                                                = $ObjCustom->getIsDefaultVariant($customOptionID,$checkCustOptVariant[0]['customOptionVariantID']);
                                                        if(empty($isDefaultRec)) {
                                                            #update isdefault of another variant as 1
                                                            $ObjCustom->updateIsDefaultVariant($customOptionID);
                                                            
                                                        } 
                                                    }
                                                }
                                                #check isDefault exists for variant
                                                $checkDefault = $ObjCustom->getIsDefaultVariant($customOptionID,'','A');
                                                $ObjCustom->updateIsDefaultVariant($customOptionID,'','Inactive');
                                                if(empty($checkDefault)) {
                                                    #update isdefault of another variant as 1
                                                    $ObjCustom->updateIsDefaultVariant($customOptionID);
                                                }
                                                //save custom options
                                            }
                                            //save 
                                        }
                                        #remove out of stock custom options
                                        /*if(!empty($prodCustArr[$productID])) {                                            
                                            $ObjProduct->deleteCustomOptions($productID,$languageIDsTemp['Current'],$prodCustArr[$productID]);
                                        }*/
                                        $combStatus          = ($params['status']=='S' && $params['availcode']=='A')?'A':'I';
                                        $checkComb = $ObjProduct->checkCombinationsExists($productID,$params['exteriorcode'],$params['interiorcode'],$combStatus,$params['vsb'],'Check',$tempVar);
                                        
                                        if($checkComb<=0) {
                                             //save combinations
                                             if($tempVar!='') {                                            
                                                $custCombID = $ObjProduct->saveCombinations($productID,$params['exteriorcode'],$params['interiorcode'],$tempVar,$combStatus,$params['vsb']);
                                             }
                                             $paramscosy['variantCode']          = $params['skucode'];
                                             $paramscosy['bmwCode']              = $params['bmwcode'];
                                             $paramscosy['exteriorCd']           = $params['exteriorcode'];
                                             $paramscosy['interiorCd']           = $params['interiorcode'];
                                             $paramscosy['year']                 = $params['modelyear'];
                                             $paramscosy['franchisee']           = $params['franchisee'];
											 if(!empty($paramscosy['exteriorCd']) && !empty($paramscosy['interiorCd'])) {
												$cosy = $this->cosyImageParams($paramscosy); 
											 }
                                        } else {    
                                            $custCombID = $checkComb;                                            
                                            //$ObjProduct->updateCombinationStatus($checkComb,$combStatus);                                            
                                        }
                                        if(empty($combAttr[$productID])) {
                                            $combKey = 0;
                                        } else {
                                            $combKey = count($combAttr[$productID]);
                                        }
                                        if($custCombID>0) {
                                            $combAttr[$productID][$combKey]               = $custCombID;  
                                        }
                                       
                                         //Attributes save                                    
                                       /* $getAttrDet      =   $ObjAttr->getAttrOptIDByName('body-type',$params['bodystyle'],$languageIDsTemp);                                    
                                        $attributeID     =   !empty($getAttrDet) ?$getAttrDet['attributeID']:0;
                                        if(!empty($params['bodystyle'])) {                                        
                                             if($attributeID<=0) {
                                                 $_POST = array();
                                                 $_POST['attributeID'] = 0;
                                                 $_POST['attrName']    = $this->getLanguageValue(lblBodyType);
                                                 $_POST['attributeKey']= 'body-type';
                                                 $_POST['attrInputType']= 'multiselect';
                                                 $_POST['isFilterable'] = 'Y';
                                                 $_POST['isComparable'] = 'Y';
                                                 $_POST['attrStatus']   = 'A';
                                                 $_POST['autoline']     = 'Yes';

                                                 $attributeID = $ObjAttr->saveAttribute($languageIDsTemp);
                                             }
                                             if($attributeID>0) {
                                                 $attrOptionID    =   !empty($getAttrDet) ? $getAttrDet['attrOptionID']:0;

                                                 $attrArr  =array();
                                                 $attrArr['attributeID']  = $attributeID;
                                                 $attrArr['attrOptionID'] = $attrOptionID;
                                                 $attrArr['attrOptName']  = $params['bodystyle'];
                                                 $ObjAttr->saveAttrOptVariants($attrArr,$languageIDsTemp);
                                                 $ObjAttr->insertProductAttr($productID,$attributeID,$attrOptionID);
                                             } 
                                        } else {
                                            //remove saved value
                                            $ObjAttr->removeProductAttr($productID,$attributeID);
                                        }
                                         */
                                        //URL Rewrite 
                                        $args     = array(
                                            'productUrl' => $params['productUrl']
                                        );
                                        
                                       if($add=='Yes') {
                                           
                                            $SefModel->_refreshProductRewrites($languageIDsTemp['AllList'], $productID, $settingsUrlSuffix, $args,'',$product_sef_format, 'insert',$params['brandID']);
                                             if($product_sef_format){
                                                $categoryIDs  = explode(",",$params['productCategoryID'][0]);        
                                                foreach ($categoryIDs as $key => $category) {
                                                    $args['category'] = $category;
                                                    $SefModel->_refreshProductRewrites($languageIDsTemp['AllList'], $productID, $settingsUrlSuffix, $args,'',$product_sef_format, 'insert',$params['brandID']);
                                                }
                                             }
                                            
                                       } else {


                                            if ($params['oldProductUrl'] != $params['productUrl']) {                                            
                                                $SefModel->_refreshProductRewrites($languageIDsTemp['AllList'], $productID, $settingsUrlSuffix, $args, '',$product_sef_format,'',$params['brandID']);
                                            }

                                            if($product_sef_format){
                                                $catEsixts = $Urlrewrite->getproductCategories($productID);
                                                $catEsixts = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($catEsixts)), 0);

                                                if(!empty($params['productCategoryID'])) {                
                                                    $categoryIDs  = explode(",",$params['productCategoryID'][0]);                
                                                    foreach ($categoryIDs as $key => $category) {

                                                        if($category>0) {
                                                            $args['category']        = $category;
                                                            $action                  = (!(in_array($category, $catEsixts))) ? 'insert' : '';

                                                            if ($params['oldProductUrl'] != $params['productUrl'] || !(in_array($category, $catEsixts)))
                                                                $SefModel->_refreshProductRewrites($languageIDsTemp['AllList'], $productID, $settingsUrlSuffix, $args,'',$product_sef_format, $action,$params['brandID']);
                                                        }
                                                    }
                                                    $deletedCat = array_diff($catEsixts, $categoryIDs);                                               
                                                    if ($deletedCat)
                                                        $Urlrewrite->deleteUrlRewrites(implode(",", $deletedCat), "product", $productID,'',$params['brandID']);
                                                }
                                             }
                                       }                         
                                       //URL Rewrite END                                    
                                    }
                                     /*echo "<tr><td>";
                                     echo $worksheet->getCell('A'.$row)->getValue();
                                     echo "</td><td>";
                                     echo $worksheet->getCell('B'.$row)->getValue()." ".$worksheet->getCell('C'.$row)->getValue();
                                     echo "</td><tr>";*/
                                    $counter	=	$counter + 1;

									}
								}
                        }
                        $ObjProduct->updateLastProcessed($productID,$counter);
                        if(!empty($prodIDs)) {
                            #inactive products not in stock
                            $ObjProduct->changeStatusInactive($prodIDs);
                            foreach($prodIDs as $pids) {
                                    if(!empty($combAttr[$pids])) {                            
                                        $ObjProduct->updateCombinationStatus($combAttr[$pids],$pids);   
                                    }
                                    if(!empty($prodCustArr[$pids])) { 
                                        foreach($prodCustArr[$pids] as $key=>$datavar) {
                                            //foreach($datavar as $varids) {
                                                $ObjProduct->updateVariantStatus($key,$datavar); 
                                            //}
                                        }
                                        //$ObjProduct->updateCombinationStatus($combAttr[$pids],$pids);   
                                    }        
                            }
                        }
                        
                        //send mail
                        if(!empty($catMis)) {
                            
                            $ObjEmailtemplate       = new EmailtemplateModel();
                            $emailbody  = $ObjEmailtemplate->getEmailTemlateDetails($languageIDsTemp, '', 'common-notification-email');
                            $from                   = array(
                                    $emailbody['emailFromEmail'],
                                    $emailbody['emailFromName']
                            );
                            $siteName               = $this->getSettingValue('site_settings', 'site_name');
                            $siteUrl                = $this->getSettingValue('site_settings', 'global_http_url');
                            //$notifyEmail            = $this->getSettingValue('site_settings', 'global_notification_email');
                            $notifyEmail            = 'feras.jamaleddine@agmc.ae';
                            $companyLogo            = $this->getSettingValue('company_information', 'company_logo');
                            $subject                = $emailbody['emailSubject'];
                            $subject                = str_replace('{$subject}', 'Vehicle Series Missing', $subject);
                            $bodytag                = $this->getLanguageValue('lblHi').",<br />
                                                        ".$this->getLanguageValue('lblRegardingProductImport1')." ".date('d-m-Y H:i:s')."<br />
                                                        ".$this->getLanguageValue('lblRegardingProductImport2')." - "." <br />";//.implode(', ',$catMis)." <br />
                            foreach($catMis as $rec) {
                                $bodytag    .= $rec."<br>";
                            }
                            $bodytag    .=          "<br /> "; 
                            $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", $languageIDsTemp);
                            $mail_settings                  = $this->getSettingValue('mail_settings');
                            $mail_settings['smtp_password'] = $this->encryptDecrypt("decrypt", $mail_settings['smtp_password']);
                            $ObjMail                        = new Mail($mail_settings);
                            $ObjMail->IsHTML();
                            $ObjMail->sendMail($from, $notifyEmail, $subject, $body);
                            if ($ObjMail->Send()) {
                               
                            } 
                        }
                        echo "Products imported successfully";exit;
                } else {
                     echo "File not found";exit;
                }
               
                 
        
        //$this->ObjView->display('ImportVariants.tpl');
    }
	public function cosyImageAction()
	{
		// $params['variantCode'] 	= '2H51B';
		// $params['bmwCode'] 		= '2H51';
		// $params['exteriorCd'] = 'A96';
        // $params['interiorCd'] = 'LCL5';
        // $params['year'] 		= '2020';
		// $params['variantCode'] 	= '4Z91D';
		// $params['bmwCode'] 		= '4Z91';
		// $params['exteriorCd'] = '490';
        // $params['interiorCd'] = 'Z1XX';
        // $params['year'] 		= '2019';
		//$fdgdfgfd = $this->cosyImageParams($params); 
	}
	public function cosyImageParams($params=array())
	{
		$ObjCosy        = new CosyModel();
		extract($params);
		if($variantCode!='' && $bmwCode!=''){
			if($franchisee =='BMW'){
				$brand = 'WBBM';
			}
			else if($franchisee=='MIN'){
				$brand = 'WBMI';
			}
			else if($franchisee=='BMI'){
				$brand = 'WBBI';
			}
			else{
				$brand = 'WBBM';
			}

			$combinationHash = $variantCode.'_'.$year.'_'.$exteriorCd.'_'.$interiorCd;
			$exteriorCode = 'P0'.$exteriorCd;
			$interiorCode = 'F'.$interiorCd;
			$saParams 	  = '';
			for($i=0;$i<=350;)
			{
				$extrString = 'BRAND='.$brand.'&VEHICLE='.$bmwCode.'&WIDTH=1400&HEIGHT=840&BKGND=0&RESP=JPEG&QUALITY=100&CLIENT=nvco&ANGLE='.$i.'&POV=walkaround&PAINT='.$exteriorCode.'&FABRIC='.$interiorCode.'&MARKET=gb';
				$insertSql[] = "
								(
										'".$bmwCode."',
										'".$franchisee."',
										'".$variantCode."',
										'".$extrString."',
										'".$saParams."',
										'".$combinationHash."',
										'".$i."',
										'extr',
										'New',
										NOW(),
										NOW(),
										'".$year."'
								)"; 
				$i=$i+10;
				//echo $extrString.'</br>'; //exit;
			}
		
			if($franchisee=='MIN'){
				$pngAngle = '130';
			}
			else{
				$pngAngle = '30';
			}
			$extrPngString = 'BRAND='.$brand.'&VEHICLE='.$bmwCode.'&WIDTH=450&HEIGHT=270&BKGND=TRANSPARENT&RESP=PNG&QUALITY=100&CLIENT=nvco&ANGLE='.$pngAngle.'&POV=walkaround&PAINT='.$exteriorCode.'&FABRIC='.$interiorCode.'&MARKET=gb';
				$insertSql[] = "
								(
										'".$bmwCode."',
										'".$franchisee."',
										'".$variantCode."',
										'".$extrPngString."',
										'".$saParams."',
										'".$combinationHash."',
										'".$pngAngle."',
										'png',
										'New',
										NOW(),
										NOW(),
										'".$year."'
								)"; 
		
			$intrString = 'BRAND='.$brand.'&VEHICLE='.$bmwCode.'&WIDTH=1400&HEIGHT=840&BKGND=0&RESP=JPEG&QUALITY=100&CLIENT=nvco&ANGLE=10&VIEW=INTERIEUR&PAINT='.$exteriorCode.'&FABRIC='.$interiorCode.'&MARKET=gb';
			//echo $intrString.'</br>';
			$insertSql[] = "
							(
									'".$bmwCode."',
									'".$franchisee."',
									'".$variantCode."',
									'".$intrString."',
									'".$saParams."',
									'".$combinationHash."',
									'10',
									'intr',
									'New',
									NOW(),
									NOW(),
									'".$year."'
							)"; 
			$intrStringTrim = 'BRAND='.$brand.'&VEHICLE='.$bmwCode.'&WIDTH=1400&HEIGHT=840&BKGND=0&RESP=JPEG&QUALITY=100&CLIENT=nvco&ANGLE=180&VIEW=INTERIEUR&PAINT='.$exteriorCode.'&FABRIC='.$interiorCode.'&MARKET=gb';
			//echo $intrStringTrim.'</br>';
			$insertSql[] = "
							(
									'".$bmwCode."',
									'".$franchisee."',
									'".$variantCode."', 														
									'".$intrStringTrim."',
									'".$saParams."',
									'".$combinationHash."',
									'180',
									'trim',
									'New',
									NOW(),
									NOW(),
									'".$year."'
							)"; 
			$intrTrimPanorama = 'BRAND='.$brand.'&VEHICLE='.$bmwCode.'&WIDTH=4000&HEIGHT=2000&BKGND=0&RESP=JPEG&QUALITY=100&CLIENT=nvco&POV=CENTERPANO&PAINT='.$exteriorCode.'&FABRIC='.$interiorCode.'&MARKET=gb';
			//echo $intrTrimPanorama.'</br>';
			$insertSql[] = "
							(
									'".$bmwCode."',
									'".$franchisee."',
									'".$variantCode."', 														
									'".$intrTrimPanorama."',
									'".$saParams."',
									'".$combinationHash."',
									'180',
									'panorama',
									'New',
									NOW(),
									NOW(),
									'".$year."'
							)";
			if($franchisee=='MIN'){
				$bonnetString = 'BRAND='.$brand.'&VEHICLE='.$bmwCode.'&WIDTH=1400&HEIGHT=840&BKGND=0&RESP=JPEG&QUALITY=100&CLIENT=nvco&ANGLE=60&POV=walkaround&PAINT='.$exteriorCode.'&FABRIC='.$interiorCode.'&MARKET=gb';
				$insertSql[] = "
								(
										'".$bmwCode."',
										'".$franchisee."',
										'".$variantCode."',
										'".$bonnetString."',
										'".$saParams."',
										'".$combinationHash."',
										'60',
										'bonnet',
										'New',
										NOW(),
										NOW(),
										'".$year."'
								)"; 
				$stripeString = 'BRAND='.$brand.'&VEHICLE='.$bmwCode.'&WIDTH=1400&HEIGHT=840&BKGND=0&RESP=JPEG&QUALITY=100&CLIENT=nvco&ANGLE=60&POV=walkaround&PAINT='.$exteriorCode.'&FABRIC='.$interiorCode.'&MARKET=gb';
				$insertSql[] = "
								(
										'".$bmwCode."',
										'".$franchisee."',
										'".$variantCode."',
										'".$stripeString."',
										'".$saParams."',
										'".$combinationHash."',
										'60',
										'stripe',
										'New',
										NOW(),
										NOW(),
										'".$year."'
								)"; 
			}
			$cosyParamsSql = $ObjCosy->SetCosyParams($insertSql);
			if($cosyParamsSql)
			{
				return true;
			}
			else{
				return false;
			}
		}
	}
	public function cosyAction(){
		$ObjCosy        = new CosyModel();
		$resCosyParams  = $ObjCosy->getCosyParams();
		if(count($resCosyParams) >0){
			// update params status
			foreach($resCosyParams as $cosyParams)
			{
				$cosyParamsId[] = $cosyParams['cosyParamsId'];
			}
			$cosyParamsStatus = $ObjCosy->updateCosyParamsStatus($cosyParamsId);
			
			foreach($resCosyParams as $cosyParams)
			{
				$sURL = $cosyParams['params'].'&SA='.$cosyParams['saParams'];
				if($cosyParams['stripe']!='' && $cosyParams['imageType']=='stripe'){
					$sURL = $sURL.','.$cosyParams['stripe'];
				}
				else if($cosyParams['bonnet']!='' && $cosyParams['imageType']=='bonnet'){
					$sURL = $sURL.','.$cosyParams['bonnet'];
				}
				else{
					if($cosyParams['stripe']!='' && $cosyParams['imageType']!='bonnet'){
						$sURL = $sURL.','.$cosyParams['stripe'];	
					}
					if($cosyParams['bonnet']!='' && $cosyParams['imageType']!='stripe'){
						$sURL = $sURL.','.$cosyParams['bonnet'];	
					}
				}
				if($cosyParams['stripe']!=''){
					$cosyParams['combinationHash']= $cosyParams['combinationHash'].'_'.$cosyParams['stripe'];
				}
				if($cosyParams['bonnet']!=''){
					$cosyParams['combinationHash']= $cosyParams['combinationHash'].'_'.$cosyParams['bonnet'];
				}
				$encodedUrl =	$ObjCosy->encode($sURL);
				//echo $encodedUrl.'</br>';
				$vehicleImage=$ObjCosy->setVehicleImage($encodedUrl,$cosyParams);
				
				$insertSql[] = "
								(
									'".$cosyParams['variantCode']."',
									'".$cosyParams['combinationHash']."',
									'".$cosyParams['imageType']."',
									'".$cosyParams['angle']."',
									'".$vehicleImage."',
									NOW()
								)"; 
			}
		 
		$cosyParamsSql 	  = $ObjCosy->saveVehicleImage($insertSql); 
		if($cosyParamsSql){
			echo 'Images inserted Successfully!';
		}
		}
		else
		{
			echo 'No data found!';
		}
		
	}
    public function optionProfilesAction() {
        $ObjExim    				= new EximModel();
		$ObjProduct  				= new ProductModel();
		$ObjProductList  			= new ProductListModel();
		$ObjCustom          		= new CustomOptionModel(); 
		$ObjEmailtemplate       	= new EmailtemplateModel();		
		$languageIDs        		= $this->ObjView->languageIDs;
		$languageIDs['AllList']     = $languageIDs['All'];
		$notify_array				= array();
		$resProducts   				= $ObjProductList->listAllProducts($languageIDs);
		
		if(!empty($resProducts)) {
			 require_once __ROOT_PATH."/vendor/phpoffice/phpexcel/Classes/PHPExcel.php";

			foreach ($resProducts as $key => $product) { 
					$variantArray = explode('-',$product['optionSKU']);
					if(file_exists(__DIR_EXIM . 'option-profiles/MINI/'.$variantArray[1].'/'.$variantArray[0].'.xlsx')) {
						$url			= __DIR_EXIM . 'option-profiles/MINI/'.$variantArray[1].'/'.$variantArray[0].'.xlsx';
						$filecontent    = file_get_contents($url);
                        $tmpfname       = tempnam(sys_get_temp_dir(),"tmpxls");
                        file_put_contents($tmpfname,$filecontent);
						
						$excelReader 	= PHPExcel_IOFactory::createReaderForFile($tmpfname);
                        $excelObj    	= $excelReader->load($tmpfname);
                        $worksheet   	= $excelObj->getSheet(0);
                        $lastRow     	= $worksheet->getHighestRow();
                        $params      	= array();
                        $profileCodes   = array();
						$spaceCounter	= 0;	
						  for ($row = 2; $row <= $lastRow; $row++) { 
                                $code 	= $worksheet->getCell('A'.$row)->getValue();	
                                $value 	= $worksheet->getCell('B'.$row)->getValue();	
                                $type 	= $worksheet->getCell('C'.$row)->getValue();	
								
								//echo $code.'---'. $value.'---'.$type.'<br/>';

								if ($value ==''){
									$spaceCounter=$spaceCounter+1;
								}else{
									$spaceCounter=0;
								}
								if($spaceCounter <=1){
									$params[] = array(
										'variantCode' 	=> $variantArray[0],
										'year' 			=> $variantArray[1],
										'profileCode' 	=> $code,
										'value' 		=> ($value != '') ? $value : 'space',
										'type' 			=> $type

									);
								}									
								if(!empty($code)) {
									$profileCodes[] =  $code;
								}
								if($type == 'W' || $type == 'T') { 
									$productID = $product['productID'];
									//save custom options
									if($type == 'W')
										$custValues  = array('Wheel');
									else if($type == 'T')
										$custValues  = array('Trim');
									$paramCustArray = array();
									$paramVariantArray = array();
									foreach($custValues as $keyc=>$cust) {
										$paramCustArray['customOptionName'] = $cust;
										$paramCustArray['isGlobal']         = 1;
										$checkGlobal = $ObjCustom->checkProductCustomOption($languageIDs,$paramCustArray['customOptionName'],$productID);
										
										$custInsArr  = array();
										$custInsArr['customOptionName'] = $paramCustArray['customOptionName'];
										$custInsArr['inputType']        = 'select';
										$custInsArr['validateRuleRequired'] = 'Yes';
										$custInsArr['validationMessage'] = $this->getLanguageValue("errPleaseSelect")." ".$paramCustArray['customOptionName'];
										$custInsArr['status'] = 'A';
										$custInsArr['productID'] = $productID;
										if(!empty($checkGlobal)) {
											$customOptionID = $checkGlobal['customOptionID'];
											$custInsArr['customOptionID']   = $customOptionID;
										} else {
											$customOptionID = 0;                                             
											$customOptionID = $ObjCustom->saveCustomOptions($languageIDs,$custInsArr,'Yes','No');
											$custInsArr['customOptionID']   = $customOptionID;
										}                                            
										if($customOptionID>0) {
											$paramVariantArray['customOptionID']            = $customOptionID;
											$paramVariantArray['customOptionVariantCode']   = $code;
											//check code exists
											$checkCustOptVariant = $ObjCustom->listOptionVariant($languageIDs,$paramVariantArray);                                               
											if(!empty($checkCustOptVariant)) {
												$custInsArr['attrOptionsGroup'][0]['customOptionVariantID'] = $checkCustOptVariant[0]['customOptionVariantID'];
												$sortOrder                                                  = $checkCustOptVariant[0]['sortOrder'];                                               
												$custInsArr['attrOptionsGroup'][0]['isDefault']             = $checkCustOptVariant[0]['isDefault'];
											} else {
												$custInsArr['attrOptionsGroup'][0]['customOptionVariantID'] = -1;
												if($keyc<=0) {
													$sortOrder      = $ObjCustom->getMaxVariantSortOrder($customOptionID);                                                    
												} else {
													$sortOrder   	= $sortOrder + 1;
												}
												$isDefault    		= $ObjCustom->getIsDefaultVariant($customOptionID);
												$custInsArr['attrOptionsGroup'][0]['isDefault']           = (!empty($isDefault))?0:1;
											}
											
											$custInsArr['attrOptionsGroup'][0]['varValue']        = $value;
											$custInsArr['attrOptionsGroup'][0]['vsbID']           = '';
											$custInsArr['attrOptionsGroup'][0]['variantCode']     = $paramVariantArray['customOptionVariantCode'];
											$custInsArr['attrOptionsGroup'][0]['priceDiff']       = 0;
											$custInsArr['attrOptionsGroup'][0]['priceDiffType']   = 'N';
											$custInsArr['attrOptionsGroup'][0]['weightDiff']      = 0;
											$custInsArr['attrOptionsGroup'][0]['weightDiffType']  = 'N';                                            
											$custInsArr['attrOptionsGroup'][0]['sortOrder']       = $sortOrder;   
											$custInsArr['attrOptionsGroup'][0]['varStatus']       = 'A';
											$ObjCustom->saveCustomOptions($languageIDs,$custInsArr,'Yes','Yes');
										}
									}
								}	
                         }
						 if(!empty($params)) {
							 $ObjProduct->InsertProductOptionProfiles($params,$profileCodes);
						 }
					}
					else {
						//if file not exists - notification mail
						$notify_array[$variantArray[1]][] = $variantArray[0];
						
					}
				}
				if(!empty($notify_array)) {
					$emailbody  = $ObjEmailtemplate->getEmailTemlateDetails($languageIDs, '', 'common-notification-email');
					$siteName               = $this->getSettingValue('site_settings', 'site_name');
					$siteUrl                = $this->getSettingValue('site_settings', 'global_http_url');
					//$notifyEmail            = $this->getSettingValue('site_settings', 'global_notification_email');
					//$notifyEmail            = 'feras.jamaleddine@agmc.ae';
					$companyLogo            = $this->getSettingValue('company_information', 'company_logo');
					$bodytag                = $this->getLanguageValue('lblHi').",<br />
												".$this->getLanguageValue('lblRegardingOptionProfileImport1')." ".date('d-m-Y H:i:s')."<br /><br />
												".$this->getLanguageValue('lblRegardingImport2')."<br /><br />";

					foreach($notify_array as $year =>$variants) {
					$bodytag                .= $this->getLanguageValue('lblInYear')." - ". $year."<br />";
					$bodytag                .= implode(', ',$variants)." <br />
													<br />"; 	
					}
												
					$this->ObjView->assign('emailbody', $bodytag);
					$this->ObjView->assign('siteUrl', $siteUrl);
					$this->ObjView->assign('siteName', $siteName);
					$this->ObjView->assign('companyLogo', $companyLogo);
					$body                           = $this->ObjCommon->fetch("email_templates/Layout.tpl", $languageIDs);
					// $ObjMail->sendMail($from, $notifyEmail, $subject, $body);
					$ObjProduct->UpdateImportRunDetails('Option Profiles Import',$body);
					
				}
				 echo "Option Profiles Imported Successfully";exit;
			}
	}
	public function sendoptionProfilesMailAction() {
		$languageIDs        = $this->ObjView->languageIDs;
		$ObjEmailtemplate   = new EmailtemplateModel();	
		$ObjProduct  		= new ProductModel();	
		$emailbody  		= $ObjEmailtemplate->getEmailTemlateDetails($languageIDs, '', 'common-notification-email');
		$details			= $ObjProduct->getImportRunDetails('Option Profiles Import');
		
		$from               = array(
			$emailbody['emailFromEmail'],
			$emailbody['emailFromName']
		);
		$notifyEmail        = $this->getSettingValue('product_cart_settings', 'option_profile_review_mail');
		$subject            = $emailbody['emailSubject'];
		$subject            = str_replace('{$subject}', 'Option Profile Import', $subject);
		$mail_settings      = $this->getSettingValue('mail_settings');
	    $mail_settings['smtp_password'] = $this->encryptDecrypt("decrypt", $mail_settings['smtp_password']);
		$ObjMail            = new Mail($mail_settings);
		$ObjMail->IsHTML();
		$ObjMail->sendMail($from, $notifyEmail, $subject, $details['emailHtml']);
		if ($ObjMail->Send()) {
		}
		 echo "Option Profiles Mail Send Successfully";exit;
	}
	public function sendReviewVechilesMailAction() {
		$languageIDs     	= $this->ObjView->languageIDs;
		$ObjProductList  	= new ProductListModel();
		$ObjEmailtemplate   = new EmailtemplateModel();
		$params        	 = array(
            'requestedBy' => 'admin',
            'languageIDs' => $languageIDs,
			'sortBy' => 'product.productID',
			'orderBy' => 'DESC',
            'status' => 'Review',
            'searchFrom' => 'admin' 
        );
		$resProducts   = $ObjProductList->listProducts($params);
		if(!empty($resProducts)) {
			$content = '';
			foreach($resProducts as $key =>$value) {
				$content .= $value['variantCode'].' - '.$value['modelYear'].'<br/>';
			}
			$emailbody  		= $ObjEmailtemplate->getEmailTemlateDetails($languageIDs, '', 'common-notification-email');
			$notifyEmail        = $this->getSettingValue('product_cart_settings', 'option_profile_review_mail');
			$from               = array(
				$emailbody['emailFromEmail'],
				$emailbody['emailFromName']
			);
			$subject            = $emailbody['emailSubject'];
			$subject            = str_replace('{$subject}', 'Vehicles Under Review Mail', $subject);
			$siteName           = $this->getSettingValue('site_settings', 'site_name');
			$siteUrl            = $this->getSettingValue('site_settings', 'global_http_url');
			$companyLogo        = $this->getSettingValue('company_information', 'company_logo');
			$bodytag            = $this->getLanguageValue('lblHi').",<br /><br />
										".$this->getLanguageValue('ListProductUnderReview')."<br /><br />";

			$bodytag           .= $content." <br /><br />"; 	
										
			$this->ObjView->assign('emailbody', $bodytag);
			$this->ObjView->assign('siteUrl', $siteUrl);
			$this->ObjView->assign('siteName', $siteName);
			$this->ObjView->assign('companyLogo', $companyLogo);
			$body  							= $this->ObjCommon->fetch("email_templates/Layout.tpl", $languageIDs);//print_r($body);exit;
			$mail_settings      			= $this->getSettingValue('mail_settings');
			$mail_settings['smtp_password'] = $this->encryptDecrypt("decrypt", $mail_settings['smtp_password']);
			$ObjMail            			= new Mail($mail_settings);
			$ObjMail->IsHTML();
			$ObjMail->sendMail($from, $notifyEmail, $subject, $body);
			if ($ObjMail->Send()) {
			}
			echo "Vehicles Under Review Mail Send Successfully";exit;
		} else {
			echo "No Vehicles Under Review";exit;
		}
	}
	public function cosyStaticAction(){
		$ObjCosy        = new CosyModel();
        $languageIDs    = $this->ObjView->languageIDs;
		$resCosyStatic  = $ObjCosy->getCosyStatic($languageIDs);
		//echo '<pre>'; print_r($resCosyStatic);exit;
		if(count($resCosyStatic) >0){
			foreach($resCosyStatic as $cosyStatic)
			{
				$bmwCode        =       $cosyStatic['bmwCode'];
				$brandID        =       $cosyStatic['brandID'];
				if($brandID =='1'){
					$brand = 'WBBM';
				}
				else if($brandID=='2'){
					$brand = 'WBMI';
				}
				else if($brandID=='5'){
					$brand = 'WBBI';
				}
				else{
					$brand = 'WBBM';
				}
				if($cosyStatic['customOptionName']=='Wheel'){
					$width  =       '160';
					$height =       '160';
					$view   =       'tile_rectangle';
					$sa             =       $cosyStatic['variantCode'];
				}
				else
				{
					if($brandID==2){
						$width  =       '210';
						$height =       '160';
						$view   =       'tile_rectangle';
					}else{
						$width  =       '300';
						$height =       '168';
						$view   =       'tile_wide';
					}
					
					if($cosyStatic['customOptionName']=='Color'){
						$sa             =       'P0'.$cosyStatic['variantCode'];
					}
					else if($cosyStatic['customOptionName']=='Trim'){
						$sa             =       $cosyStatic['variantCode'];
					}
					else if($cosyStatic['customOptionName']=='Stripe'){
						$sa             =       $cosyStatic['variantCode'];
					}
					else if($cosyStatic['customOptionName']=='Roof'){
						$sa             =       $cosyStatic['variantCode'];
					}
					else
					{
						$sa             =       'F'.$cosyStatic['variantCode'];
					}
				}
				$sURL = 'BRAND='.$brand.'&VEHICLE='.$bmwCode.'&WIDTH='.$width.'&HEIGHT='.$height.'&RESP=JPEG&QUALITY=100&VIEW='.$view.'&SA='.$sa.'&CLIENT=static';
				$encodedUrl =   $ObjCosy->encode($sURL);
				//echo $encodedUrl.'</br>';
				$cosyStaticSql    = $ObjCosy->saveStaticImage($encodedUrl,$cosyStatic);
			}
			if($cosyStaticSql){
				echo 'Static Images inserted Successfully!';
			}
		}
		else
		{
			echo 'No data found!';
		}
    }
    public function removeCosyImgAction() {
        $ObjCosy        = new CosyModel();
        // $getData       = $ObjCosy->getDuplicates();
        // if(!empty($getData)) {
            // foreach($getData as $get) {
                // $remove = $ObjCosy->removeImg($get['imageId'],'');
            // }
        // }
        
        $getData       = $ObjCosy->getDuplicates('cosy');
        //echo '<pre>'; print_r($getData); exit;
		if(!empty($getData)) {
            foreach($getData as $data) {
                $remove = $ObjCosy->removeImg($data['cosyParamsId'],'cosy');
				echo 'Deleted';
            }
			
        }
		else{
			echo 'No data';
		}
    }
    public function checkReviewProductsInfoAction() {
        $ObjProductList = new ProductListModel();
        $ObjProduct     = new ProductModel();
        $ObjCustom      = new CustomOptionModel();  
        $languageIDs    = $this->ObjView->languageIDs;
        $languageIDsTemp            =   $languageIDs;
        $languageIDsTemp['Current'] =   $languageIDs['Default'];
         $params        = array(
            'requestedBy' => '',
            'languageIDs' => $languageIDs,
            'limitFrom' => 0,
            'limitTo' => '',            
            'status' => 'Review',
            'getCnt'=>'Yes'
        );
        #list all products with Review status
        $resProducts   = $ObjProductList->listProductsInReview($params);
        $updateCnt     = 0;
        //echo "<pre>";print_r($resProducts);exit;
        if(!empty($resProducts)) {
            foreach($resProducts as $key=>$product) {               
                            
                #check in lease 
                $leasePriceCnt      = $product['leasePriceCnt'];
                #checkFinance
                $monthlyInstallment = $product['monthlyInstallment'];
                #option Profile Exists
                $optionProfileCnt   = $product['optionProfileCnt'];                
                 #check Product Image
                $cosyImgNewCnt      = $product['cosyImgNewCnt'];    
                $cosyImgExists      = $product['cosyImgExists']; 
                
                //$custValues  = array("Color","Upholstery","Wheel","Trim","Stripe","Roof");
                $custValues  = array("Color","Upholstery","Wheel","Trim");                
                $custCheck   = 0;
                foreach($custValues as $keyc=>$cust) {
                    $checkGlobal = $ObjCustom->checkProductCustomOption($languageIDsTemp,$cust,$product['productID']);
                    if(!empty($checkGlobal)) {
                        $customOptionID = $checkGlobal['customOptionID'];
                        $paramVariantArray['customOptionID']            = $customOptionID;
                        $paramVariantArray['customOptionVariantImg']    = 'Img';
                        //check code exists
                        $checkCustOptVariant = $ObjCustom->listOptionVariant($languageIDsTemp,$paramVariantArray);
                        if(!empty($checkCustOptVariant)) {
                            $custCheck = $custCheck + 1;
                        }
                    }
                }
                
                //if($leasePriceCnt>0 && $monthlyInstallment>0 && $optionProfileCnt>0 && $cosyImgNewCnt<=0 && $cosyImgExists>0 && $custCheck>=4) {
                if($optionProfileCnt>0 && $cosyImgNewCnt<=0 && $cosyImgExists>0 && $custCheck>=4) {
                    
                    $updateCnt  =$updateCnt+1;                    
                    $ObjProduct->updateProductStatus('Active',$product['productID']);
                } 
            }
            if($updateCnt>0) {
                echo "Products status with review updated to active status";
            } else {
                echo "No products updated to active status";
            }
        } else {
            echo "No products under review status";
           
        }
         exit;
    }
}
