<?php
/***************************************************************************
 *                                                                          *
 * Copyright (c) 2005 ISPG Technologies (I) Pvt Ltd. All rights reserved.   *
 *                                                                          *
 * This  is  commercial  software,  only  users  who have purchased a valid *
 * license  and  accept  to the terms of the  License Agreement can install *
 * and use this program.                                                    *
 *                                                                          *
 ****************************************************************************
 * PLEASE READ THE FULL TEXT  OF THE SOFTWARE  LICENSE   AGREEMENT  IN  THE *
 * "copyright.txt" FILE PROVIDED WITH THIS DISTRIBUTION PACKAGE.            *
 ****************************************************************************/ //
//$Id: BusinessController.php, v 1.0 2011/06/14 20:52:11
//
class IndexController extends Controller {
    //BusinessController index action
    public function indexAction() {
        $ObjFlot            = new Flot();
        $ObjProduct         = new ProductModel();
        $ObjCart            = new CartModel();
        $ObjBusiness        = new BusinessModel();
        $ObjOrder           = new OrderModel();
		$ObjReport          = new ReportModel();
        $languageIDs        = $this->ObjView->languageIDs;
        $settingsDateFormat = $date_format = $this->getSettingValue('site_settings', 'date_format');
        $timeFormat         = $this->getSettingValue('site_settings', 'time_format');
        $businessID         = $this->ObjSession->getSession("BUSINESS_USER_ID");
        $businessUserID     = $this->ObjSession->getSession("BUSINESS_SUB_USER_ID");
        //Start: Graph ,Business Purchase ------------------//
        $lastDay            = mktime(0, 0, 0, date("m"), date("d") - 7, date("Y"));
        $dateFrom           = GregorianToJD(date("m", $lastDay), date("d", $lastDay), date("Y", $lastDay));
        $dateTo             = GregorianToJD(date('m'), date('d'), date('Y'));
        $arr                = array();
        $xCordArray         = array();
        $queryArr           = array();
        $arrayCounter       = 0;
        for ($dateIndex = $dateFrom; $dateIndex <= $dateTo; $dateIndex++) {
            $arrayCounter = $arrayCounter + 1;
            list($month, $day, $year) = explode('/', JDToGregorian($dateIndex));
            $month = $month < 10 ? '0' . $month : $month;
            $day   = $day < 10 ? '0' . $day : $day;
            array_push($arr, $year . "-" . $month . "-" . $day);
            ($dateIndex == $dateFrom) ? $colName = 'orderDate' : $colName = '';
            array_push($queryArr, "SELECT '" . $year . "-" . $month . "-" . $day . "' $colName");
        }
        $dateRange[0]    = $arr[0];
        $dateRange[1]    = $arr[count($arr) - 1];
        $trafficSource   = $ObjBusiness->getDashBoardGraphDetails($businessID, $dateRange, '', '', implode(' UNION ALL ', $queryArr));
        $currencyDetails = $this->ObjView->_currencies[$this->ObjView->_defaultCurrency];
        if ($currencyDetails['currencySymbolLeft'] != '') {
            $trafficReportSettings['currencyPosition'] = 'Left';
            $trafficReportSettings['currency']         = $currencyDetails['currencySymbolLeft'];
        } elseif ($currencyDetails['currencySymbolRight'] != '') {
            $trafficReportSettings['currencyPosition'] = 'Right';
            $trafficReportSettings['currency']         = $currencyDetails['currencySymbolRight'];
        }
        $trafficReportSettings['placeholder']             = 'businessGraphHolder';
        $trafficReportSettings['fill']                    = 'true';
        $trafficReportSettings['graphLabels']             = $this->getLanguageValue("lblRevenueGraph");
        $trafficReportSettings['graphTotalLabels']        = $this->getLanguageValue("lblRevenueGraph");
        $trafficReportSettings['graphTotalHolder']        = 'businessGraphHoldergraphTotalHolder';
        $trafficReportSettings['graphTotalHolderUlClass'] = 'graphTotalHolderUl';
        $trafficReportSettings['legendHolder']            = 'businessHolderLegend';
        $trafficReportSettings['legendColumns']           = 4;
        $trafficReportSettings['mode']                    = 'time';
        $trafficReportSettings['tootlTipXLabel']          = 'Day';
        $trafficReportSettings['graphType']               = 'line';
        $trafficReportSettings['enableSelection']         = 'false';
        $trafficReportSettings['graphColors']             = array(
            '#1999cf'
        );
        $trafficReportSettings['ticksForLineGraph']       = $xCordArray;
        $trafficReportSettings['javascript_path']         = $this->ObjView->_common_js_path;
        $trafficReportSettings['tooltipDecimalsY']        = 2;
        $line1                                            = array();
        $totRevenue                                       = 0;
        $totPurchase                                      = 0;
        foreach ($trafficSource as $key => $value) {
            array_push($line1, array(
                'graphX' => $value['orderDate'],
                'graphY' => $value['revenue']
            ));
            $totPurchase += $value['purchase'];
            $totRevenue += $value['revenue'];
        }
        //$trafficSource as $key => $value
        $trafficGraphArray[0] = $line1;
        $trafficReportGraph   = $ObjFlot->init($trafficGraphArray, 0, $trafficReportSettings);
        $this->ObjView->assign("graphData", $trafficReportGraph);
        //END  : End of graph-------------------------------//
        $businessUserActiveLocs = $transactionCount = $resMerchantMessageCount = $resUserMessageCount = 0;
        if ($businessID > 0) {
            $transactionCount        = $ObjBusiness->getTransactionCount($businessID);
			$params         = array(
				'businessID' => $businessID,
				'status' => 'New',
				'by' => 'Admin',
				'type' => 'merchant'
			);			
            $resMerchantMessageCount = $ObjBusiness->getNewMessageCount($params);
			$params         = array(
				'businessID' => $businessID,
				'status' => 'Verified',
				'by' => 'User',
				'type' => 'user'
			);			
            $resUserMessageCount     = $ObjBusiness->getNewMessageCount($params);
			//Messages waiting for responce (in the last 7 days)		
			$params         = array(
				'businessID' => $businessID,
				'status' => 'Verified',
				'by' => 'User',
				'fromDate' => date('Y-m-d h:i:s', strtotime("-7 day")),
				'toDate' => 'Y-m-d h:i:s',
				'type' => 'user'
			);			
            $res7daysUserMessageCount     = $ObjBusiness->getNewMessageCount($params);	
			//Messages waiting for responce (in the last 24 hrs)		
			$params         = array(
				'businessID' => $businessID,
				'status' => 'Verified',
				'by' => 'User',
				'fromDate' => date('Y-m-d h:i:s', strtotime("-1 day")),
				'toDate' => 'Y-m-d h:i:s',
				'type' => 'user'
			);			
            $resOnedaysUserMessageCount     = $ObjBusiness->getNewMessageCount($params);	
			$resBusinessRating = $ObjBusiness->selectUserRating($businessID);	
            $busAvgRating = ($resBusinessRating['ratingCount'] > 0) ? number_format($resBusinessRating['ratingTotal'] / $resBusinessRating['ratingCount'], 1) : 0;
            $this->ObjView->assign('busAvgRating', $busAvgRating);			
            $this->ObjView->assign('ratingCount', $resBusinessRating['ratingCount']);	
			$resMessages   = $ObjBusiness->listMyMessages(0, 1, $businessID, $languageIDs, '', '', '', '', '', '', '', '','Admin');			
			$resLastpayment   = $ObjReport->lastPaymentMadebyAdmin($businessID);	
			$resTransactionDet = $ObjReport->listBusinessOrdersTransactions($languageIDs, $businessID,'','','','','',0,4);			
        }
        $this->ObjView->assign("resTransactionDet", $resTransactionDet);
        $this->ObjView->assign("resLastpayment", $resLastpayment);
        $this->ObjView->assign("resMessages", $resMessages);
        $this->ObjView->assign("7daysUserMessageCount", $res7daysUserMessageCount);
        $this->ObjView->assign("OnedayUserMessageCount", $resOnedaysUserMessageCount);
        $this->ObjView->assign("transactionCount", $transactionCount);
        $this->ObjView->assign("myMessageReplyCount", $resMerchantMessageCount);
        $this->ObjView->assign("userMessageReplyCount", $resUserMessageCount);		
        $this->ObjView->assign('businessUserID', $businessID);
        $this->ObjView->assign("date_format", $settingsDateFormat);
        $this->ObjView->assign("time_format", $timeFormat);
        $resLatestProducts = $ObjProduct->latestProductOrders($languageIDs, $businessID);
        if(!empty($resLatestProducts)) {
            foreach($resLatestProducts as $latest=>$latestOrder) { 
                $getFreeProductsSubTotal    =   $ObjCart->getFreeProductsSubTotal($latestOrder['masterOrderID']);
                $resLatestProducts[$latest]['total']  = $resLatestProducts[$latest]['total'] + $getFreeProductsSubTotal;
                $resLatestProducts[$latest]['amount'] = $resLatestProducts[$latest]['amount'] + $getFreeProductsSubTotal;
            }
        }        
        $this->ObjView->assign('resDashBoard', $ObjBusiness->getDashBoardDetails($businessID));
        $this->ObjView->assign('resLatestProducts', $resLatestProducts);
        $this->ObjView->assign('dateFrom', date("Y-m-d", $lastDay));
        $this->ObjView->assign('dateTo', date('Y-m-d'));
        $avg = $totRevenue / ($arrayCounter);
        $avg = $this->ObjView->getFormattedCurrency($avg);
        $this->ObjView->assign('productAvg', $avg);
        $this->ObjView->assign('totPurachase', $totPurchase);
        $this->ObjView->assign('totRevenue', $totRevenue);
        $outOfStockCount = $ObjOrder->getOutOfStockProducts('count', $businessID);
        $this->ObjView->assign("outOfStockCount", $outOfStockCount['OutOfStockCount']);
        $this->ObjView->display('Index.tpl');
    }
    //End of function
    public function ajaxGraphAction() {
        $ObjFlot            = new Flot();
        $ObjBusiness        = new BusinessModel();
        $businessID         = $this->ObjSession->getSession("BUSINESS_USER_ID");
        $dateFrom           = GregorianToJD(date('m'), 01, date('Y'));
        $dateTo             = GregorianToJD(date('m'), date('d'), date('Y'));
        $gender             = json_decode($_POST['gender']);
        $age                = json_decode($_POST['age']);
        $_POST['dateRange'] = $_POST['dateRange'];
        if ($_POST['dateRange'] != 'Select Date') {
            if (strpos($_POST['dateRange'], " - ")) {
                list($fromDate, $toDate) = explode(" - ", $_POST['dateRange']);
            } //strpos($_POST['dateRange'], " - ")
            else {
                $fromDate = $toDate = $_POST['dateRange'];
            }
            $fromDate = strtotime($fromDate);
            $toDate   = strtotime($toDate);
            $dateFrom = GregorianToJD(date('m', $fromDate), date('d', $fromDate), date('Y', $fromDate));
            $dateTo   = GregorianToJD(date('m', $toDate), date('d', $toDate), date('Y', $toDate));
        } //$_POST['dateRange'] != 'Select Date'
        $arr          = array();
        $xCordArray   = array();
        $queryArr     = array();
        $arrayCounter = 0;
        for ($dateIndex = $dateFrom; $dateIndex <= $dateTo; $dateIndex++) {
            $arrayCounter = $arrayCounter + 1;
            list($month, $day, $year) = explode('/', JDToGregorian($dateIndex));
            $month = $month < 10 ? '0' . $month : $month;
            $day   = $day < 10 ? '0' . $day : $day;
            array_push($arr, $year . "-" . $month . "-" . $day);
            ($dateIndex == $dateFrom) ? $colName = 'orderDate' : $colName = '';
            array_push($queryArr, "SELECT '" . $year . "-" . $month . "-" . $day . "' $colName");
        }
        $dateRange[0]    = $arr[0];
        $dateRange[1]    = $arr[count($arr) - 1];
        $trafficSource   = $ObjBusiness->getDashBoardGraphDetails($businessID, $dateRange, $gender, $age, implode(' UNION ALL ', $queryArr));
        $currencyDetails = $this->ObjView->_currencies[$this->ObjView->_defaultCurrency];
        if ($currencyDetails['currencySymbolLeft'] != '') {
            $trafficReportSettings['currencyPosition'] = 'Left';
            $trafficReportSettings['currency']         = $currencyDetails['currencySymbolLeft'];
        } elseif ($currencyDetails['currencySymbolRight'] != '') {
            $trafficReportSettings['currencyPosition'] = 'Right';
            $trafficReportSettings['currency']         = $currencyDetails['currencySymbolRight'];
        }
        $trafficReportSettings['placeholder']             = 'businessGraphHolder';
        $trafficReportSettings['fill']                    = 'true';
        $trafficReportSettings['graphLabels']             = $this->getLanguageValue("lblRevenueGraph");
        $trafficReportSettings['graphTotalLabels']        = $this->getLanguageValue("lblRevenueGraph");
        $trafficReportSettings['graphTotalHolder']        = 'businessGraphHoldergraphTotalHolder';
        $trafficReportSettings['graphTotalHolderUlClass'] = 'graphTotalHolderUl';
        $trafficReportSettings['legendHolder']            = 'businessHolderLegend';
        $trafficReportSettings['legendColumns']           = 4;
        $trafficReportSettings['mode']                    = 'time';
        $trafficReportSettings['tootlTipXLabel']          = 'Day';
        $trafficReportSettings['graphType']               = 'line';
        $trafficReportSettings['enableSelection']         = 'false';
        $trafficReportSettings['graphColors']             = array(
            '#1999cf'
        );
        $trafficReportSettings['ticksForLineGraph']       = $xCordArray;
        $trafficReportSettings['includeScript']           = 'false';
        $trafficReportSettings['tooltipDecimalsY']        = 2;
        $line1                                            = array();
        $totRevenue                                       = 0;
        $totPurchase                                      = 0;
        foreach ($trafficSource as $key => $value) {
            array_push($line1, array(
                'graphX' => $value['orderDate'],
                'graphY' => $value['revenue']
            ));
            $totPurchase += $value['purchase'];
            $totRevenue += $value['revenue'];
        }
        //$trafficSource as $key => $value
        $trafficGraphArray[0] = $line1;
        $noOfDays             = ($dateTo - $dateFrom) == 0 ? 1 : ($dateTo - $dateFrom);
        $avg                  = $totRevenue / ($arrayCounter);
        $totRevenue           = $this->ObjView->getFormattedCurrency($totRevenue);
        $avg                  = $this->ObjView->getFormattedCurrency($avg);
        echo json_encode(array(
            $ObjFlot->init($trafficGraphArray, 0, $trafficReportSettings),
            $avg,
            $totPurchase,
            $totRevenue
        ));
    }
    //FUNCTION to lsit the STATES with AJAX
    public function ajaxStateAction() {
        $objState    = new StateModel();
        $countryID   = $_POST['countryID'];
        $languageIDs = $this->ObjView->languageIDs;
        $stateID     = $_POST['stateID'];
        if ($countryID > 0) {
            $statesList = $objState->listStates($languageIDs, $countryID);
        }
        $this->ObjView->assign('stateID', $stateID);
        $this->ObjView->assign('statesList', $statesList);
        $this->ObjView->display('CityState.tpl');
    }
    //END OF FUNCTION ajaxStateAction
    //FUNCTION TO GET URL KEY
    public function ajaxGetUrlKeyAction() {
        $businessName = trim($_POST['businessName']);
        $businessKey  = strtolower(preg_replace(array(
            '/\&/',
            '/\|/',
            '/\//'
        ), "-", $businessName));
        $businessKey  = strtolower(preg_replace("![^a-z0-9]+!i", "-", $businessKey));
        echo $businessKey;
        return $businessKey;
    }
    //END OF FUNCTION
    public function languageResetAction() {
        $ObjFilter    = new Filter();
        $ObjLanguages = new LanguageModel();
        $LanguageID   = $_REQUEST['ajax_request'][0];
        $type         = $this->getRequestValue("type");
        if ($type == 'content')
            $resSetContentLanguage = $ObjLanguages->setContentLanguageID($LanguageID);
        else {
            $ObjCookie = $ObjFilter->getCookieInstance();
            $ObjCookie->setCookie($ObjLanguages->getSection() . '_CurrentLanguageID', $LanguageID);
        }
    }
}