<?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: IndexController.php, v 1.0 2011/06/14 20:52:11
//
class IndexController extends Controller {
    public function indexAction() {
        $ObjOrder          = new OrderModel();
        $ObjProduct        = new ProductModel();
        $date_format       = $this->getSettingValue('site_settings', 'date_format');
        $languageIDs       = $this->ObjView->languageIDs;
        $orderCount        = 0;
        $monthCount        = 0;
        $orderTotalCount   = 0;
        $limitTo           = 7;

        //Order List Privilege
        $orderPrivilege = $this->ObjCommon->hasPrivilege('order/index/');
        if ($orderPrivilege) {
            $orderParams                              = array(
                'limitFrom' => 0,
                'limitTo' => $limitTo,
                'orderStatus' => 'Yes',
                'userID' => '',
                'orderType' => 'product',
                'languageIDs' => $languageIDs,
                'orderNumber' => '',
                'section' => 'adminDashboard'
            );
            
            $resListUserOrders                        = $ObjOrder->listUserOrders($orderParams);
			foreach($resListUserOrders as $key => $order) {
				if($order['billingAddress']!='') {
					$billingAddress = unserialize($order['billingAddress']);
					 $resListUserOrders[$key]['customer_phone'] = $billingAddress['billingPhone'];
				}
			}
            $orderCount                               = $ObjOrder->getTodaysOrder();
            $monthCount                               = $ObjOrder->getThisMonthsOrder();
            $orderTotalCount                          = $ObjOrder->getTotalOrder();
            $ordershowPrivilege                       = $this->ObjCommon->hasPrivilege('order/show/');
        }
        
        //Shipping & Product list Privilege
        $productPrivilege = $this->ObjCommon->hasPrivilege('product/index/');
        if ($productPrivilege) {
            $params       = array(
                'productPrivilege' => $productPrivilege
            );
            $resDashboard = $ObjProduct->getDashboardValues($params);
        }
		$autolineUpdate = $ObjProduct->autolineUpdate();
		
		$leasePrivilege                       = $this->ObjCommon->hasPrivilege('product/listleases/');
		$financePrivilege                     = $this->ObjCommon->hasPrivilege('product/listfinanceRate/');
		$params       = array(
			'leasePrivilege' 	=> $leasePrivilege,
			'financePrivilege' 	=> $financePrivilege
		);
		$dashboardMissing = $ObjProduct->getDashboardMissing($params);
		
        $this->ObjView->assign("resListUserOrders", isset($resListUserOrders) ? $resListUserOrders : array());
        $orderCount = ($orderCount < 1) ? "0" : $orderCount;
        $this->ObjView->assign("orderCount", $orderCount);
		$monthCount = ($monthCount < 1) ? "0" : $monthCount;
        $this->ObjView->assign("monthCount", $monthCount);
		$orderTotalCount = ($orderTotalCount < 1) ? "0" : $orderTotalCount;
        $this->ObjView->assign("orderTotalCount", $orderTotalCount);
        $this->ObjView->assign("orderPrivilege", $orderPrivilege);
        $this->ObjView->assign("ordershowPrivilege", isset($ordershowPrivilege) ? $ordershowPrivilege : '');
        $this->ObjView->assign("productPrivilege", $productPrivilege);
        $this->ObjView->assign("resDashboard", isset($resDashboard) ? $resDashboard : array());
        $this->ObjView->assign("autolineUpdate", $autolineUpdate);
        $this->ObjView->assign("dashboardMissing", $dashboardMissing);
		$this->ObjView->assign("leasePrivilege", isset($leasePrivilege) ? $leasePrivilege : '');
		$this->ObjView->assign("financePrivilege", isset($financePrivilege) ? $financePrivilege : '');
		
        $this->ObjView->display('Index.tpl');
    }
    /**
     * For dashboard graph
     */ //FUNCTION TO SHOW GRAPH
    public function ajaxGraphAction() {
        $ObjReport   = new ReportModel();
        $ObjFlot     = new Flot();
        $date_format = $this->getSettingValue('site_settings', 'date_format');
        $orderLabel  = $this->getLanguageValue("lblMenuSales");
        $date        = str_replace('+', '/', $this->getRequestValue('date'));
        $toDate      = '';
        if ($date) {
            $searchDates = explode(' - ', $date);
            $fromDate    = $searchDates[0];
            if (isset($searchDates[1])) {
                $toDate = $searchDates[1];
            }
        }
        if (!$toDate) {
            $toDate = $fromDate;
            $orderLabel .= $this->getLanguageValue("lblOn") . ' ' . $this->converToSystemDateFormat($fromDate, $date_format);
        } else {
            $orderLabel .= $this->getLanguageValue("lblBetween") . ' ' . $this->converToSystemDateFormat($fromDate, $date_format) . ' ' . $this->getLanguageValue("lblAnd") . ' ' . $this->converToSystemDateFormat($toDate, $date_format);
        }
        $fromDate                                 = date("Y-m-d", strtotime($fromDate));
        $toDate                                   = date("Y-m-d", strtotime($toDate));
        $sales                                    = $ObjReport->listOrdersForGraph($fromDate, $toDate);
        // default graph setings
        $trafficReportSettings['placeholder']     = 'placeholder';
        $trafficReportSettings['includeScript']   = 'false';
        $trafficReportSettings['fill']            = 'true';
        $trafficReportSettings['graphLabels']     = $this->getLanguageValue("lblNoofSales");
        $trafficReportSettings['mode']            = 'time';
        $trafficReportSettings['tootlTipXLabel']  = 'Day';
        $trafficReportSettings['graphType']       = 'line';
        $trafficReportSettings['enableSelection'] = 'false';
        $trafficReportSettings['graphColors']     = array(
            '#1999cf'
        );
        $trafficReportSettings['javascript_path'] = $this->ObjView->_javascript_path;
        $finalArray                               = array();
        $sales[0]['orderCreatedDate']             = isset($sales[0]['orderCreatedDate']) ? $sales[0]['orderCreatedDate'] : '';
        if ($sales[0]['orderCreatedDate'] != $fromDate) {
            $finalArray[0]['graphX'] = $fromDate;
            $finalArray[0]['graphY'] = 0;
            $flag                    = 0;
        }
        foreach ($sales as $key => $value) {
            array_push($finalArray, array(
                'graphX' => isset($value['orderCreatedDate']) ? $value['orderCreatedDate'] : '',
                'graphY' => isset($value['orderItemQuantity']) ? $value['orderItemQuantity'] : ''
            ));
        }
        $sales[count($sales) - 1]['orderCreatedDate'] = isset($sales[count($sales) - 1]['orderCreatedDate']) ? $sales[count($sales) - 1]['orderCreatedDate'] : '';
        if ($sales[count($sales) - 1]['orderCreatedDate'] != $toDate) {
            array_push($finalArray, array(
                'graphX' => $toDate,
                'graphY' => 0
            ));
        }
        $trafficGraphArray[0] = $finalArray;
        $daysCount            = $this->getDays($fromDate, $toDate);
        $avgSale              = $this->getAverage($sales, $daysCount);
        list($sales_amount, $sales_count) = $this->getSalesAmount($sales);
        $graph       = $ObjFlot->init($trafficGraphArray, '', $trafficReportSettings);
        $salesAmount = $this->ObjView->getFormattedCurrency($sales_amount);
        $result      = array(
            'graph' => $graph,
            'salesAmount' => $salesAmount,
            'avg' => $avgSale,
            'salesCount' => $sales_count,
            'orderLabel' => $orderLabel
        );
        echo json_encode($result);
    }
    //END OF FUNCTION
    //FUNCTION TO GET AVERAGE
    private function getAverage($valueList, $days_between) {
        $totalSales = 0;
        foreach ($valueList as $salesCount) {
            $salesCount['orderItemQuantity'] = isset($salesCount['orderItemQuantity']) ? $salesCount['orderItemQuantity'] : '';
            $totalSales                      = $totalSales + $salesCount['orderItemQuantity'];
        }
        if ($days_between > 0) {
            $avg_sale = $totalSales / ($days_between);
        } else {
            $avg_sale = $totalSales;
        }
        return round($avg_sale, 2);
    }
    //END OF FUNCTION
    //FUNCTION TO GET SALES AMOUNT
    private function getSalesAmount($reslistCity) {
        $sales_amount = 0;
        $order_count  = 0;
        foreach ($reslistCity as $amountTotal) {
            $amountTotal['orderTotalAmount']  = isset($amountTotal['orderTotalAmount']) ? $amountTotal['orderTotalAmount'] : '';
            $amountTotal['orderItemQuantity'] = isset($amountTotal['orderItemQuantity']) ? $amountTotal['orderItemQuantity'] : '';
            $sales_amount                     = $sales_amount + $amountTotal['orderTotalAmount'];
            $order_count                      = $order_count + $amountTotal['orderItemQuantity'];
        }
        return array(
            $sales_amount,
            $order_count
        );
    }
    public function getDays($fromDate, $toDate = '') {
        $daysCount      = 0;
        $startTimeStamp = strtotime($fromDate);
        if ($toDate) {
            $endTimeStamp = strtotime($toDate);
            $timeDiff     = abs($endTimeStamp - $startTimeStamp);
        } else {
            $timeDiff = abs($endTimeStamp);
        }
        $numberDays = $timeDiff / 86400; // 86400 seconds in one day
        // and you might want to convert to integer
        return intval($numberDays) + 1;
    }
    //END OF FUNCTION
    public function converToSystemDateFormat($date, $preferedDateFormat) {
        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';
        }
        return date($returnDateFormat, strtotime($date));
    }
}