<?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: AnlyticsController.php, v 1.0 2012/05/15 09:52:11
//
class AnalyticsController extends Controller {
    public function indexAction() {
        $ObjFlot      = new Flot();
        $ObjLog       = new AnalyticsModel();
        $merchantID   = $this->ObjSession->getSession("BUSINESS_USER_ID");
        $visitCount   = 0;
        $date         = isset($date) ? $date : '';
        //overview
        $overViewData = $ObjLog->getTotalCountsCustomer($merchantID, '', '', $date);
        $visitCount   = count($overViewData);
        if ($visitCount > 0) {
            $overViewData['orderCount']            = $overViewData['ordersplaced'];
            $overViewData['orderTotalAmount']      = $overViewData['totalRevenue'];
            $overViewData['returningVisitorCount'] = $overViewData['returnVisit'];
            $overViewData['visitorCount']          = $overViewData['totalCustomers'];
        } else {
            $overViewData['orderCount']            = 0;
            $overViewData['orderTotalAmount']      = 0;
            $overViewData['returningVisitorCount'] = 0;
            $overViewData['visitorCount']          = 0;
        }
        $date                = date("Y-m-d", strtotime("- 7 day")) . " to " . date("Y-m-d");
        //Age/gender   
        $ResultSet           = $ObjLog->getCustomerAgeGenderDetails('object', $merchantID, '', '', $date);
        $ResultSetCount      = $ResultSet->num_rows;
        $femaleBelow17       = $female18to24 = $female25to34 = $female35to54 = $femaleAbove55 = $femaleNotSpecified = 0;
        $maleBelow17         = $male18to24 = $male25to34 = $male35to54 = $maleAbove55 = $maleNotSpecified = 0;
        $notSpecifiedBelow17 = $notSpecified18to24 = $notSpecified25to34 = $notSpecified35to54 = $notSpecifiedAbove55 = $notSpecifiedNotSpecified = 0;
        if ($ResultSetCount > 0) {
            $userIdArr = array();
            for ($i = 0; $i < $ResultSetCount; $i++) {
                $result = $ResultSet->fetch_array(MYSQLI_ASSOC);
                if (!in_array($result['userID'], $userIdArr)) {
                    switch ($result['userSex']) {
                        case 'Male':
                            if ($result['userAge'] != '') {
                                if ($result['userAge'] <= 17) {
                                    $maleBelow17++;
                                } else if ($result['userAge'] > 17 && $result['userAge'] <= 24) {
                                    $male18to24++;
                                } else if ($result['userAge'] > 24 && $result['userAge'] <= 34) {
                                    $male25to34++;
                                } else if ($result['userAge'] > 34 && $result['userAge'] <= 54) {
                                    $male35to54++;
                                } else {
                                    $maleAbove55++;
                                }
                            } else {
                                $maleNotSpecified++;
                            }
                            break;
                        case 'Female':
                            if ($result['userAge'] != '') {
                                if ($result['userAge'] <= 17) {
                                    $femaleBelow17++;
                                } else if ($result['userAge'] > 17 && $result['userAge'] <= 24) {
                                    $female18to24++;
                                } else if ($result['userAge'] > 24 && $result['userAge'] <= 34) {
                                    $female25to34++;
                                } else if ($result['userAge'] > 34 && $result['userAge'] <= 54) {
                                    $female35to54++;
                                } else {
                                    $femaleAbove55++;
                                }
                            } else {
                                $femaleNotSpecified++;
                            }
                            break;
                        case 'Not Specified':
                            if ($result['userAge'] != '') {
                                if ($result['userAge'] <= 17) {
                                    $notSpecifiedBelow17++;
                                } else if ($result['userAge'] > 17 && $result['userAge'] <= 24) {
                                    $notSpecified18to24++;
                                } else if ($result['userAge'] > 24 && $result['userAge'] <= 34) {
                                    $notSpecified25to34++;
                                } else if ($result['userAge'] > 34 && $result['userAge'] <= 54) {
                                    $notSpecified35to54++;
                                } else {
                                    $notSpecifiedAbove55++;
                                }
                            } else {
                                $notSpecifiedNotSpecified++;
                            }
                            break;
                    }
                    $userIdArr[] = $result['userID'];
                }
                unset($result);
            }
            $ResultSet->free();
            //Demographics
            $resultLog = $resultLogTemp = $locatioGraphData = array();
            $ResultLoc = $ObjLog->getCustomerAgeGenderDetails('sql', $merchantID, '', '', $date);
            if (count($ResultLoc) > 0) {
                foreach ($ResultLoc as $key => $value) {
                    $billingAddress                    = unserialize($value['billingAddress']);
                    $newKey                            = $billingAddress['billingCountry'] . "_" . $billingAddress['billingState'] . "_" . $billingAddress['billingCity'];
                    $resultLog[$newKey]['cityName']    = $billingAddress['billingCity'];
                    $resultLogTemp[$newKey]['users'][] = $value['userID'];
                }
                foreach ($resultLogTemp as $key => $userarray) {
                    $resultLog[$key]['users']     = array_count_values($userarray['users']);
                    $resultLog[$key]['userCount'] = count($resultLog[$key]['users']);
                }
                $resultLog = $this->sortMultiArray($resultLog, 'userCount', 'desc');
            }
            $locationWiseLabels = '';
            if (count($resultLog) > 0) {
                $countReturningVisitor = 0;
                foreach ($resultLog as $key => $value) {
                    if ($countReturningVisitor == 6) {
                        break;
                    }
                    $locatioGraphData[$countReturningVisitor][$countReturningVisitor]['graphX'] = $countReturningVisitor + 1;
                    $locatioGraphData[$countReturningVisitor][$countReturningVisitor]['graphY'] = count($value['users']);
                    $locationWiseLabels .= $value['cityName'] . ",";
                    $countReturningVisitor++;
                }
                $locationWiseLabels = substr($locationWiseLabels, 0, -1);
                unset($resultLog);
            } // echo "<pre>"; print_r($locatioGraphData);exit; 
            //ageGenderDistribution
            $maleData                                                 = $femaleData = $notSpecifiedData = array();
            $maleData[0]['graphX']                                    = 0;
            $maleData[0]['graphY']                                    = $maleBelow17;
            $maleData[1]['graphX']                                    = 1;
            $maleData[1]['graphY']                                    = $male18to24;
            $maleData[2]['graphX']                                    = 2;
            $maleData[2]['graphY']                                    = $male25to34;
            $maleData[3]['graphX']                                    = 3;
            $maleData[3]['graphY']                                    = $male35to54;
            $maleData[4]['graphX']                                    = 4;
            $maleData[4]['graphY']                                    = $maleAbove55;
            $maleData[5]['graphX']                                    = 5;
            $maleData[5]['graphY']                                    = $maleNotSpecified;
            $femaleData[0]['graphX']                                  = 0;
            $femaleData[0]['graphY']                                  = $femaleBelow17;
            $femaleData[1]['graphX']                                  = 1;
            $femaleData[1]['graphY']                                  = $female18to24;
            $femaleData[2]['graphX']                                  = 2;
            $femaleData[2]['graphY']                                  = $female25to34;
            $femaleData[3]['graphX']                                  = 3;
            $femaleData[3]['graphY']                                  = $female35to54;
            $femaleData[4]['graphX']                                  = 4;
            $femaleData[4]['graphY']                                  = $femaleAbove55;
            $femaleData[5]['graphX']                                  = 5;
            $femaleData[5]['graphY']                                  = $femaleNotSpecified;
            $notSpecifiedData[0]['graphX']                            = 0;
            $notSpecifiedData[0]['graphY']                            = $notSpecifiedBelow17;
            $notSpecifiedData[1]['graphX']                            = 1;
            $notSpecifiedData[1]['graphY']                            = $notSpecified18to24;
            $notSpecifiedData[2]['graphX']                            = 2;
            $notSpecifiedData[2]['graphY']                            = $notSpecified25to34;
            $notSpecifiedData[3]['graphX']                            = 3;
            $notSpecifiedData[3]['graphY']                            = $notSpecified35to54;
            $notSpecifiedData[4]['graphX']                            = 4;
            $notSpecifiedData[4]['graphY']                            = $notSpecifiedAbove55;
            $notSpecifiedData[5]['graphX']                            = 5;
            $notSpecifiedData[5]['graphY']                            = $notSpecifiedNotSpecified;
            $ageGenderGraphData[0]                                    = $maleData;
            $ageGenderGraphData[1]                                    = $femaleData;
            $ageGenderGraphData[2]                                    = $notSpecifiedData;
            $ageGenderDistributionSettings['placeholder']             = 'ageGenderDistribution';
            $ageGenderDistributionSettings['fill']                    = 'false';
            $tempText                                                 = $this->getLanguageValue("lblMale") . ',' . $this->getLanguageValue("lblFemale") . ',' . $this->getLanguageValue("lblNotSpecified");
            $ageGenderDistributionSettings['graphLabels']             = $tempText;
            $ageGenderDistributionSettings['graphTotalLabels']        = $tempText;
            $ageGenderDistributionSettings['ticksForbarGraph']        = array(
                0 => $this->getLanguageValue("lbl0to17"),
                1 => $this->getLanguageValue("lbl18to24"),
                2 => $this->getLanguageValue("lbl25to34"),
                3 => $this->getLanguageValue("lbl35to54"),
                4 => $this->getLanguageValue("lbl55plus"),
                5 => $this->getLanguageValue("lblNotSpecified")
            );
            $ageGenderDistributionSettings['tootlTipXLabel']          = $this->getLanguageValue("lblVisits");
            $ageGenderDistributionSettings['graphTotalHolder']        = 'ageGenderDistributiongraphTotalHolder';
            $ageGenderDistributionSettings['graphTotalHolderUlClass'] = 'graphTotalHolderUl';
            $ageGenderDistributionSettings['legendHolder']            = 'ageGenderDistributionLegend';
            $ageGenderDistributionSettings['legendColumns']           = 4;
            $ageGenderDistributionSettings['mode']                    = 'null';
            $ageGenderDistributionSettings['graphColors']             = array(
                "#1999cf",
                "#d41857",
                "#0e8f05"
            );
            $ageGenderDistributionSettings['graphType']               = 'bar';
            $ageGenderDistributionSettings['multiBar']                = 'true';
            $ageGenderDistributionSettings['barWidth']                = '0.2';
            $ageGenderDistributionSettings['hoverable']               = 'true';
            $ageGenderDistributionSettings['includeScript']           = 'false';
            $ageGenderDistributionSettings['javascript_path']         = $this->ObjView->_javascript_path;
            if (count($ageGenderGraphData) > 0) {
                $ageGenderDistributionGraph = $ObjFlot->init($ageGenderGraphData, 0, $ageGenderDistributionSettings);
            }
            unset($ageGenderGraphData);
            //demographics	
            $demographicsSettings['placeholder']             = 'demographics';
            $demographicsSettings['fill']                    = 'true';
            $demographicsSettings['graphLabels']             = $locationWiseLabels;
            $demographicsSettings['legendHolder']            = 'demographicsLegend';
            $demographicsSettings['graphTotalLabels']        = $locationWiseLabels;
            $demographicsSettings['graphTotalHolder']        = 'demographicsgraphTotalHolder';
            $demographicsSettings['graphTotalHolderUlClass'] = 'graphTotalHolderUl';
            $demographicsSettings['tooltipDecimalsY']        = '2';
            $demographicsSettings['javascript_path']         = $this->ObjView->_javascript_path;
            $demographicsSettings['graphType']               = 'pie';
            $demographicsSettings['filterCheckboxContainer'] = false;
            $demographicsSettings['mode']                    = 'null';
            $demographicsSettings['includeScript']           = 'false';
            if (count($locatioGraphData) > 0) {
                $demographicsGraph = $ObjFlot->init($locatioGraphData, 0, $demographicsSettings);
            }
            unset($locatioGraphData);
        } else {
            $demographicsGraph          = '<div class="noDataFound">' . $this->getLanguageValue("lblNoData") . '</div>';
            $ageGenderDistributionGraph = '<div class="noDataFound">' . $this->getLanguageValue("lblNoData") . '</div>';
        }
        $settingsDateFormat = $this->getSettingValue("site_settings", "date_format");
        $toDate             = date("Y-m-d");
        $fromDate           = date("Y-m-d", strtotime("-7 day"));
        $formattedFromDate  = $this->changeToSystemDateFormat($settingsDateFormat, $fromDate);
        $formattedToDate    = $this->changeToSystemDateFormat($settingsDateFormat, $toDate);
        $formattedDate      = $formattedFromDate . " to " . $formattedToDate;
        $this->ObjView->assign("dateDemographics", $formattedDate);
        $this->ObjView->assign("dateAgeGender", $formattedDate);
        $this->ObjView->assign("demographicsGraph", $demographicsGraph);
        $this->ObjView->assign("ageGenderDistribution", $ageGenderDistributionGraph);
        $this->ObjView->assign("overViewData", $overViewData);
        $this->ObjView->display('AnalyticsDashBoard.tpl');
    }
    public function ajaxDemographicsAction() {
        $ObjFlot         = new Flot();
        $ObjLog          = new AnalyticsModel();
        $merchantID      = $this->ObjSession->getSession("BUSINESS_USER_ID");
        $currentAjaxPost = $_POST;
        $dateRange       = $currentAjaxPost['ajax_request'][0];
        if ($dateRange) {
            if (strpos($dateRange, 'to') > 0) {
                $queryString = explode(' to ', $dateRange);
                $firstDate   = date("Y-m-d", strtotime($queryString[0] . ' 00:00:00'));
                $lastDay     = date("Y-m-d", strtotime($queryString[1] . ' 00:00:00'));
                $date        = $firstDate . " to " . $lastDay;
            } else {
                $date = date("Y-m-d", strtotime($dateRange . ' 00:00:00'));
            }
        }
        //Demographics
        $locationWiseLabels = '';
        $resultLog          = $resultLogTemp = $locatioGraphData = array();
        $ResultLoc          = $ObjLog->getCustomerAgeGenderDetails('sql', $merchantID, '', '', $date);
        if (count($ResultLoc) > 0) {
            foreach ($ResultLoc as $key => $value) {
                $billingAddress                    = unserialize($value['billingAddress']);
                $newKey                            = $billingAddress['billingCountry'] . "_" . $billingAddress['billingState'] . "_" . $billingAddress['billingCity'];
                $resultLog[$newKey]['cityName']    = $billingAddress['billingCity'];
                $resultLogTemp[$newKey]['users'][] = $value['userID'];
            }
            foreach ($resultLogTemp as $key => $userarray) {
                $resultLog[$key]['users']     = array_count_values($userarray['users']);
                $resultLog[$key]['userCount'] = count($resultLog[$key]['users']);
            }
        }
        $resultLog = $this->sortMultiArray($resultLog, 'userCount', 'desc');
        if (count($resultLog) > 0) {
            $countReturningVisitor = 0;
            foreach ($resultLog as $key => $value) {
                if ($countReturningVisitor == 6) {
                    break;
                }
                $locatioGraphData[$countReturningVisitor][$countReturningVisitor]['graphX'] = $countReturningVisitor + 1;
                $locatioGraphData[$countReturningVisitor][$countReturningVisitor]['graphY'] = count($value['users']);
                $locationWiseLabels .= $value['cityName'] . ",";
                $countReturningVisitor++;
            }
            $locationWiseLabels = substr($locationWiseLabels, 0, -1);
            unset($resultLog);
            //demographics	
            $demographicsSettings['placeholder']             = 'demographics';
            $demographicsSettings['fill']                    = 'true';
            $demographicsSettings['graphLabels']             = $locationWiseLabels;
            $demographicsSettings['legendHolder']            = 'demographicsLegend';
            $demographicsSettings['graphTotalLabels']        = $locationWiseLabels;
            $demographicsSettings['graphTotalHolder']        = 'demographicsgraphTotalHolder';
            $demographicsSettings['graphTotalHolderUlClass'] = 'graphTotalHolderUl';
            $demographicsSettings['tooltipDecimalsY']        = '2';
            $demographicsSettings['javascript_path']         = $this->ObjView->_javascript_path;
            $demographicsSettings['graphType']               = 'pie';
            $demographicsSettings['filterCheckboxContainer'] = false;
            $demographicsSettings['mode']                    = 'null';
            $demographicsSettings['includeScript']           = 'false';
            if (count($locatioGraphData) > 0) {
                $demographicsGraph = $ObjFlot->init($locatioGraphData, 0, $demographicsSettings);
            } else {
                echo '<div class="noDataFound">' . $this->getLanguageValue("lblNoData") . '</div>';
                exit;
            }
            echo $demographicsGraph;
            exit;
        } else {
            echo '<div class="noDataFound">' . $this->getLanguageValue("lblNoData") . '</div>';
            exit;
        }
    }
    public function ajaxAgeGenderAction() {
        $ObjFlot         = new Flot();
        $ObjLog          = new AnalyticsModel();
        $merchantID      = $this->ObjSession->getSession("BUSINESS_USER_ID");
        $currentAjaxPost = $_POST;
        $dateRange       = $currentAjaxPost['ajax_request'][0];
        $filterGender    = (isset($currentAjaxPost['ajax_request'][1])) ? $currentAjaxPost['ajax_request'][1] : '';
        $filterAge       = (isset($currentAjaxPost['ajax_request'][2])) ? $currentAjaxPost['ajax_request'][2] : '';
        if (is_array($filterGender) && is_array($filterAge)) {
            if ($dateRange) {
                if (strpos($dateRange, 'to') > 0) {
                    $queryString = explode(' to ', $dateRange);
                    $firstDate   = date("Y-m-d", strtotime($queryString[0] . ' 00:00:00'));
                    $lastDay     = date("Y-m-d", strtotime($queryString[1] . ' 00:00:00'));
                    $date        = $firstDate . " to " . $lastDay;
                } else {
                    $date = date("Y-m-d", strtotime($dateRange . ' 00:00:00'));
                }
            }
            // print_r($filterAge);
            $resultsSet          = $ObjLog->getCustomerAgeGenderDetails('object', $merchantID, $filterAge, $filterGender, $date);
            $visitCount          = $resultsSet->num_rows;
            $userIdArr           = array();
            $femaleBelow17       = $female18to24 = $female25to34 = $female35to54 = $femaleAbove55 = $femaleNotSpecified = 0;
            $maleBelow17         = $male18to24 = $male25to34 = $male35to54 = $maleAbove55 = $maleNotSpecified = 0;
            $notSpecifiedBelow17 = $notSpecified18to24 = $notSpecified25to34 = $notSpecified35to54 = $notSpecifiedAbove55 = $notSpecifiedNotSpecified = 0;
            $maleData            = $femaleData = $notSpecifiedData = array();
            $counter             = "Customers";
            if ($visitCount > 0) {
                for ($i = 0; $i < $visitCount; $i++) {
                    $result = $resultsSet->fetch_array(MYSQLI_ASSOC);
                    if (!in_array($result['userID'], $userIdArr)) {
                        switch ($result['userSex']) {
                            case 'Male':
                                if ($result['userAge'] != '') {
                                    if ($result['userAge'] <= 17) {
                                        $maleBelow17++;
                                    } else if ($result['userAge'] > 17 && $result['userAge'] <= 24) {
                                        $male18to24++;
                                    } else if ($result['userAge'] > 24 && $result['userAge'] <= 34) {
                                        $male25to34++;
                                    } else if ($result['userAge'] > 34 && $result['userAge'] <= 54) {
                                        $male35to54++;
                                    } else {
                                        $maleAbove55++;
                                    }
                                } else {
                                    $maleNotSpecified++;
                                }
                                break;
                            case 'Female':
                                if ($result['userAge'] != '') {
                                    if ($result['userAge'] <= 17) {
                                        $femaleBelow17++;
                                    } else if ($result['userAge'] > 17 && $result['userAge'] <= 24) {
                                        $female18to24++;
                                    } else if ($result['userAge'] > 24 && $result['userAge'] <= 34) {
                                        $female25to34++;
                                    } else if ($result['userAge'] > 34 && $result['userAge'] <= 54) {
                                        $female35to54++;
                                    } else {
                                        $femaleAbove55++;
                                    }
                                } else {
                                    $femaleNotSpecified++;
                                }
                                break;
                            case 'Not Specified':
                                if ($result['userAge'] != '') {
                                    if ($result['userAge'] <= 17) {
                                        $notSpecifiedBelow17++;
                                    } else if ($result['userAge'] > 17 && $result['userAge'] <= 24) {
                                        $notSpecified18to24++;
                                    } else if ($result['userAge'] > 24 && $result['userAge'] <= 34) {
                                        $notSpecified25to34++;
                                    } else if ($result['userAge'] > 34 && $result['userAge'] <= 54) {
                                        $notSpecified35to54++;
                                    } else {
                                        $notSpecifiedAbove55++;
                                    }
                                } else {
                                    $notSpecifiedNotSpecified++;
                                }
                                break;
                        }
                        $userIdArr[] = $result['userID'];
                    }
                    unset($result);
                }
                $resultsSet->free();
                $index = 0;
                if (in_array("below17", $filterAge)) {
                    $maleData[$index]['graphX']         = $index;
                    $maleData[$index]['graphY']         = $maleBelow17;
                    $femaleData[$index]['graphX']       = $index;
                    $femaleData[$index]['graphY']       = $femaleBelow17;
                    $notSpecifiedData[$index]['graphX'] = $index;
                    $notSpecifiedData[$index]['graphY'] = $notSpecifiedBelow17;
                    $ticks[$index]                      = $this->getLanguageValue("lbl0to17");
                    $index++;
                }
                if (in_array("18-24", $filterAge)) {
                    $maleData[$index]['graphX']         = $index;
                    $maleData[$index]['graphY']         = $male18to24;
                    $femaleData[$index]['graphX']       = $index;
                    $femaleData[$index]['graphY']       = $female18to24;
                    $notSpecifiedData[$index]['graphX'] = $index;
                    $notSpecifiedData[$index]['graphY'] = $notSpecified18to24;
                    $ticks[$index]                      = $this->getLanguageValue("lbl18to24");
                    $index++;
                }
                if (in_array("25-34", $filterAge)) {
                    $maleData[$index]['graphX']         = $index;
                    $maleData[$index]['graphY']         = $male25to34;
                    $femaleData[$index]['graphX']       = $index;
                    $femaleData[$index]['graphY']       = $female25to34;
                    $notSpecifiedData[$index]['graphX'] = $index;
                    $notSpecifiedData[$index]['graphY'] = $notSpecified25to34;
                    $ticks[$index]                      = $this->getLanguageValue("lbl25to34");
                    $index++;
                }
                if (in_array("35-54", $filterAge)) {
                    $maleData[$index]['graphX']         = $index;
                    $maleData[$index]['graphY']         = $male35to54;
                    $femaleData[$index]['graphX']       = $index;
                    $femaleData[$index]['graphY']       = $female35to54;
                    $notSpecifiedData[$index]['graphX'] = $index;
                    $notSpecifiedData[$index]['graphY'] = $notSpecified35to54;
                    $ticks[$index]                      = $this->getLanguageValue("lbl35to54");
                    $index++;
                }
                if (in_array("above55", $filterAge)) {
                    $maleData[$index]['graphX']         = $index;
                    $maleData[$index]['graphY']         = $maleAbove55;
                    $femaleData[$index]['graphX']       = $index;
                    $femaleData[$index]['graphY']       = $femaleAbove55;
                    $notSpecifiedData[$index]['graphX'] = $index;
                    $notSpecifiedData[$index]['graphY'] = $notSpecifiedAbove55;
                    $ticks[$index]                      = $this->getLanguageValue("lbl55plus");
                    $index++;
                }
                if (in_array("notage", $filterAge)) {
                    $maleData[$index]['graphX']         = $index;
                    $maleData[$index]['graphY']         = $maleNotSpecified;
                    $femaleData[$index]['graphX']       = $index;
                    $femaleData[$index]['graphY']       = $femaleNotSpecified;
                    $notSpecifiedData[$index]['graphX'] = $index;
                    $notSpecifiedData[$index]['graphY'] = $notSpecifiedNotSpecified;
                    $ticks[$index]                      = $this->getLanguageValue("lblNotSpecified");
                    $index++;
                }
                $index       = 0;
                $mainCorors  = array(
                    'male' => "#1999cf",
                    'female' => "#d41857",
                    'Not Specified' => "#0e8f05"
                );
                $graphLabels = '';
                if (in_array("male", $filterGender)) {
                    $ageGenderGraphData[$index] = $maleData;
                    $graphLabels .= $this->getLanguageValue("lblMale") . ',';
                    $color[$index] = $mainCorors['male'];
                    $index++;
                }
                if (in_array("female", $filterGender)) {
                    $ageGenderGraphData[$index] = $femaleData;
                    $graphLabels .= $this->getLanguageValue("lblFemale") . ',';
                    $color[$index] = $mainCorors['female'];
                    $index++;
                }
                if (in_array("Not Specified", $filterGender)) {
                    $graphLabels .= $this->getLanguageValue("lblNotSpecified") . ',';
                    $color[$index]              = $mainCorors['Not Specified'];
                    $ageGenderGraphData[$index] = $notSpecifiedData;
                    $index++;
                }
                $ageGenderDistributionSettings['placeholder']             = 'ageGenderDistribution';
                $ageGenderDistributionSettings['fill']                    = 'false';
                $ageGenderDistributionSettings['graphLabels']             = substr($graphLabels, 0, -1);
                $ageGenderDistributionSettings['graphTotalLabels']        = substr($graphLabels, 0, -1);
                $ageGenderDistributionSettings['ticksForbarGraph']        = $ticks;
                $ageGenderDistributionSettings['tootlTipXLabel']          = $counter;
                $ageGenderDistributionSettings['graphColors']             = $color;
                $ageGenderDistributionSettings['graphTotalHolder']        = 'ageGenderDistributiongraphTotalHolder';
                $ageGenderDistributionSettings['graphTotalHolderUlClass'] = 'graphTotalHolderUl';
                $ageGenderDistributionSettings['legendHolder']            = 'ageGenderDistributionLegend';
                $ageGenderDistributionSettings['legendColumns']           = count($filterGender);
                $ageGenderDistributionSettings['mode']                    = 'null';
                $ageGenderDistributionSettings['graphType']               = 'bar';
                $ageGenderDistributionSettings['multiBar']                = 'true';
                $ageGenderDistributionSettings['barWidth']                = '0.2';
                $ageGenderDistributionSettings['hoverable']               = 'true';
                $ageGenderDistributionSettings['includeScript']           = 'false';
                $ageGenderDistributionSettings['enableSelection']         = false;
                $ageGenderDistributionSettings['javascript_path']         = $this->ObjView->_javascript_path;
                $ageGenderDistributionGraph                               = $ObjFlot->init($ageGenderGraphData, 0, $ageGenderDistributionSettings);
            } else {
                echo '<div class="noDataFound">' . $this->getLanguageValue("lblNoData") . '</div>';
                exit;
            }
            echo $ageGenderDistributionGraph;
        } else {
            echo '<div class="noDataFound">' . $this->getLanguageValue("lblNoData") . '</div>';
        }
    }
    public function locationAction() {
        $ObjLog             = new AnalyticsModel();
        $ObjState           = new StateModel();
        $ObjCountry         = new CountryModel();
        $languageIDs        = $this->ObjView->languageIDs;
        $settingsDateFormat = $this->getSettingValue("site_settings", "date_format");
        $merchantID         = $this->ObjSession->getSession("BUSINESS_USER_ID");
        $link               = '';
        $ageArray           = array("below17","18-24","25-34","35-54","above55","notage");
        $genderArray        = array("Male","Female","Not Specified");
        if (isset($_POST['submitSearch'])) {
            $sortByOption = isset($_POST['sortByOption']) ? $_POST['sortByOption'] : '';
            $sortByOrder  = isset($_POST['sortByOrder']) ? $_POST['sortByOrder'] : '';
            $age          = isset($_POST['searchAge']) ? $_POST['searchAge'] : '';
            $gender       = isset($_POST['searchGender']) ? $_POST['searchGender'] : '';
            $date         = isset($_POST['date']) ? $_POST['date'] : '';
            if (isset($age) && $age != '')
                $searchAge = implode(":", $age);
            if (isset($gender) && $gender != '')
                $searchGender = implode(":", $gender);
            if ($date) {
                if (strpos($date, 'to') > 0) {
                    $queryString = explode(' to ', $date);
                    $firstDate   = date("Y-m-d", strtotime($queryString[0] . ' 00:00:00'));
                    $lastDay     = date("Y-m-d", strtotime($queryString[1] . ' 00:00:00'));
                    $date        = $firstDate . " to " . $lastDay;
                } else {
                    $date = date("Y-m-d", strtotime($date . ' 00:00:00'));
                }
            }
            if (is_array($gender) && count(array_filter($gender)) > 0) {
                $link .= "gender/" . $searchGender . "/";
            }
            if (is_array($age) && count(array_filter($age)) > 0) {
                $link .= "age/" . $searchAge . "/";
            }
            if ($date) {
                $link .= "date/" . $date . "/";
            }
            $this->setRedirect("analytics/location/" . $link);
        } else {
            $searchAge         = $this->getRequestValue("age");
            $searchAgeArray    = ($searchAge != '') ? explode(":", $searchAge) : array();
            $searchGender      = $this->getRequestValue("gender");
            $searchGenderArray = ($searchGender != '') ? explode(":", $searchGender) : array();
            $toDate            = date("Y-m-d");
            $fromDate          = date("Y-m-d", strtotime("- 7 day"));
            $formattedDate     = $fromDate . " to " . $toDate;
            $date              = ($this->getRequestValue("date") != '') ? $this->getRequestValue("date") : $formattedDate;
            if($this->getRequestValue("date")!='') {
                if (strpos($this->getRequestValue("date"), 'to') > 0) {
                    $queryString      = explode(' to ', $this->getRequestValue("date"));
                    $searchFromDate   = $queryString[0];  
                    $searchToDate   = $queryString[1];  
                } else {
                    $searchFromDate   = $this->getRequestValue("date");
                }
                $dateint              = strtotime($searchFromDate);
                if(!(int)$dateint){
                    $date = $formattedDate;
                } 
                 $searchToDate       = isset($searchToDate) ? $searchToDate : '';
                if($searchToDate!=''){
                    $dateToint            = strtotime($searchToDate);
                    if(!(int)$dateToint){
                        $this->setRedirect("analytics/location/");
                    } 
                }
            }
            $sortByOption      = $this->getRequestValue("sortby");
            $sortByOrder       = $this->getRequestValue("orderby");
            if ($searchGender != '') {
                $link .= "gender/" . $searchGender . "/";
            }
            if ($searchAge != '') {
                $link .= "age/" . $searchAge . "/";
            }
            if ($date != '') {
                $link .= "date/" . $date . "/";
            }
            $sortByOption = ($this->getRequestValue("sortby") != '') ? $this->getRequestValue("sortby") : "cityName";
            $sortByOrder  = ($this->getRequestValue("orderby") != '') ? $this->getRequestValue("orderby") : "asc";
            if ($sortByOption == 'user' && $sortByOrder == "asc") {
                $sortByOrderVisit = "desc";
            } else {
                $sortByOrderVisit = "asc";
            }
            if ($sortByOption == 'cityName' && $sortByOrder == "asc") {
                $sortByOrderCity = "desc";
            } else {
                $sortByOrderCity = "asc";
            }
            if ($sortByOption == 'orderCount' && $sortByOrder == "asc") {
                $sortByOrderOrder = "desc";
            } else {
                $sortByOrderOrder = "asc";
            }
            if ($sortByOption == 'orderAmount' && $sortByOrder == "asc") {
                $sortByOrderOrderAmount = "desc";
            } else {
                $sortByOrderOrderAmount = "asc";
            }
        }
        
        if(!empty($searchAgeArray)) {
            foreach($searchAgeArray as $age) {
                if(!in_array($age, $ageArray)) {
                    $searchAgeArray = '';
                    continue;
                }
            }
        }
        if(!empty($searchGenderArray)) {
            foreach($searchGenderArray as $gender) {
                if(!in_array($gender, $genderArray)) {
                    $searchGenderArray = '';
                    continue;
                }
            }
        }
        //  list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page', $rows = 10);
        $result    = $ObjLog->getCustomerAgeGenderDetails('sql', $merchantID, $searchAgeArray, $searchGenderArray, $date);
        //  $resPagesCount = $this->setPagesCount($key = 'page');
        $resultLog = $resultLogTemp = array();
        if (count($result) > 0) {
            foreach ($result as $key => $value) {
                $billingAddress                    = unserialize($value['billingAddress']);
                $newKey                            = $billingAddress['billingCountry'] . "_" . $billingAddress['billingState'] . "_" . $billingAddress['billingCity'];
                $resultLog[$newKey]['cityName']    = $billingAddress['billingCity'];
                $resultLog[$newKey]['orderCount']  = isset($resultLog[$newKey]['orderCount']) ? ($resultLog[$newKey]['orderCount'] + 1) : 1;
                $resultLog[$newKey]['orderAmount'] = isset($resultLog[$newKey]['orderAmount']) ? ($resultLog[$newKey]['orderAmount'] + $value['orderTotalAmount']) : $value['orderTotalAmount'];
                //Temp array values
                //  if(isset($resultLogTemp[$newKey]['state']) && $resultLogTemp[$newKey]['state']=='')
                $resultLogTemp[$newKey]['state']   = $billingAddress['billingState'];
                //  if(isset($resultLogTemp[$newKey]['country']) && $resultLogTemp[$newKey]['country']=='')
                $resultLogTemp[$newKey]['country'] = $billingAddress['billingCountry'];
                $resultLogTemp[$newKey]['users'][] = $value['userID'];
            }
            foreach ($resultLogTemp as $key => $userarray) {
                $resultLog[$key]['users'] = array_count_values($userarray['users']);
                if (isset($userarray['state']) && $userarray['state'] > 0)
                    $resultLog[$key]['stateName'] = $ObjState->getStateNameByID($userarray['state'], $languageIDs);
                if (isset($userarray['country']) && $userarray['country'] > 0)
                    $resultLog[$key]['countryName'] = $ObjCountry->getCountryNameByID($userarray['country'], $languageIDs);
                $resultLog[$key]['user'] = count($resultLog[$key]['users']);
            }
        }
        // echo "<pre>";print_r($resultLog);exit;
        $resultSet   = $this->sortMultiArray($resultLog, $sortByOption, $sortByOrder);
        // echo "<pre>";print_r($resultSet);exit;
        $resultTotal = $ObjLog->getTotalCountsCustomer($merchantID, $searchAgeArray, $searchGenderArray, $date);
        $this->ObjView->assign('sortByOption', $sortByOption);
        $this->ObjView->assign('link', $link);
        $this->ObjView->assign('sortByOrderCity', $sortByOrderCity);
        $this->ObjView->assign('sortByOrderVisit', $sortByOrderVisit);
        $this->ObjView->assign('sortByOrderOrder', $sortByOrderOrder);
        $this->ObjView->assign('sortByOrderOrderAmount', $sortByOrderOrderAmount);
        $this->ObjView->assign("searchGenderSelect", str_replace(":", "~*", $searchGender));
        $this->ObjView->assign("searchAgeSelect", str_replace(":", "~*", $searchAge));
        if (substr_count($date, "to") > 0) {
            $dateArr           = explode("to", $date);
            $fromDate          = $dateArr[0];
            $toDate            = $dateArr[1];
            $formattedFromDate = $this->changeToSystemDateFormat($settingsDateFormat, $fromDate);
            $formattedToDate   = $this->changeToSystemDateFormat($settingsDateFormat, $toDate);
            $formattedDate     = $formattedFromDate . " to " . $formattedToDate;
        } else {
            $fromDate      = $date;
            $formattedDate = $this->changeToSystemDateFormat($settingsDateFormat, $fromDate);
        }
        $this->ObjView->assign("date", $formattedDate);
        $this->ObjView->assign("resultLog", $resultSet);
        $this->ObjView->assign("resultLogTotal", $resultTotal);
        $this->ObjView->assign("cityNameString", isset($cityNameString) ? $cityNameString : '');
        $this->ObjView->display('AnalyticsLocation.tpl');
    }
    public function agegenderAction() {
        $ObjLog              = new AnalyticsModel();
        $ObjFlot             = new Flot();
        $settingsDateFormat  = $this->getSettingValue("site_settings", "date_format");
        $merchantID          = $this->ObjSession->getSession("BUSINESS_USER_ID");
        $counter             = "Customers";
        $link                = '';
        $ageArray            = array("below17","18-24","25-34","35-54","above55","notage");
        $genderArray         = array("Male","Female","Not Specified");
        $colorArray          = array(
            'Male' => '#1999cf',
            'Female' => '#d41857',
            'Not Specified' => '#0e8f05'
        );
        $colorWeekGraphArray = array(
            'below17' => '#f88f25',
            '18-24' => '#1999cf',
            '25-34' => '#0e8f05',
            '35-54' => '#ba084a',
            'above55' => '#ff6868',
            'notage' => '#64C6B9'
        );
        if (isset($_POST['submitSearch'])) {
            $age    = isset($_POST['searchAge']) ? $_POST['searchAge'] : '';
            $gender = isset($_POST['searchGender']) ? $_POST['searchGender'] : '';
            $date   = isset($_POST['date']) ? $_POST['date'] : '';
            ;
            if ($date) {
                if (strpos($date, 'to') > 0) {
                    $queryString = explode(' to ', $date);
                    $firstDate   = date("Y-m-d", strtotime($queryString[0] . ' 00:00:00'));
                    $lastDay     = date("Y-m-d", strtotime($queryString[1] . ' 00:00:00'));
                    $date        = $firstDate . " to " . $lastDay;
                } else {
                    $date = date("Y-m-d", strtotime($date . ' 00:00:00'));
                }
            }
            if (isset($age) && $age != '')
                $searchAge = implode(":", $age);
            if (isset($gender) && $gender != '')
                $searchGender = implode(":", $gender);
            if (is_array($gender) && count(array_filter($gender)) > 0) {
                $link .= "gender/" . $searchGender . "/";
            }
            if (is_array($age) && count(array_filter($age)) > 0) {
                $link .= "age/" . $searchAge . "/";
            }
            if ($date) {
                $link .= "date/" . $date . "/";
            }
            $this->setRedirect("analytics/agegender/" . $link);
        } else {
            $searchAge         = $this->getRequestValue("age");
            $searchAgeArray    = ($searchAge != '') ? explode(":", $searchAge) : array();
            $searchGender      = $this->getRequestValue("gender");
            $searchGenderArray = ($searchGender != '') ? explode(":", $searchGender) : array();
            $toDate            = date("Y-m-d");
            $fromDate          = date("Y-m-d", strtotime("- 7 day"));
            $formattedDate     = $fromDate . " to " . $toDate;
            $date              = ($this->getRequestValue("date") != '') ? $this->getRequestValue("date") : $formattedDate;
            if($this->getRequestValue("date")!='') {
                if (strpos($this->getRequestValue("date"), 'to') > 0) {
                    $queryString      = explode(' to ', $this->getRequestValue("date"));
                    $searchFromDate   = $queryString[0]; 
                    $searchToDate   = $queryString[1];     
                } else {
                    $searchFromDate   = $this->getRequestValue("date");
                }
                $dateint              = strtotime($searchFromDate);
                if(!(int)$dateint){
                    $date = $formattedDate;
                } 
                 $searchToDate       = isset($searchToDate) ? $searchToDate : '';
                 if($searchToDate!=''){
                    $dateToint            = strtotime($searchToDate);
                    if(!(int)$dateToint){
                        $this->setRedirect("analytics/agegender/");
                    } 
                }
            }
            if ($searchGender != '') {
                $link .= "gender/" . $searchGender . "/";
            }
            if ($searchAge != '') {
                $link .= "age/" . $searchAge . "/";
            }
            if ($date != '') {
                $link .= "date/" . $date . "/";
            }
        }
        if(!empty($searchAgeArray)) {
            foreach($searchAgeArray as $age) {
                if(!in_array($age, $ageArray)) {
                    $searchAgeArray = '';
                    continue;
                }
            }
        }
        if(!empty($searchGenderArray)) {
            foreach($searchGenderArray as $gender) {
                if(!in_array($gender, $genderArray)) {
                    $searchGenderArray = '';
                    continue;
                }
            }
        }
        $resultsSet          = $ObjLog->getCustomerAgeGenderDetails('object', $merchantID, $searchAgeArray, $searchGenderArray, $date);
        $totalResults        = $ObjLog->getTotalCountsCustomer($merchantID, $searchAgeArray, $searchGenderArray, $date);
        $visitCount          = $resultsSet->num_rows;
        $userIdArr           = array();
        $femaleBelow17       = $femaleNotAge = $female18to24 = $female25to34 = $female35to54 = $femaleAbove55 = $femaleNotSpecified = 0;
        $maleBelow17         = $maleNotAge = $male18to24 = $male25to34 = $male35to54 = $maleAbove55 = $maleNotSpecified = 0;
        $notSpecifiedBelow17 = $notSpecifiedNotAge = $notSpecified18to24 = $notSpecified25to34 = $notSpecified35to54 = $notSpecifiedAbove55 = $notSpecifiedNotSpecified = 0;
        $maleData            = $femaleData = $notSpecifiedData = array();
        $weekBelow17         = $week18to24 = $week25to34 = $week35to54 = $weekAbove55 = $weekNotAge = array();
        if ($visitCount > 0) {
            for ($i = 0; $i < $visitCount; $i++) {
                $result = $resultsSet->fetch_array(MYSQLI_ASSOC);
                if (!in_array($result['userID'], $userIdArr)) {
                    switch ($result['userSex']) {
                        case 'Male':
                            if ($result['userAge'] > 0) {
                                if ($result['userAge'] <= 17) {
                                    $maleBelow17++;
                                } else if ($result['userAge'] > 17 && $result['userAge'] <= 24) {
                                    $male18to24++;
                                } else if ($result['userAge'] > 24 && $result['userAge'] <= 34) {
                                    $male25to34++;
                                } else if ($result['userAge'] > 34 && $result['userAge'] <= 54) {
                                    $male35to54++;
                                } else {
                                    $maleAbove55++;
                                }
                            } else {
                                $maleNotAge++;
                            }
                            break;
                        case 'Female':
                            if ($result['userAge'] > 0) {
                                if ($result['userAge'] <= 17) {
                                    $femaleBelow17++;
                                } else if ($result['userAge'] > 17 && $result['userAge'] <= 24) {
                                    $female18to24++;
                                } else if ($result['userAge'] > 24 && $result['userAge'] <= 34) {
                                    $female25to34++;
                                } else if ($result['userAge'] > 34 && $result['userAge'] <= 54) {
                                    $female35to54++;
                                } else {
                                    $femaleAbove55++;
                                }
                            } else {
                                $femaleNotAge++;
                            }
                            break;
                        case 'Not Specified':
                            if ($result['userAge'] > 0) {
                                if ($result['userAge'] <= 17) {
                                    $notSpecifiedBelow17++;
                                } else if ($result['userAge'] > 17 && $result['userAge'] <= 24) {
                                    $notSpecified18to24++;
                                } else if ($result['userAge'] > 24 && $result['userAge'] <= 34) {
                                    $notSpecified25to34++;
                                } else if ($result['userAge'] > 34 && $result['userAge'] <= 54) {
                                    $notSpecified35to54++;
                                } else {
                                    $notSpecifiedAbove55++;
                                }
                            } else {
                                $notSpecifiedNotAge++;
                            }
                            break;
                    }
                    if ($result['userAge'] > 0) {
                        if ($result['userAge'] <= 17) {
                            $weekBelow17[] = $result['weekday'];
                        } else if ($result['userAge'] > 17 && $result['userAge'] <= 24) {
                            $week18to24[] = $result['weekday'];
                        } else if ($result['userAge'] > 24 && $result['userAge'] <= 34) {
                            $week25to34[] = $result['weekday'];
                        } else if ($result['userAge'] > 34 && $result['userAge'] <= 54) {
                            $week35to54[] = $result['weekday'];
                        } else {
                            $weekAbove55[] = $result['weekday'];
                        }
                    } else {
                        $weekNotAge[] = $result['weekday'];
                    }
                    $userIdArr[] = $result['userID'];
                }
                unset($result);
            }
            $resultsSet->free();
            $weekBelow17Count = (count($weekBelow17) > 0) ? array_count_values($weekBelow17) : array();
            $week18to24Count  = (count($week18to24) > 0) ? array_count_values($week18to24) : array();
            $week25to34Count  = (count($week25to34) > 0) ? array_count_values($week25to34) : array();
            $week35to54Count  = (count($week35to54) > 0) ? array_count_values($week35to54) : array();
            $weekAbove55Count = (count($weekAbove55) > 0) ? array_count_values($weekAbove55) : array();
            $weekNotAgeCount  = (count($weekNotAge) > 0) ? array_count_values($weekNotAge) : array();
            unset($weekBelow17);
            unset($week18to24);
            unset($week25to34);
            unset($week35to54);
            unset($weekAbove55);
            unset($weekNotAge);
            $weekBelow17GraphData = $week18to24GraphData = $week25to34GraphData = $week35to54GraphData = $weekAbove55GraphData = $weekNotAgeGraphData = array();
            $weekDays             = array(
                1 => $this->getLanguageValue("lblSun"),
                2 => $this->getLanguageValue("lblMon"),
                3 => $this->getLanguageValue("lblTue"),
                4 => $this->getLanguageValue("lblWed"),
                5 => $this->getLanguageValue("lblThu"),
                6 => $this->getLanguageValue("lblFri"),
                7 => $this->getLanguageValue("lblSat")
            );
            for ($i = 1; $i < 8; $i++) {
                $weekBelow17GraphData[$i - 1]['graphX'] = $i;
                $weekBelow17GraphData[$i - 1]['graphY'] = 0;
                $week18to24GraphData[$i - 1]['graphX']  = $i;
                $week18to24GraphData[$i - 1]['graphY']  = 0;
                $week25to34GraphData[$i - 1]['graphX']  = $i;
                $week25to34GraphData[$i - 1]['graphY']  = 0;
                $week35to54GraphData[$i - 1]['graphX']  = $i;
                $week35to54GraphData[$i - 1]['graphY']  = 0;
                $weekAbove55GraphData[$i - 1]['graphX'] = $i;
                $weekAbove55GraphData[$i - 1]['graphY'] = 0;
                $weekNotAgeGraphData[$i - 1]['graphX']  = $i;
                $weekNotAgeGraphData[$i - 1]['graphY']  = 0;
            }
            if (count($weekBelow17Count) > 0) {
                foreach ($weekBelow17Count as $key => $value) {
                    $weekBelow17GraphData[$key - 1]['graphX'] = $key;
                    $weekBelow17GraphData[$key - 1]['graphY'] = $value;
                }
                unset($weekBelow17Count);
            }
            if (count($week18to24Count) > 0) {
                foreach ($week18to24Count as $key => $value) {
                    $week18to24GraphData[$key - 1]['graphX'] = $key;
                    $week18to24GraphData[$key - 1]['graphY'] = $value;
                }
                unset($week18to24Count);
            }
            if (count($week25to34Count) > 0) {
                foreach ($week25to34Count as $key => $value) {
                    $week25to34GraphData[$key - 1]['graphX'] = $key;
                    $week25to34GraphData[$key - 1]['graphY'] = $value;
                }
                unset($week25to34Count);
            }
            if (count($week35to54Count) > 0) {
                foreach ($week35to54Count as $key => $value) {
                    $week35to54GraphData[$key - 1]['graphX'] = $key;
                    $week35to54GraphData[$key - 1]['graphY'] = $value;
                }
                unset($week35to54Count);
            }
            if (count($weekAbove55Count) > 0) {
                foreach ($weekAbove55Count as $key => $value) {
                    $weekAbove55GraphData[$key - 1]['graphX'] = $key;
                    $weekAbove55GraphData[$key - 1]['graphY'] = $value;
                }
                unset($weekAbove55Count);
            }
            if (count($weekNotAgeCount) > 0) {
                foreach ($weekNotAgeCount as $key => $value) {
                    $weekNotAgeGraphData[$key - 1]['graphX'] = $key;
                    $weekNotAgeGraphData[$key - 1]['graphY'] = $value;
                }
                unset($weekNotAgeCount);
            }
            $index = 0;
            if (count($searchAgeArray) > 0) {
                if (in_array("below17", $searchAgeArray)) {
                    $maleData[$index]['graphX']         = $index;
                    $maleData[$index]['graphY']         = $maleBelow17;
                    $femaleData[$index]['graphX']       = $index;
                    $femaleData[$index]['graphY']       = $femaleBelow17;
                    $notSpecifiedData[$index]['graphX'] = $index;
                    $notSpecifiedData[$index]['graphY'] = $notSpecifiedBelow17;
                    $ticks[$index]                      = $this->getLanguageValue("lbl0to17");
                    $weeklyGraphArray[$index]           = $weekBelow17GraphData;
                    $colorWeek[$index]                  = $colorWeekGraphArray['below17'];
                    $index++;
                }
                if (in_array("18-24", $searchAgeArray)) {
                    $maleData[$index]['graphX']         = $index;
                    $maleData[$index]['graphY']         = $male18to24;
                    $femaleData[$index]['graphX']       = $index;
                    $femaleData[$index]['graphY']       = $female18to24;
                    $notSpecifiedData[$index]['graphX'] = $index;
                    $notSpecifiedData[$index]['graphY'] = $notSpecified18to24;
                    $ticks[$index]                      = $this->getLanguageValue("lbl18to24");
                    $weeklyGraphArray[$index]           = $week18to24GraphData;
                    $colorWeek[$index]                  = $colorWeekGraphArray['18-24'];
                    $index++;
                }
                if (in_array("25-34", $searchAgeArray)) {
                    $maleData[$index]['graphX']         = $index;
                    $maleData[$index]['graphY']         = $male25to34;
                    $femaleData[$index]['graphX']       = $index;
                    $femaleData[$index]['graphY']       = $female25to34;
                    $notSpecifiedData[$index]['graphX'] = $index;
                    $notSpecifiedData[$index]['graphY'] = $notSpecified25to34;
                    $ticks[$index]                      = $this->getLanguageValue("lbl25to34");
                    $weeklyGraphArray[$index]           = $week25to34GraphData;
                    $colorWeek[$index]                  = $colorWeekGraphArray['25-34'];
                    $index++;
                }
                if (in_array("35-54", $searchAgeArray)) {
                    $maleData[$index]['graphX']         = $index;
                    $maleData[$index]['graphY']         = $male35to54;
                    $femaleData[$index]['graphX']       = $index;
                    $femaleData[$index]['graphY']       = $female35to54;
                    $notSpecifiedData[$index]['graphX'] = $index;
                    $notSpecifiedData[$index]['graphY'] = $notSpecified35to54;
                    $ticks[$index]                      = $this->getLanguageValue("lbl35to54");
                    $weeklyGraphArray[$index]           = $week35to54GraphData;
                    $colorWeek[$index]                  = $colorWeekGraphArray['35-54'];
                    $index++;
                }
                if (in_array("above55", $searchAgeArray)) {
                    $maleData[$index]['graphX']         = $index;
                    $maleData[$index]['graphY']         = $maleAbove55;
                    $femaleData[$index]['graphX']       = $index;
                    $femaleData[$index]['graphY']       = $femaleAbove55;
                    $notSpecifiedData[$index]['graphX'] = $index;
                    $notSpecifiedData[$index]['graphY'] = $notSpecifiedAbove55;
                    $ticks[$index]                      = $this->getLanguageValue("lbl55plus");
                    $weeklyGraphArray[$index]           = $weekAbove55GraphData;
                    $colorWeek[$index]                  = $colorWeekGraphArray['above55'];
                    $index++;
                }
                if (in_array("notage", $searchAgeArray)) {
                    $maleData[$index]['graphX']         = $index;
                    $maleData[$index]['graphY']         = $maleNotAge;
                    $femaleData[$index]['graphX']       = $index;
                    $femaleData[$index]['graphY']       = $femaleNotAge;
                    $notSpecifiedData[$index]['graphX'] = $index;
                    $notSpecifiedData[$index]['graphY'] = $notSpecifiedNotAge;
                    $ticks[$index]                      = $this->getLanguageValue("lblNotSpecified");
                    $weeklyGraphArray[$index]           = $weekNotAgeGraphData;
                    $colorWeek[$index]                  = $colorWeekGraphArray['notage'];
                    $index++;
                }
            } else {
                $maleData[0]['graphX']         = 0;
                $maleData[0]['graphY']         = $maleBelow17;
                $femaleData[0]['graphX']       = 0;
                $femaleData[0]['graphY']       = $femaleBelow17;
                $notSpecifiedData[0]['graphX'] = 0;
                $notSpecifiedData[0]['graphY'] = $notSpecifiedBelow17;
                $ticks[0]                      = $this->getLanguageValue("lbl0to17");
                $maleData[1]['graphX']         = 1;
                $maleData[1]['graphY']         = $male18to24;
                $femaleData[1]['graphX']       = 1;
                $femaleData[1]['graphY']       = $female18to24;
                $notSpecifiedData[1]['graphX'] = 1;
                $notSpecifiedData[1]['graphY'] = $notSpecified18to24;
                $ticks[1]                      = $this->getLanguageValue("lbl18to24");
                $maleData[2]['graphX']         = 2;
                $maleData[2]['graphY']         = $male25to34;
                $femaleData[2]['graphX']       = 2;
                $femaleData[2]['graphY']       = $female25to34;
                $notSpecifiedData[2]['graphX'] = 2;
                $notSpecifiedData[2]['graphY'] = $notSpecified25to34;
                $ticks[2]                      = $this->getLanguageValue("lbl25to34");
                $maleData[3]['graphX']         = 3;
                $maleData[3]['graphY']         = $male35to54;
                $femaleData[3]['graphX']       = 3;
                $femaleData[3]['graphY']       = $female35to54;
                $notSpecifiedData[3]['graphX'] = 3;
                $notSpecifiedData[3]['graphY'] = $notSpecified35to54;
                $ticks[3]                      = $this->getLanguageValue("lbl35to54");
                $maleData[4]['graphX']         = 4;
                $maleData[4]['graphY']         = $maleAbove55;
                $femaleData[4]['graphX']       = 4;
                $femaleData[4]['graphY']       = $femaleAbove55;
                $notSpecifiedData[4]['graphX'] = 4;
                $notSpecifiedData[4]['graphY'] = $notSpecifiedAbove55;
                $ticks[4]                      = $this->getLanguageValue("lbl55plus");
                $maleData[5]['graphX']         = 5;
                $maleData[5]['graphY']         = $maleNotAge;
                $femaleData[5]['graphX']       = 5;
                $femaleData[5]['graphY']       = $femaleNotAge;
                $notSpecifiedData[5]['graphX'] = 5;
                $notSpecifiedData[5]['graphY'] = $notSpecifiedNotAge;
                $ticks[5]                      = $this->getLanguageValue("lblNotSpecified");
                $weeklyGraphArray[0]           = $weekBelow17GraphData;
                $colorWeek[0]                  = $colorWeekGraphArray['below17'];
                $weeklyGraphArray[1]           = $week18to24GraphData;
                $colorWeek[1]                  = $colorWeekGraphArray['18-24'];
                $weeklyGraphArray[2]           = $week25to34GraphData;
                $colorWeek[2]                  = $colorWeekGraphArray['25-34'];
                $weeklyGraphArray[3]           = $week35to54GraphData;
                $colorWeek[3]                  = $colorWeekGraphArray['35-54'];
                $weeklyGraphArray[4]           = $weekAbove55GraphData;
                $colorWeek[4]                  = $colorWeekGraphArray['above55'];
                $weeklyGraphArray[5]           = $weekNotAgeGraphData;
                $colorWeek[5]                  = $colorWeekGraphArray['notage'];
            }
            $index       = 0;
            $graphLabels = '';
            if (count($searchGenderArray) > 0) {
                if (in_array("Male", $searchGenderArray)) {
                    $ageGenderGraphData[$index] = $maleData;
                    $graphLabels .= $this->getLanguageValue("lblMale") . ',';
                    $color[$index] = $colorArray['Male'];
                    $index++;
                }
                if (in_array("Female", $searchGenderArray)) {
                    $ageGenderGraphData[$index] = $femaleData;
                    $graphLabels .= $this->getLanguageValue("lblFemale") . ',';
                    $color[$index] = $colorArray['Female'];
                    $index++;
                }
                if (in_array("Not Specified", $searchGenderArray)) {
                    $graphLabels .= $this->getLanguageValue("lblNotSpecified") . ',';
                    $ageGenderGraphData[$index] = $notSpecifiedData;
                    $color[$index]              = $colorArray['Not Specified'];
                    $index++;
                }
                $legendColumns = count($searchGenderArray);
                $genderArray   = $searchGenderArray;
            } else {
                $ageGenderGraphData[0] = $maleData;
                $graphLabels .= $this->getLanguageValue("lblMale") . ',';
                $color[0]              = $colorArray['Male'];
                $ageGenderGraphData[1] = $femaleData;
                $color[1]              = $colorArray['Female'];
                $graphLabels .= $this->getLanguageValue("lblFemale") . ',';
                $graphLabels .= $this->getLanguageValue("lblNotSpecified") . ',';
                $ageGenderGraphData[2] = $notSpecifiedData;
                $color[2]              = $colorArray['Not Specified'];
                $legendColumns         = 5;
                $genderArray           = array(
                    0 => $this->getLanguageValue("lblMale"),
                    1 => $this->getLanguageValue("lblFemale"),
                    2 => $this->getLanguageValue("lblNotSpecified")
                );
            }
            $ageGenderDistributionSettings['placeholder']             = 'ageGenderDistribution';
            $ageGenderDistributionSettings['fill']                    = 'false';
            $ageGenderDistributionSettings['graphLabels']             = substr($graphLabels, 0, -1);
            $ageGenderDistributionSettings['graphTotalLabels']        = substr($graphLabels, 0, -1);
            $ageGenderDistributionSettings['ticksForbarGraph']        = $ticks;
            $ageGenderDistributionSettings['tootlTipXLabel']          = $counter;
            $ageGenderDistributionSettings['graphTotalHolder']        = 'ageGenderDistributiongraphTotalHolder';
            $ageGenderDistributionSettings['graphTotalHolderUlClass'] = 'graphTotalHolderUl';
            $ageGenderDistributionSettings['legendHolder']            = 'ageGenderDistributionLegend';
            $ageGenderDistributionSettings['graphColors']             = $color;
            $ageGenderDistributionSettings['legendColumns']           = 3;
            $ageGenderDistributionSettings['mode']                    = 'null';
            $ageGenderDistributionSettings['graphType']               = 'bar';
            $ageGenderDistributionSettings['multiBar']                = 'true';
            $ageGenderDistributionSettings['barWidth']                = '0.2';
            $ageGenderDistributionSettings['hoverable']               = 'true';
            $ageGenderDistributionSettings['enableSelection']         = 'false';
            $ageGenderDistributionSettings['javascript_path']         = $this->ObjView->_javascript_path;
            $ageGenderDistributionGraph                               = $ObjFlot->init($ageGenderGraphData, 0, $ageGenderDistributionSettings);
            $weeklyReportSettings['placeholder']                      = 'weeklyReport';
            $weeklyReportSettings['fill']                             = 'false';
            $weeklyReportSettings['graphLabels']                      = implode(",", $ticks);
            $weeklyReportSettings['graphTotalLabels']                 = implode(",", $ticks);
            $weeklyReportSettings['ticksForLineGraph']                = $weekDays;
            $weeklyReportSettings['graphTotalHolder']                 = 'weeklyReportgraphTotalHolder';
            $weeklyReportSettings['graphTotalHolderUlClass']          = 'graphTotalHolderUl';
            $weeklyReportSettings['legendHolder']                     = 'weeklyReportLegend';
            $weeklyReportSettings['legendColumns']                    = count($ticks);
            $weeklyReportSettings['graphColors']                      = $colorWeek;
            $weeklyReportSettings['mode']                             = 'null';
            $weeklyReportSettings['enableSelection']                  = false;
            $weeklyReportSettings['graphType']                        = 'line';
            $weeklyReportSettings['javascript_path']                  = $this->ObjView->_javascript_path;
            $weeklyReportGraph                                        = $ObjFlot->init($weeklyGraphArray, 0, $weeklyReportSettings);
            unset($weeklyGraphArray);
        }
        $this->ObjView->assign('link', $link);
        $this->ObjView->assign('counter', $counter);
        $this->ObjView->assign("searchGenderSelect", str_replace(":", "~*", $searchGender));
        $this->ObjView->assign("searchAgeSelect", str_replace(":", "~*", $searchAge));
        if (substr_count($date, "to") > 0) {
            $dateArr           = explode(" to ", $date);
            $fromDate          = $dateArr[0];
            $toDate            = $dateArr[1];
            $formattedFromDate = $this->changeToSystemDateFormat($settingsDateFormat, $fromDate);
            $formattedToDate   = $this->changeToSystemDateFormat($settingsDateFormat, $toDate);
            $formattedDate     = $formattedFromDate . " to " . $formattedToDate;
        } else {
            $fromDate      = $date;
            $formattedDate = $this->changeToSystemDateFormat($settingsDateFormat, $fromDate);
        }
        $this->ObjView->assign("date", $formattedDate);
        $this->ObjView->assign("resultLog", isset($ageGenderGraphData) ? $ageGenderGraphData : array());
        $this->ObjView->assign("totalResults", $totalResults);
        $this->ObjView->assign("graphData", isset($ageGenderDistributionGraph) ? $ageGenderDistributionGraph : '');
        $this->ObjView->assign("ages", isset($ticks) ? $ticks : '');
        $this->ObjView->assign("genderTypes", isset($genderArray) ? $genderArray : array());
        $this->ObjView->assign("weeklyReport", isset($weeklyReportGraph) ? $weeklyReportGraph : '');
        $this->ObjView->display('AnalyticsAgeGender.tpl');
    }
    //FUNCTION TO LIST TOP DEALS OF THE SITE
    public function topproductAction() {
        $ObjLog             = new AnalyticsModel();
        $languageIDs        = $this->ObjView->languageIDs;
        $merchantID         = $this->ObjSession->getSession("BUSINESS_USER_ID");
        $settingsDateFormat = $this->getSettingValue("site_settings", "date_format");
        $settingsTimeFormat = $this->getSettingValue('site_settings', 'time_format');
        $link               = '';
        $queryStringLink    = '';
        $redirectLink       = '';
        list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page', $rows = 1);
        if (isset($_POST['submitSearch'])) {
            $searchDate  = $_POST['date'];            
            $datePassArr = explode("to", $searchDate);
            $date1       = isset($datePassArr[0]) ? $datePassArr[0] : '';
            $date2       = isset($datePassArr[1]) ? $datePassArr[1] : '';
            if (!$date2) {
                $queryStringLink = date("Y-m-d", strtotime($date1));
            } else {
                $queryStringLink .= date("Y-m-d", strtotime($date1)) . " to " . date("Y-m-d", strtotime($date2));
            }
            $redirectLink .= "date/" . $queryStringLink . "/";
            $this->setRedirect("analytics/topproduct/" . $redirectLink);
        }
        $dateFromURL = $this->getRequestValue("date");       
        if ($dateFromURL) {
            if (substr_count($dateFromURL, "to") > 0) {
                $dateArray         = explode("to", $dateFromURL);
                $searchFromDate    = $dateArray[0];
                $searchToDate      = $dateArray[1];
                
                $formattedFromDate = $this->changeToSystemDateFormat($settingsDateFormat, $searchFromDate);
                $formattedToDate   = $this->changeToSystemDateFormat($settingsDateFormat, $searchToDate);
                $formattedDate     = $formattedFromDate . " to " . $formattedToDate;
            } else {
                $searchFromDate = $dateFromURL;
                
                $formattedDate  = $this->changeToSystemDateFormat($settingsDateFormat, $searchFromDate);
            }
            $link = "date/" . $dateFromURL . "/";
        } else {
            $searchToDate      = date("Y-m-d");
            $searchFromDate    = date("Y-m-d", strtotime("- 7 day"));
            $formattedFromDate = $this->changeToSystemDateFormat($settingsDateFormat, $searchFromDate);
            $formattedToDate   = $this->changeToSystemDateFormat($settingsDateFormat, $searchToDate);
            $formattedDate     = $formattedFromDate . " to " . $formattedToDate;
            // $formattedDate 			= 	$this->changeToSystemDateFormat($settingsDateFormat, $searchFromDate);			
        }
        $searchToDate       = isset($searchToDate) ? $searchToDate : '';
        $dateint            = strtotime($searchFromDate);
        if(!(int)$dateint){
            $this->setRedirect("analytics/topproduct/");
        } 
        if($searchToDate!=''){
            $dateToint            = strtotime($searchToDate);
            if(!(int)$dateToint){
                $this->setRedirect("analytics/topproduct/");
            } 
        }
        $resultSet          = $ObjLog->listProductsForTopProducts($languageIDs, $searchFromDate, $searchToDate, $merchantID);
        $resTopProductCount = $this->setPagesCount($key = 'page');
        if ($this->getRequestValue("sort")) {
            $sortVariable = $this->getRequestValue("sort");
        }
        if (!isset($sortVariable)) {
            $sortVariable = "totalweigtage";
        }
        if ($this->getRequestValue("order")) {
            $orderOfSorting = $this->getRequestValue("order");
        } else {
            $orderOfSorting = "desc";
        }
        switch ($sortVariable) {
            case 'totalweigtage':
                $orderOfSortVariable = $orderOfSorting;
                break;
            case 'alluniqueviews':
                $orderOfAllUniqueViews = $orderOfSorting;
                break;
            case 'uniqueviews':
                $orderOfUniqueViews = $orderOfSorting;
                break;
            case 'alltotalviews':
                $orderOfAllTotalViews = $orderOfSorting;
                break;
            case 'totalviews':
                $orderOfViews = $orderOfSorting;
                break;
            case 'allqty':
                $orderOfAllQty = $orderOfSorting;
                break;
            case 'searchspanQty':
                $orderOfSearchOrders = $orderOfSorting;
                break;
        }
        $resultSet     = $this->sortMultiArray($resultSet, $sortVariable, $orderOfSorting);
        $resPagesCount = $this->setPagesCount($key = 'page');
        $this->ObjView->assign('orderofsort', $orderOfSorting);
        $this->ObjView->assign('sortvariable', $sortVariable);
        $this->ObjView->assign('searchedDate', isset($searchTo) ? $searchTo : '');
        $this->ObjView->assign("date", $formattedDate);
        $this->ObjView->assign('resTopProduct', $resultSet);
        $this->ObjView->assign("totalweigtagesortorder", isset($orderOfSortVariable) ? $orderOfSortVariable : '');
        $this->ObjView->assign("alluniqueviewssortorder", isset($orderOfAllUniqueViews) ? $orderOfAllUniqueViews : '');
        $this->ObjView->assign("uniqueviewsortorder", isset($orderOfUniqueViews) ? $orderOfUniqueViews : '');
        $this->ObjView->assign("alltotalviewssortorder", isset($orderOfAllTotalViews) ? $orderOfAllTotalViews : '');
        $this->ObjView->assign("viewssortorder", isset($orderOfViews) ? $orderOfViews : '');
        $this->ObjView->assign("allqtysortorder", isset($orderOfAllQty) ? $orderOfAllQty : '');
        $this->ObjView->assign("qtysortorder", isset($orderOfSearchOrders) ? $orderOfSearchOrders : '');
        $this->ObjView->assign("reportgentym", date("Y-m-d H:i:s"));
        $this->ObjView->assign("link", $link);
        $this->ObjView->assign("date_format", $settingsDateFormat);
        $this->ObjView->assign("time_format", $settingsTimeFormat);
        $this->ObjView->display("TopProducts.tpl");
    }
    public function sortMultiArray($array, $indexOfArray, $sortOrder, $bounce = '', $secondSort = '') {
        if (count($array) > 0) {
            foreach ($array as $key => $row) {
                if ($bounce == 1) {
                    $column[$key] = round(($row[$indexOfArray] / $row['totalvisits']), 2);
                } else {
                    $column[$key] = trim($row[$indexOfArray]);
                }
                if ($secondSort != '') {
                    $pagename[$key] = $row[$secondSort];
                }
            }
            if (count($column) > 0) {
                if ($sortOrder == "asc") {
                    if (isset($pagename) && $pagename != '') {
                        array_multisort($column, SORT_ASC, $pagename, SORT_ASC, $array);
                    } else {
                        array_multisort($column, SORT_ASC, $array);
                    }
                } else if ($sortOrder == "desc") {
                    if (isset($pagename) && $pagename != '') {
                        array_multisort($column, SORT_DESC, $pagename, SORT_ASC, $array);
                    } else {
                        array_multisort($column, SORT_DESC, $array);
                    }
                }
                return $array;
            }
        }
    }
    public function changeToSystemDateFormat($preferedDateFormat, $date) {
        switch ($preferedDateFormat) {
            case '%Y-%m-%d': {
                $returnDateFormat = 'Y-m-d';
            }
                break;
            case '%m/%d/%Y': {
                $returnDateFormat = 'm/d/Y';
            }
                break;
            case '%d-%m-%Y': {
                $returnDateFormat = 'd-m-Y';
            }
                break;
            default:
                $returnDateFormat = 'm/d/Y';
        }
        $returnValue = date($returnDateFormat, strtotime($date));
        return $returnValue;
    }
}
