<?php

class DashboardController extends Controller
{
    public function accessRules()
    {
        return array(
            array(
                'allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('login', 'error', 'logout'),
                'users' => array('*'),
            ),
            array(
                'allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array(
                    'Index',
                    'Create',
                    'GetLeadGraphs',
                    'GetQuoteGraphs',
                    'GetOrderGraphs',
                    'GettestGraphs',
                    'GetGraph',
                    'LeadGraphDetails',
                    'GetLeadOwnerDetail',
                    'LeadGraphOwnerDetails',
                    'LeadGetMonthDetails',
                    'GetLeadCountryDetail',
                    'LeadGraphCountryDetails',
                    'LeadGetLeadCountryMonthDetails',
                    'GetLeadSalesGroupDetail',
                    'LeadGraphSalesGroupDetails',
                    'LeadSalesMonthDetails',
                    'quotes_graphdetails',
                    'GetQuoteOwnerDetail',
                    'GetQuoteCountryDetail',
                    'GetQuotesSalesGroupDetail',
                    'QuotesGraphOwnerDetails',
                    'QuotesGraphCountryDetails',
                    'QuoteGraphSalesGroupDetails',
                    'QuoteGetMonthDetails',
                    'GetQuoteMonthDetails',
                    'QuoteSalesMonthDetails',
                    'Quotation_items',
                    'order_graphdetails',
                    'OrderGraphOwnerDetails',
                    'GetOrderOwnerDetail',
                    'GetOrderCountryDetail',
                    'GetOrderSalesGroupDetail',
                    'OrderGraphOwnerDetails',
                    'OrderCountryDetails',
                    'OrderSalesGroupDetails',
                    'OrderGetMonthDetails',
                    'GetOrderMonthDetails',
                    'OrderSalesMonthDetails',
                    'Order_items',
                    'invoice_graphdetails',
                    'GetInvoiceOwnerDetail',
                    'GetInvoiceCountryDetail',
                    'GetInvoiceSalesGroupDetail',
                    'invoiceGraphOwnerDetails',
                    'invoiceCountryDetails',
                    'InvoiceSalesGroupDetails',
                    'InvoiceGetMonthDetails',
                    'GetInvoiceMonthDetails',
                    'InvoiceSalesMonthDetails',
                    'getInvoiceItems',
                    'GetInvoiceDetail',
                    'GetMonthlyInvoice',
                    'loadInvoicesMtdGraph',
                    'InvoiceYear',
                    'GetOrderDetail',
                    'OrderYear',
                    'loadOrderMtdGraph',
                    'Current_stock_details',
                    'GetMonthlyBrandWiseDetails',
                    'GetBrandWiseDetail',
                    'BrandGraphOwnerDetails',
                    'QuotesYear',
                    'LeadYear',
                    'followups',
                    'AIDashboard'
                ),
                'expression' => '$user->isMember()',
            ),
            array(
                'deny', // deny all users
                'users' => array('*'),
            ),
        );
    }
    public function actionIndex()
        {
            
            if (isset(Yii::app()->user->havePermissionOn['dashboard_view']) || Yii::app()->user->authorised_user == 1) {
               
                $this->render('index');
            } else {
                // Unauthorized: render custom unauthorized page without layout
                $this->layout = false;
                $this->render('//front/site/unauthorised'); // Do not include .php
                Yii::app()->end(); // Stop execution
            }
        }


    // Uncomment the following methods and override them if needed

    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }
    public function actionGetLeadGraphs()
    {
        //print_r("HI");die();
        $this->renderPartial('lead_graphs');
    }
    public function actionGetQuoteGraphs()
    {
        $this->render('quotation_graphs');
    }
    public function actionGetOrderGraphs()
    {
        $this->render('order_graphs');
    }
    public function actionGettestGraphs()
    {
        $this->render('test_graphs');
    }

    public function actionGetGraph()
    {

        $page = Yii::app()->request->getparam("page");
        $fromdate = Yii::app()->request->getparam("fromdate");
        $todate = Yii::app()->request->getparam("todate");
        $this->render($page, array('fromdate' => $fromdate, 'todate' => $todate));
    }

    public function actionLeadGraphDetails()
    {
        $type = (int) Yii::app()->request->getParam('type');
        $fromdate = Yii::app()->request->getParam('from_date');
        $todate = Yii::app()->request->getParam('end_date');
        $currentYear = date("Y");
        $fromdate = str_replace('/', '-', $fromdate);
        $from_date = date("Y-m-d", strtotime($fromdate));
        $todate = str_replace('/', '-', $todate);
        $end_date = date("Y-m-d", strtotime($todate));
        $month = date("m", strtotime($fromdate));
        $month_1 = date("m", strtotime($todate));
        $year = date("Y", strtotime($todate));
        Yii::app()->clientScript->scriptMap = array('*jquery.js' => false, '*jquery.min.js' => false, 'jquery.min.js' => false, '*jquery-ui.js' => false, '*jquery-ui.min.js' => false, '*jquery-2.1.4.min.js' => false, 'jquery-2.1.4.min.js' => false);
        if ($type == 1) {
            $graph_lead_owner = Yii::app()->db->createCommand('SELECT CONCAT(user.first_name," ",user.last_name) AS x_value,COUNT(*) AS y_value FROM {{lead}} AS L 
                                                         INNER JOIN ' . User::MainDb . '.{{user}} AS user ON L.lead_owner_id=user.id 
                                                         WHERE L.enq_date BETWEEN "' . $from_date . '" AND "' . $end_date . '" GROUP BY user.id')->queryAll();
            if (!empty($graph_lead_owner)) {
                $plot = '[';
                foreach ($graph_lead_owner as $m => $eachdata) {
                    $color = substr(md5(rand()), 0, 6);
                    $plot .= '{label:"' . $eachdata['x_value'] . '", value:"' . $eachdata['y_value'] . '", color: "#' . $color . '"},';
                }
                $plot .= ']';
            } else {
                $plot = '';
            }
            $this->render('lead_owner_view', array('plot' => $plot, 'from_date' => $from_date, 'end_date' => $end_date));
        } else if ($type == 2) {
            $graph_lead_country = Yii::app()->db->createCommand('SELECT COUNT(*) AS y_value,country.country_name AS x_value FROM {{lead}} AS L 
                                                        INNER JOIN {{customer}} AS customer ON L.customer_id=customer.id 
                                                        INNER JOIN {{mas_country}} AS country ON customer.customer_country=country.id 
                                                        WHERE L.enq_date BETWEEN "' . $from_date . '" AND "' . $end_date . '" GROUP BY customer.customer_country')->queryAll();
            if (!empty($graph_lead_country)) {

                $plot = '[';
                foreach ($graph_lead_country as $m => $eachdata) {
                    $color = substr(md5(rand()), 0, 6);
                    $plot .= '{label:"' . $eachdata['x_value'] . '", value:"' . $eachdata['y_value'] . '", color: "#' . $color . '"},';
                }
                $plot .= ']';
            } else {
                $plot = '';
            }
            $this->render('lead_country_view', array('plot' => $plot, 'from_date' => $from_date, 'end_date' => $end_date));
        } else if ($type == 3) {
            $graph_lead_sales_group = Yii::app()->db->createCommand('SELECT sales_group.group_name AS x_value,COUNT(*) AS y_value FROM {{lead}} AS L 
                                                        INNER JOIN {{mas_sales_group}} AS sales_group ON L.sales_group_id=sales_group.id
                                                        WHERE L.enq_date BETWEEN "' . $from_date . '" AND "' . $end_date . '" GROUP BY sales_group.id')->queryAll();
            if (!empty($graph_lead_sales_group)) {
                $plot = '[';
                foreach ($graph_lead_sales_group as $m => $eachdata) {
                    $color = substr(md5(rand()), 0, 6);
                    $plot .= '{label:"' . $eachdata['x_value'] . '", value:"' . $eachdata['y_value'] . '", color: "#' . $color . '"},';
                }
                $plot .= ']';
            } else {
                $plot = '';
            }
            $this->render('lead_sales_group_view', array('plot' => $plot, 'from_date' => $from_date, 'end_date' => $end_date));
        } else if ($type == 4) {
            $year = date("Y", strtotime($todate));
            $currentYear = date("Y");
            $currentmonth = date("m");
            if ($year == $currentYear) {
                $month_1 = $currentmonth;
            }
            $data = array();
            $plot_4 = '[';
            for ($k = $month; $k <= $month_1; $k++) {
                $dateObj = DateTime::createFromFormat('!m', $k);
                $monthName = $dateObj->format('F'); // March
                $graphdata3 = Yii::app()->db->createCommand('SELECT COUNT(id) AS value FROM {{lead}}  WHERE YEAR(enq_date) = "' . $year . '" AND MONTH(enq_date) = "' . $k . '"')->queryAll();

                foreach ($graphdata3 as $i => $eachdata) {
                    $color = substr(md5(rand()), 0, 6);
                    $plot_4 .= '{label:"' . $monthName . '", value:"' . $eachdata['value'] . '", color: "#' . $color . '" },';
                    $data[$k]['month'] = $monthName;
                    $data[$k]['month_id'] = $k;
                    $data[$k]['year'] = $year;
                    $data[$k]['value'] = $eachdata['value'];
                }

            }
            $plot_4 .= ']';
            $this->render('lead_year_view', array('plot' => $plot_4, 'data' => $data));
        }
    }

    /***********************   start - lead Owner *****************************************************/

    public function actionGetLeadOwnerDetail()
    {
        $lead_graph_details = array();
        //Quotation Owner
//            $fin_month = Yii::app()->user->fin_year; 
//            $year = date('Y');
//            $year_next = $year + 1;
//            if($fin_month == 1){
//                $from_date = $year.'-01-01';
//                $end_date = $year.'-12-31';
//            }else{
//                $from_date = $year.'-04-01';
//                $end_date = $year_next.'-03-31';
//            }
        $from_date = Yii::app()->request->getParam('fromdate');
        $end_date = Yii::app()->request->getParam('todate');
        $graph_data_quantity = Yii::app()->db->createCommand('SELECT L.lead_owner_id AS OWNERID,CONCAT(user.first_name," ",user.last_name) AS x_value,COUNT(*) AS y_value FROM {{lead}} AS L INNER JOIN ' . User::MainDb . '.{{user}} AS user ON L.lead_owner_id=user.id  WHERE L.enq_date BETWEEN "' . $from_date . '" AND "' . $end_date . '" GROUP BY user.id')->queryAll();
        $plot = '[';
        foreach ($graph_data_quantity as $m => $eachdata) {
            $color = substr(md5(rand()), 0, 6);
            $plot .= '{label:"' . $eachdata['x_value'] . '", value:"' . $eachdata['y_value'] . '", color: "#' . $color . '"},';
            $lead_graph_details[$m]['slno'] = $m + 1;
            $lead_graph_details[$m]['lead_owner'] = $eachdata['x_value'];
            $lead_graph_details[$m]['lead_count'] = $eachdata['y_value'];
            $lead_graph_details[$m]['lead_color'] = "#" . $color;
            $lead_graph_details[$m]['lead_owner_id'] = $eachdata['OWNERID'];
        }
        $plot .= ']';

        foreach ($lead_graph_details as $key => $value) {
            $rowData[] = array($value['slno'], $value['lead_owner'], $value['lead_count'], $value['lead_color'], $value['lead_owner_id']);
        }
        $data['data'] = $rowData;
        $data['plot'] = $plot;
        echo json_encode($data);
    }

    public function actionLeadGraphOwnerDetails()
    {

        $owner_id = $_POST['user_id'];
        //            $currentYear  = date("Y");
        $from_date = Yii::app()->request->getParam('fromdate');
        $end_date = Yii::app()->request->getParam('todate');
        $from_date = strtotime($from_date);
        $end_date = strtotime($end_date);
        $month = date("m", $from_date);
        $month_1 = date("m", $end_date);
        $year = date("Y", $end_date);
        $graph_detail = Yii::app()->db->createCommand('SELECT YEAR(L.enq_date) as y, MONTH(L.enq_date) as m, COUNT(L.id) as TOTAL_COUNT,SUM(L.value) AS TOTAL_AMT FROM {{lead}} AS L                                         
                                        WHERE YEAR(L.enq_date) = "' . $year . '" AND MONTH(L.enq_date) BETWEEN "' . $month . '" AND "' . $month_1 . '" AND L.lead_owner_id="' . $owner_id . '" GROUP BY y, m ORDER BY y DESC, m ASC')->queryAll();

        $this->render('lead_owner_details', array('graph_detail' => $graph_detail, 'owner_id' => $owner_id));
    }

    public function actionLeadGetMonthDetails()
    {

        $owner_id = $_POST['ownerid'];
        $month = $_POST['month'];
        $year = $_POST['year'];
        $currentYear = date("Y");

        $graph_detail = Yii::app()->db->createCommand('SELECT L.customer_id,L.value,L.enq_date,L.closing_date FROM {{lead}} AS L                                                     
                                                WHERE YEAR(L.enq_date) = "' . $year . '" AND MONTH(L.enq_date) = "' . $month . '" AND L.lead_owner_id="' . $owner_id . '"')->queryAll();


        $this->render('lead_owner_month_details', array('graph_detail' => $graph_detail, 'month' => $month, 'year' => $year));
    }
    /***********************   End - lead Owner ************************************************************/
    /***********************   start - lead Country *****************************************************/

    public function actionGetLeadCountryDetail()
    {
        $lead_graph_details = array();
        $from_date = Yii::app()->request->getParam('fromdate');
        $end_date = Yii::app()->request->getParam('todate');
        $graph_data_quantity = Yii::app()->db->createCommand('SELECT country.id AS COUNTRY_ID,COUNT(*) AS y_value,country.country_name AS x_value FROM {{lead}} AS L 
                                                        INNER JOIN {{customer}} AS customer ON L.customer_id=customer.id 
                                                        INNER JOIN {{mas_country}} AS country ON customer.customer_country=country.id 
                                                        WHERE L.enq_date BETWEEN "' . $from_date . '" AND "' . $end_date . '" GROUP BY customer.customer_country')->queryAll();

        $plot = '[';
        foreach ($graph_data_quantity as $m => $eachdata) {
            $color = substr(md5(rand()), 0, 6);
            $plot .= '{label:"' . $eachdata['x_value'] . '", value:"' . $eachdata['y_value'] . '", color: "#' . $color . '"},';
            $lead_graph_details[$m]['slno'] = $m + 1;
            $lead_graph_details[$m]['lead_country'] = $eachdata['x_value'];
            $lead_graph_details[$m]['lead_count'] = $eachdata['y_value'];
            $lead_graph_details[$m]['lead_color'] = "#" . $color;
            $lead_graph_details[$m]['lead_country_id'] = $eachdata['COUNTRY_ID'];
        }
        $plot .= ']';

        foreach ($lead_graph_details as $key => $value) {
            $rowData[] = array($value['slno'], $value['lead_country'], $value['lead_count'], $value['lead_color'], $value['lead_country_id']);
        }
        $data['data'] = $rowData;
        $data['plot'] = $plot;
        echo json_encode($data);
    }

    public function actionLeadGraphCountryDetails()
    {

        $country_id = $_POST['country_id'];
        //            $currentYear  = date("Y");
        $from_date = Yii::app()->request->getParam('fromdate');
        $end_date = Yii::app()->request->getParam('todate');
        $from_date = strtotime($from_date);
        $end_date = strtotime($end_date);
        $month = date("m", $from_date);
        $month_1 = date("m", $end_date);
        $year = date("Y", $end_date);
        $graph_detail = Yii::app()->db->createCommand('SELECT YEAR(L.enq_date) as y, MONTH(L.enq_date) as m, COUNT(L.id) as TOTAL_COUNT,SUM(L.value) AS TOTAL_AMT  FROM {{lead}} AS L 
                                                        INNER JOIN {{customer}} AS customer ON L.customer_id=customer.id 
                                                        INNER JOIN {{mas_country}} AS country ON customer.customer_country=country.id 
                                                        WHERE YEAR(L.enq_date) = "' . $year . '" AND MONTH(L.enq_date) BETWEEN "' . $month . '" AND "' . $month_1 . '" AND country.id="' . $country_id . '" GROUP BY y, m ORDER BY y DESC, m ASC')->queryAll();

        $this->render('lead_country_details', array('graph_detail' => $graph_detail, 'country_id' => $country_id, 'action' => 'view_country_detail'));
    }

    public function actionLeadGetLeadCountryMonthDetails()
    {

        $country_id = $_POST['country_id'];
        $month = $_POST['month'];
        $year = $_POST['year'];
        $currentYear = date("Y");

        $graph_detail = Yii::app()->db->createCommand('SELECT L.customer_id,L.value,L.enq_date,L.closing_date FROM {{lead}} AS L 
                                                        INNER JOIN {{customer}} AS customer ON L.customer_id=customer.id  
                                                        INNER JOIN {{mas_country}} AS country ON customer.customer_country=country.id 
                                                        WHERE YEAR(L.enq_date) = "' . $year . '" AND MONTH(L.enq_date) = "' . $month . '" AND country.id="' . $country_id . '"')->queryAll();


        $this->render('lead_country_details', array('graph_detail' => $graph_detail, 'action' => 'view_country_month_detail', 'month' => $month, 'year' => $year));
    }

    /***********************   End - lead Country ************************************************************/
    /***********************   start - lead sales group  *****************************************************/

    public function actionGetLeadSalesGroupDetail()
    {
        $lead_graph_details = array();
        //            $fin_month = Yii::app()->user->fin_year; 
//            $year = date('Y');
//            $year_next = $year + 1;
//            if($fin_month == 1){
//                $from_date = $year.'-01-01';
//                $end_date = $year.'-12-31';
//            }else{
//                $from_date = $year.'-04-01';
//                $end_date = $year_next.'-03-31';
//            }
        $from_date = Yii::app()->request->getParam('fromdate');
        $end_date = Yii::app()->request->getParam('todate');
        $graph_data_quantity = Yii::app()->db->createCommand('SELECT sales_group.id AS SALES_GROUP_ID,sales_group.group_name AS x_value,COUNT(L.id) AS y_value FROM {{lead}} AS L 
                                                        INNER JOIN {{mas_sales_group}} AS sales_group ON L.sales_group_id=sales_group.id 
                                                        WHERE L.enq_date BETWEEN "' . $from_date . '" AND "' . $end_date . '" GROUP BY sales_group.id')->queryAll();

        $plot = '[';
        foreach ($graph_data_quantity as $m => $eachdata) {
            $color = substr(md5(rand()), 0, 6);
            $plot .= '{label:"' . $eachdata['x_value'] . '", value:"' . $eachdata['y_value'] . '", color: "#' . $color . '"},';
            $lead_graph_details[$m]['slno'] = $m + 1;
            $lead_graph_details[$m]['sales_group'] = $eachdata['x_value'];
            $lead_graph_details[$m]['lead_count'] = $eachdata['y_value'];
            $lead_graph_details[$m]['lead_color'] = "#" . $color;
            $lead_graph_details[$m]['sales_group_id'] = $eachdata['SALES_GROUP_ID'];
        }
        $plot .= ']';

        foreach ($lead_graph_details as $key => $value) {
            $rowData[] = array($value['slno'], $value['sales_group'], $value['lead_count'], $value['lead_color'], $value['sales_group_id']);
        }
        $data['data'] = $rowData;
        $data['plot'] = $plot;
        echo json_encode($data);
    }

    public function actionLeadGraphSalesGroupDetails()
    {

        $group_id = $_POST['group_id'];
        $from_date = Yii::app()->request->getParam('fromdate');
        $end_date = Yii::app()->request->getParam('todate');
        $from_date = strtotime($from_date);
        $end_date = strtotime($end_date);
        $month = date("m", $from_date);
        $month_1 = date("m", $end_date);
        $year = date("Y", $end_date);


        $graph_detail = Yii::app()->db->createCommand('SELECT YEAR(L.enq_date) as y, MONTH(L.enq_date) as m, COUNT(L.id) as TOTAL_COUNT,SUM(L.value) AS TOTAL_AMT FROM {{lead}} AS L 
                                                        INNER JOIN {{mas_sales_group}} AS sales_group ON L.sales_group_id=sales_group.id 
                                                        WHERE YEAR(L.enq_date) = "' . $year . '" AND MONTH(L.enq_date) BETWEEN "' . $month . '" AND "' . $month_1 . '" AND sales_group.id="' . $group_id . '" GROUP BY y, m ORDER BY y DESC, m ASC')->queryAll();

        $this->render('lead_sales_group_details', array('graph_detail' => $graph_detail, 'group_id' => $group_id, 'action' => 'view_sales_group_detail'));
    }
    public function actionLeadSalesMonthDetails()
    {

        $group_id = $_POST['group_id'];
        $month = $_POST['month'];
        $year = $_POST['year'];
        $currentYear = date("Y");


        $graph_detail = Yii::app()->db->createCommand('SELECT L.customer_id,L.value,L.enq_date,L.closing_date FROM {{lead}} AS L 
                                                        INNER JOIN {{mas_sales_group}} AS sales_group ON L.sales_group_id=sales_group.id
                                                        WHERE YEAR(L.enq_date) = "' . $year . '" AND MONTH(L.enq_date) = "' . $month . '" AND sales_group.id="' . $group_id . '"')->queryAll();

        $this->render('lead_sales_group_details', array('graph_detail' => $graph_detail, 'action' => 'view_sales_group_month_detail', 'month' => $month, 'year' => $year));
    }

    /***********************   End - lead sales group *****************************************************/

    /***********************   Start  - Quaotation Part *****************************************************/


    //quotes_graphdetails  

    public function actionQuotes_graphdetails()
    {
        $type = (int) Yii::app()->request->getParam('type');
        //        $currentYear  = date("Y");
        $fromdate = Yii::app()->request->getParam('from_date');
        $todate = Yii::app()->request->getParam('end_date');
        $currentYear = date("Y");
        $fromdate = str_replace('/', '-', $fromdate);
        $from_date = date("Y-m-d", strtotime($fromdate));
        $todate = str_replace('/', '-', $todate);
        $end_date = date("Y-m-d", strtotime($todate));
        $month = date("m", strtotime($fromdate));
        $month_1 = date("m", strtotime($todate));
        $year = date("Y", strtotime($todate));
        Yii::app()->clientScript->scriptMap = array('*jquery.js' => false, '*jquery.min.js' => false, 'jquery.min.js' => false, '*jquery-ui.js' => false, '*jquery-ui.min.js' => false, '*jquery-2.1.4.min.js' => false, 'jquery-2.1.4.min.js' => false);
        if ($type == 1) {
            $graph_data_quantity = Yii::app()->db->createCommand('SELECT CONCAT(user.first_name," ",user.last_name) AS x_value,SUM(quotes.grand_total) AS y_value FROM {{quotes}} AS quotes INNER JOIN ' . User::MainDb . '.{{user}} AS user ON quotes.lead_owner_id=user.id WHERE quotes.qtn_start_date BETWEEN "' . $from_date . '" AND "' . $end_date . '"  GROUP BY user.id')->queryAll();
            $plot = '[';
            foreach ($graph_data_quantity as $m => $eachdata) {
                $color = substr(md5(rand()), 0, 6);
                $plot .= '{label:"' . $eachdata['x_value'] . '", value:"' . $eachdata['y_value'] . '", color: "#' . $color . '"},';
            }
            $plot .= ']';
            $this->render('quotes_owner_view', array('plot' => $plot, 'from_date' => $from_date, 'end_date' => $end_date));
        } else if ($type == 2) {


            $graphdata = Yii::app()->db->createCommand('SELECT SUM(quotes.grand_total) AS y_value,country.country_name AS x_value FROM {{quotes}} AS quotes 
                                                        INNER JOIN {{customer}} AS customer ON quotes.customer_id=customer.id 
                                                        INNER JOIN {{mas_country}} AS country ON customer.customer_country=country.id 
                                                        WHERE quotes.qtn_start_date BETWEEN "' . $from_date . '" AND "' . $end_date . '" GROUP BY customer.customer_country')->queryAll();

            $plot = '[';
            foreach ($graphdata as $m => $eachdata) {
                $color = substr(md5(rand()), 0, 6);
                $plot .= '{label:"' . $eachdata['x_value'] . '", value:"' . $eachdata['y_value'] . '", color: "#' . $color . '"},';
            }
            $plot .= ']';

            $this->render('quotes_country_view', array('plot' => $plot, 'from_date' => $from_date, 'end_date' => $end_date));
        } else if ($type == 3) {


            $graphdata = Yii::app()->db->createCommand('SELECT sales_group.group_name AS x_value,SUM(quotes.grand_total) AS y_value FROM {{quotes}} AS quotes
                                                        INNER JOIN {{mas_sales_group}} AS sales_group ON quotes.sales_group_id=sales_group.id  
                                                        WHERE quotes.qtn_start_date BETWEEN "' . $from_date . '" AND "' . $end_date . '" GROUP BY sales_group.id')->queryAll();


            $plot = '[';
            foreach ($graphdata as $m => $eachdata) {
                $color = substr(md5(rand()), 0, 6);
                $plot .= '{label:"' . $eachdata['x_value'] . '", value:"' . $eachdata['y_value'] . '", color: "#' . $color . '"},';
            }
            $plot .= ']';

            $this->render('quotes_sales_group_view', array('plot' => $plot, 'from_date' => $from_date, 'end_date' => $end_date));
        } else if ($type == 4) {

            $currentYear = date("Y");
            $currentmonth = date("m");
            if ($year == $currentYear) {
                $month_1 = $currentmonth;
            }
            $data = array();
            $plot_4 = '[';
            for ($k = $month; $k <= $month_1; $k++) {
                $dateObj = DateTime::createFromFormat('!m', $k);
                $monthName = $dateObj->format('F'); // March
                $graphdata3 = Yii::app()->db->createCommand('SELECT SUM(grand_total*exchange_rate) AS value FROM {{quotes}}  WHERE YEAR(qtn_start_date) = "' . $year . '" AND MONTH(qtn_start_date) = "' . $k . '"')->queryAll();

                foreach ($graphdata3 as $eachdata) {
                    $color = substr(md5(rand()), 0, 6);
                    $plot_4 .= '{label:"' . $monthName . '", value:"' . $eachdata['value'] . '", color: "#' . $color . '" },';
                    $data[$k]['month'] = $monthName;
                    $data[$k]['month_id'] = $k;
                    $data[$k]['year'] = $year;
                    $data[$k]['value'] = $eachdata['value'];
                }

            }
            $plot_4 .= ']';

            $this->render('quotes_year_view', array('plot' => $plot_4, 'data' => $data));
        }
    }

    /***********************   start - Quote Owner *****************************************************/

    public function actionGetQuoteOwnerDetail()
    {
        $lead_graph_details = array();
        //            $fin_month = Yii::app()->user->fin_year; 
//            $year = date('Y');
//            $year_next = $year + 1;
//            if($fin_month == 1){
//                $from_date = $year.'-01-01';
//                $end_date = $year.'-12-31';
//            }else{
//                $from_date = $year.'-04-01';
//                $end_date = $year_next.'-03-31';
//            }
        $from_date = Yii::app()->request->getParam('fromdate');
        $end_date = Yii::app()->request->getParam('todate');
        $graph_data_quantity = Yii::app()->db->createCommand('SELECT quotes.lead_owner_id AS OWNERID,CONCAT(user.first_name," ",user.last_name) AS x_value,COUNT(*) AS y_value,SUM(quotes.grand_total*quotes.exchange_rate) AS amount FROM {{quotes}} AS quotes INNER JOIN ' . User::MainDb . '.{{user}} AS user ON quotes.lead_owner_id =user.id WHERE quotes.qtn_start_date BETWEEN "' . $from_date . '" AND "' . $end_date . '" GROUP BY user.id')->queryAll();
        $plot = '[';
        foreach ($graph_data_quantity as $m => $eachdata) {
            $color = substr(md5(rand()), 0, 6);
            $plot .= '{label:"' . $eachdata['x_value'] . '", value:"' . $eachdata['y_value'] . '", color: "#' . $color . '"},';
            $lead_graph_details[$m]['slno'] = $m + 1;
            $lead_graph_details[$m]['quote_owner'] = $eachdata['x_value'];
            $lead_graph_details[$m]['quote_count'] = $eachdata['y_value'];
            $lead_graph_details[$m]['quote_amount'] = $eachdata['amount'];
            $lead_graph_details[$m]['quote_color'] = "#" . $color;
            $lead_graph_details[$m]['quote_owner_id'] = $eachdata['OWNERID'];
        }
        $plot .= ']';

        foreach ($lead_graph_details as $key => $value) {
            $rowData[] = array($value['slno'], $value['quote_owner'], $value['quote_count'], Yii::app()->numberFormatter->formatCurrency($value['quote_amount'], ""), $value['quote_color'], $value['quote_owner_id']);
        }
        $data['data'] = $rowData;
        $data['plot'] = $plot;
        echo json_encode($data);
    }

    public function actionQuotesGraphOwnerDetails()
    {

        $owner_id = $_POST['user_id'];
        //            $currentYear  = date("Y");
        $from_date = Yii::app()->request->getParam('fromdate');
        $end_date = Yii::app()->request->getParam('todate');
        $from_date = strtotime($from_date);
        $end_date = strtotime($end_date);
        $month = date("m", $from_date);
        $month_1 = date("m", $end_date);
        $year = date("Y", $end_date);
        $graph_detail = Yii::app()->db->createCommand('SELECT YEAR(quotes.qtn_start_date) as y, MONTH(quotes.qtn_start_date) as m, COUNT(quotes.id) as TOTAL_COUNT,SUM(quotes.grand_total) AS TOTAL_AMT FROM {{quotes}} AS quotes                                         
                                        WHERE YEAR(quotes.qtn_start_date) = "' . $year . '" AND MONTH(quotes.qtn_start_date) BETWEEN "' . $month . '" AND "' . $month_1 . '" AND quotes.lead_owner_id="' . $owner_id . '" GROUP BY y, m ORDER BY y DESC, m ASC')->queryAll();

        $this->render('quotes_owner_details', array('graph_detail' => $graph_detail, 'owner_id' => $owner_id, 'action' => 'view_quotes_detail'));
    }

    public function actionQuoteGetMonthDetails()
    {

        $owner_id = $_POST['ownerid'];
        $month = $_POST['month'];
        $year = $_POST['year'];
        $currentYear = date("Y");

        $graph_detail = Yii::app()->db->createCommand('SELECT quotes.id AS quotes_id,quotes.customer_id,quotes.grand_total,quotes.qtn_start_date,quotes.qtn_validity FROM {{quotes}} AS quotes                                                     
                                                WHERE YEAR(quotes.qtn_start_date) = "' . $year . '" AND MONTH(quotes.qtn_start_date) = "' . $month . '" AND quotes.lead_owner_id="' . $owner_id . '"')->queryAll();


        $this->render('quotes_owner_details', array('graph_detail' => $graph_detail, 'month' => $month, 'year' => $year, 'action' => 'view_country_month_detail'));
    }

    public function actionQuotation_items()
    {

        $quotesid = $_POST['quotesid'];
        $this->render('view_quotesItems', array('quotesid' => $quotesid));
    }

    /***********************   End - Quote Owner ************************************************************/
    /***********************   start - Quote Country *****************************************************/

    public function actionGetQuoteCountryDetail()
    {
        $lead_graph_details = array();
        $from_date = Yii::app()->request->getParam('fromdate');
        $end_date = Yii::app()->request->getParam('todate');

        $graph_data_quantity = Yii::app()->db->createCommand('SELECT country.id AS COUNTRY_ID,COUNT(*) AS y_value,country.country_name AS x_value,SUM(quotes.grand_total*quotes.exchange_rate) AS amount  FROM {{quotes}} AS quotes 
                                                        INNER JOIN {{customer}} AS customer ON quotes.customer_id=customer.id
                                                        INNER JOIN {{mas_country}} AS country ON customer.customer_country=country.id 
                                                        WHERE quotes.qtn_start_date BETWEEN "' . $from_date . '" AND "' . $end_date . '" GROUP BY customer.customer_country')->queryAll();

        $plot = '[';
        foreach ($graph_data_quantity as $m => $eachdata) {
            $color = substr(md5(rand()), 0, 6);
            $plot .= '{label:"' . $eachdata['x_value'] . '", value:"' . $eachdata['y_value'] . '", color: "#' . $color . '"},';
            $lead_graph_details[$m]['slno'] = $m + 1;
            $lead_graph_details[$m]['quotes_country'] = $eachdata['x_value'];
            $lead_graph_details[$m]['quotes_count'] = $eachdata['y_value'];
            $lead_graph_details[$m]['amount'] = $eachdata['amount'];
            $lead_graph_details[$m]['quotes_color'] = "#" . $color;
            $lead_graph_details[$m]['quotes_country_id'] = $eachdata['COUNTRY_ID'];
        }
        $plot .= ']';

        foreach ($lead_graph_details as $key => $value) {
            $rowData[] = array($value['slno'], $value['quotes_country'], $value['quotes_count'], Yii::app()->numberFormatter->formatCurrency($value['amount'], ""), $value['quotes_color'], $value['quotes_country_id']);
        }
        $data['data'] = $rowData;
        $data['plot'] = $plot;
        echo json_encode($data);
    }

    public function actionQuotesGraphCountryDetails()
    {

        $country_id = $_POST['country_id'];
        //            $currentYear  = date("Y");
        $from_date = Yii::app()->request->getParam('fromdate');
        $end_date = Yii::app()->request->getParam('todate');
        $from_date = strtotime($from_date);
        $end_date = strtotime($end_date);
        $month = date("m", $from_date);
        $month_1 = date("m", $end_date);
        $year = date("Y", $end_date);
        $graph_detail = Yii::app()->db->createCommand('SELECT YEAR(quotes.qtn_start_date) as y, MONTH(quotes.qtn_start_date) as m, COUNT(quotes.id) as TOTAL_COUNT,SUM(quotes.grand_total) AS TOTAL_AMT  FROM {{quotes}} AS quotes 
                                                        INNER JOIN {{customer}} AS customer ON quotes.customer_id=customer.id
                                                        INNER JOIN {{mas_country}} AS country ON customer.customer_country=country.id 
                                                        WHERE YEAR(quotes.qtn_start_date) = "' . $year . '" AND MONTH(quotes.qtn_start_date) BETWEEN "' . $month . '" AND "' . $month_1 . '"  AND country.id="' . $country_id . '" GROUP BY y, m ORDER BY y DESC, m ASC')->queryAll();

        $this->render('quotes_country_details', array('graph_detail' => $graph_detail, 'country_id' => $country_id, 'action' => 'view_country_detail'));
    }

    public function actionGetQuoteMonthDetails()
    {

        $country_id = $_POST['country_id'];
        $month = $_POST['month'];
        $year = $_POST['year'];
        $currentYear = date("Y");

        $graph_detail = Yii::app()->db->createCommand('SELECT quotes.id AS quotes_id,quotes.customer_id,quotes.grand_total,quotes.qtn_start_date,quotes.qtn_validity FROM {{quotes}} AS quotes  
                                                        INNER JOIN {{customer}} AS customer ON quotes.customer_id=customer.id
                                                        INNER JOIN {{mas_country}} AS country ON customer.customer_country=country.id 
                                                        WHERE YEAR(quotes.qtn_start_date) = "' . $year . '" AND MONTH(quotes.qtn_start_date) = "' . $month . '" AND country.id="' . $country_id . '"')->queryAll();


        $this->render('quotes_country_details', array('graph_detail' => $graph_detail, 'action' => 'view_country_month_detail', 'month' => $month, 'year' => $year));
    }

    /***********************   End - Quote Country ************************************************************/
    /***********************   start - Quote sales group *****************************************************/


    public function actionGetQuotesSalesGroupDetail()
    {

        $lead_graph_details = array();
        $from_date = Yii::app()->request->getParam('fromdate');
        $end_date = Yii::app()->request->getParam('todate');

        $graph_data_quantity = Yii::app()->db->createCommand('SELECT sales_group.id AS SALES_GROUP_ID,sales_group.group_name AS x_value,COUNT(*) AS y_value,SUM(quotes.grand_total*quotes.exchange_rate) AS amount FROM {{quotes}} AS quotes  
                                                        INNER JOIN {{mas_sales_group}} AS sales_group ON quotes.sales_group_id=sales_group.id 
                                                        WHERE quotes.qtn_start_date BETWEEN "' . $from_date . '" AND "' . $end_date . '"  GROUP BY sales_group.id')->queryAll();

        $plot = '[';
        foreach ($graph_data_quantity as $m => $eachdata) {
            $color = substr(md5(rand()), 0, 6);
            $plot .= '{label:"' . $eachdata['x_value'] . '", value:"' . $eachdata['y_value'] . '", color: "#' . $color . '"},';
            $lead_graph_details[$m]['slno'] = $m + 1;
            $lead_graph_details[$m]['sales_group'] = $eachdata['x_value'];
            $lead_graph_details[$m]['quotes_count'] = $eachdata['y_value'];
            $lead_graph_details[$m]['amount'] = $eachdata['amount'];
            $lead_graph_details[$m]['quotes_color'] = "#" . $color;
            $lead_graph_details[$m]['sales_group_id'] = $eachdata['SALES_GROUP_ID'];
        }
        $plot .= ']';

        foreach ($lead_graph_details as $key => $value) {
            $rowData[] = array($value['slno'], $value['sales_group'], $value['quotes_count'], Yii::app()->numberFormatter->formatCurrency($value['amount'], ""), $value['quotes_color'], $value['sales_group_id']);
        }
        $data['data'] = $rowData;
        $data['plot'] = $plot;
        echo json_encode($data);
    }

    public function actionQuoteGraphSalesGroupDetails()
    {

        $group_id = $_POST['group_id'];
        //$currentYear  = date("Y");
        $from_date = Yii::app()->request->getParam('fromdate');
        $end_date = Yii::app()->request->getParam('todate');


        $graph_detail = Yii::app()->db->createCommand('SELECT YEAR(quotes.qtn_start_date) as y, MONTH(quotes.qtn_start_date) as m, COUNT(quotes.id) as TOTAL_COUNT,SUM(quotes.grand_total) AS TOTAL_AMT FROM {{quotes}} AS quotes
                                                        INNER JOIN {{mas_sales_group}} AS sales_group ON quotes.sales_group_id=sales_group.id  
                                                        WHERE YEAR(quotes.qtn_start_date) = "' . $from_date . '" AND "' . $end_date . '"AND sales_group.id="' . $group_id . '" GROUP BY y, m ORDER BY y DESC, m ASC')->queryAll();

        $this->render('quotes_sales_group_details', array('graph_detail' => $graph_detail, 'group_id' => $group_id, 'action' => 'view_sales_group_detail'));
    }
    public function actionQuoteSalesMonthDetails()
    {

        $group_id = $_POST['group_id'];
        $month = $_POST['month'];
        $year = $_POST['year'];
        $currentYear = date("Y");


        $graph_detail = Yii::app()->db->createCommand('SELECT quotes.id AS quotes_id,quotes.customer_id,quotes.grand_total,quotes.qtn_start_date,quotes.qtn_validity FROM {{quotes}} AS quotes
                                                        INNER JOIN {{mas_sales_group}} AS sales_group ON quotes.sales_group_id=sales_group.id
                                                        WHERE YEAR(quotes.qtn_start_date) = "' . $year . '" AND MONTH(quotes.qtn_start_date) = "' . $month . '" AND sales_group.id="' . $group_id . '"')->queryAll();

        $this->render('quotes_sales_group_details', array('graph_detail' => $graph_detail, 'action' => 'view_sales_group_month_detail', 'month' => $month, 'year' => $year));
    }


    /***********************   End - Quote sales group *****************************************************/


    /***********************   Start  - Order Part *****************************************************/




    public function actionorder_graphdetails()
    {
        $type = (int) Yii::app()->request->getParam('type');
        $currentYear = date("Y");
        $fromdate = Yii::app()->request->getParam('from_date');
        $todate = Yii::app()->request->getParam('end_date');
        $fromdate = str_replace('/', '-', $fromdate);
        $from_date = date("Y-m-d", strtotime($fromdate));
        $todate = str_replace('/', '-', $todate);
        $end_date = date("Y-m-d", strtotime($todate));
        $month = date("m", strtotime($fromdate));
        $month_1 = date("m", strtotime($todate));
        $year = date("Y", strtotime($todate));
        Yii::app()->clientScript->scriptMap = array('*jquery.js' => false, '*jquery.min.js' => false, 'jquery.min.js' => false, '*jquery-ui.js' => false, '*jquery-ui.min.js' => false, '*jquery-2.1.4.min.js' => false, 'jquery-2.1.4.min.js' => false);
        if ($type == 1) {
            $graph_data_quantity = Yii::app()->db->createCommand('SELECT CONCAT(user.first_name," ",user.last_name) AS x_value,sum(grand_total) AS y_value FROM {{order}} AS ord INNER JOIN ' . User::MainDb . '.{{user}} AS user ON ord.lead_owner_id=user.id  WHERE ord.order_date BETWEEN "' . $from_date . '" AND "' . $end_date . '" GROUP BY user.id')->queryAll();
            $plot = '[';
            foreach ($graph_data_quantity as $m => $eachdata) {
                $color = substr(md5(rand()), 0, 6);
                $plot .= '{label:"' . $eachdata['x_value'] . '", value:"' . $eachdata['y_value'] . '", color: "#' . $color . '"},';
            }
            $plot .= ']';
            $this->render('order_owner_view', array('plot' => $plot, 'from_date' => $from_date, 'end_date' => $end_date));
        } else if ($type == 2) {
            $graphdata = Yii::app()->db->createCommand('SELECT sum(grand_total) AS y_value,country.country_name AS x_value FROM {{order}} AS ord 
                                                        INNER JOIN {{customer}} AS customer ON ord.customer_id=customer.id 
                                                        INNER JOIN {{mas_country}} AS country ON customer.customer_country=country.id 
                                                        WHERE ord.order_date BETWEEN "' . $from_date . '" AND "' . $end_date . '" GROUP BY customer.customer_country')->queryAll();

            $plot = '[';
            foreach ($graphdata as $m => $eachdata) {
                $color = substr(md5(rand()), 0, 6);
                $plot .= '{label:"' . $eachdata['x_value'] . '", value:"' . $eachdata['y_value'] . '", color: "#' . $color . '"},';
            }
            $plot .= ']';

            $this->render('order_country_view', array('plot' => $plot, 'from_date' => $from_date, 'end_date' => $end_date));
        } else if ($type == 3) {
            $graphdata = Yii::app()->db->createCommand('SELECT sales_group.group_name AS x_value,sum(grand_total) AS y_value FROM {{order}} AS ord
                                                        INNER JOIN {{mas_sales_group}} AS sales_group ON ord.sales_group_id=sales_group.id                                                         
                                                        WHERE ord.order_date BETWEEN "' . $from_date . '" AND "' . $end_date . '" GROUP BY sales_group.id')->queryAll();


            $plot = '[';
            foreach ($graphdata as $m => $eachdata) {
                $color = substr(md5(rand()), 0, 6);
                $plot .= '{label:"' . $eachdata['x_value'] . '", value:"' . $eachdata['y_value'] . '", color: "#' . $color . '"},';
            }
            $plot .= ']';

            $this->render('order_sales_group_view', array('plot' => $plot, 'from_date' => $from_date, 'end_date' => $end_date));
        } else if ($type == 4) {
            $currentYear = date("Y");
            $currentmonth = date("m");
            if ($year == $currentYear) {
                $month_1 = $currentmonth;
            }
            $plot = '[';
            for ($k = $month; $k <= $month_1; $k++) {
                $dateObj = DateTime::createFromFormat('!m', $k);
                $monthName = $dateObj->format('F');
                $graphdata3 = Yii::app()->db->createCommand('SELECT sum(grand_total) AS value FROM {{order}}  WHERE YEAR(order_date) = "' . $year . '" AND MONTH(order_date) = "' . $k . '"')->queryAll();
                foreach ($graphdata3 as $eachdata) {
                    $color = substr(md5(rand()), 0, 6);
                    $plot .= '{label:"' . $monthName . '", value:"' . $eachdata['value'] . '", color: "#' . $color . '" },';
                }

            }
            $plot .= ']';

            $this->render('order_year_view', array('plot' => $plot, 'from_date' => $from_date, 'end_date' => $end_date));
        }
    }

    /***********************   start - Order Owner *****************************************************/

    public function actionGetOrderOwnerDetail()
    {
        $lead_graph_details = array();
        $from_date = Yii::app()->request->getParam('fromdate');
        $end_date = Yii::app()->request->getParam('todate');
        $graph_data_quantity = Yii::app()->db->createCommand('SELECT ord.lead_owner_id AS OWNERID,CONCAT(user.first_name," ",user.last_name) AS x_value,COUNT(*) AS y_value,SUM(ord.grand_total*ord.exchange_rate) AS amount FROM {{order}} AS ord INNER JOIN ' . User::MainDb . '.{{user}} AS user ON ord.lead_owner_id=user.id  WHERE ord.order_date BETWEEN "' . $from_date . '" AND "' . $end_date . '" GROUP BY user.id')->queryAll();
        $plot = '[';
        foreach ($graph_data_quantity as $m => $eachdata) {
            $color = substr(md5(rand()), 0, 6);
            $plot .= '{label:"' . $eachdata['x_value'] . '", value:"' . $eachdata['y_value'] . '", color: "#' . $color . '"},';
            $lead_graph_details[$m]['slno'] = $m + 1;
            $lead_graph_details[$m]['order_owner'] = $eachdata['x_value'];
            $lead_graph_details[$m]['order_count'] = $eachdata['y_value'];
            $lead_graph_details[$m]['amount'] = $eachdata['amount'];
            $lead_graph_details[$m]['order_color'] = "#" . $color;
            $lead_graph_details[$m]['order_owner_id'] = $eachdata['OWNERID'];
        }
        $plot .= ']';

        foreach ($lead_graph_details as $key => $value) {
            $rowData[] = array($value['slno'], $value['order_owner'], $value['order_count'], Yii::app()->numberFormatter->formatCurrency($value['amount'], ""), $value['order_color'], $value['order_owner_id']);
        }
        $data['data'] = $rowData;
        $data['plot'] = $plot;
        echo json_encode($data);
    }

    public function actionOrderGraphOwnerDetails()
    {

        $owner_id = $_POST['user_id'];
        $from_date = Yii::app()->request->getParam('fromdate');
        $end_date = Yii::app()->request->getParam('todate');
        $graph_detail = Yii::app()->db->createCommand('SELECT YEAR(ord.order_date) as y, MONTH(ord.order_date) as m, COUNT(ord.id) as TOTAL_COUNT,SUM(ord.grand_total) AS TOTAL_AMT FROM {{order}} AS ord
                                        WHERE ord.order_date BETWEEN "' . $from_date . '" AND "' . $end_date . '" AND ord.lead_owner_id="' . $owner_id . '" GROUP BY y, m ORDER BY y DESC, m ASC')->queryAll();

        $this->render('order_owner_details', array('graph_detail' => $graph_detail, 'owner_id' => $owner_id, 'action' => 'view_quotes_detail'));
    }

    public function actionOrderGetMonthDetails()
    {

        $owner_id = $_POST['ownerid'];
        $month = $_POST['month'];
        $year = $_POST['year'];
        $currentYear = date("Y");

        $graph_detail = Yii::app()->db->createCommand('SELECT ord.id AS order_id,ord.customer_id,ord.grand_total,ord.order_date,ord.delivery_date FROM {{order}} AS ord                                                     
                                                WHERE YEAR(ord.order_date) = "' . $year . '" AND MONTH(ord.order_date) = "' . $month . '" AND ord.lead_owner_id="' . $owner_id . '"')->queryAll();


        $this->render('order_owner_details', array('graph_detail' => $graph_detail, 'month' => $month, 'year' => $year, 'action' => 'view_country_month_detail'));
    }

    /* public function actionQuotation_items(){
        
            $quotesid  = $_POST['quotesid'];
            $this->render('view_quotesItems', array('quotesid' => $quotesid));
     }

/***********************   End - order Owner ************************************************************/
    /***********************   start - order Country *****************************************************/


    public function actionGetOrderCountryDetail()
    {
        $lead_graph_details = array();
        $from_date = Yii::app()->request->getParam('fromdate');
        $end_date = Yii::app()->request->getParam('todate');
        $graph_data_quantity = Yii::app()->db->createCommand('SELECT country.id AS COUNTRY_ID,COUNT(*) AS y_value,country.country_name AS x_value,SUM(ord.grand_total*ord.exchange_rate) AS amount FROM {{order}} AS ord
                                                        INNER JOIN {{customer}} AS customer ON ord.customer_id=customer.id 
                                                        INNER JOIN {{mas_country}} AS country ON customer.customer_country=country.id 
                                                        WHERE ord.order_date BETWEEN "' . $from_date . '" AND "' . $end_date . '" GROUP BY customer.customer_country')->queryAll();

        $plot = '[';
        foreach ($graph_data_quantity as $m => $eachdata) {
            $color = substr(md5(rand()), 0, 6);
            $plot .= '{label:"' . $eachdata['x_value'] . '", value:"' . $eachdata['y_value'] . '", color: "#' . $color . '"},';
            $lead_graph_details[$m]['slno'] = $m + 1;
            $lead_graph_details[$m]['order_country'] = $eachdata['x_value'];
            $lead_graph_details[$m]['order_count'] = $eachdata['y_value'];
            $lead_graph_details[$m]['amount'] = $eachdata['amount'];
            $lead_graph_details[$m]['order_color'] = "#" . $color;
            $lead_graph_details[$m]['order_country_id'] = $eachdata['COUNTRY_ID'];
        }
        $plot .= ']';

        foreach ($lead_graph_details as $key => $value) {
            $rowData[] = array($value['slno'], $value['order_country'], $value['order_count'], Yii::app()->numberFormatter->formatCurrency($value['amount'], ''), $value['order_color'], $value['order_country_id']);
        }
        $data['data'] = $rowData;
        $data['plot'] = $plot;
        echo json_encode($data);
    }

    public function actionOrderCountryDetails()
    {

        $country_id = $_POST['country_id'];
        $from_date = Yii::app()->request->getParam('fromdate');
        $end_date = Yii::app()->request->getParam('todate');

        $graph_detail = Yii::app()->db->createCommand('SELECT YEAR(ord.order_date) as y, MONTH(ord.order_date) as m, COUNT(ord.id) as TOTAL_COUNT,SUM(ord.grand_total) AS TOTAL_AMT  FROM {{order}} AS ord 
                                                        INNER JOIN {{customer}} AS customer ON ord.customer_id=customer.id
                                                        INNER JOIN {{mas_country}} AS country ON customer.customer_country=country.id 
                                                        WHERE ord.order_date BETWEEN "' . $from_date . '" AND "' . $end_date . '" AND country.id="' . $country_id . '" GROUP BY y, m ORDER BY y DESC, m ASC')->queryAll();

        $this->render('order_country_details', array('graph_detail' => $graph_detail, 'country_id' => $country_id, 'action' => 'view_country_detail'));
    }

    public function actionGetOrderMonthDetails()
    {

        $country_id = $_POST['country_id'];
        $month = $_POST['month'];
        $year = $_POST['year'];
        $currentYear = date("Y");

        $graph_detail = Yii::app()->db->createCommand('SELECT ord.id AS order_id,ord.customer_id,ord.grand_total,ord.order_date,ord.delivery_date FROM {{order}} AS ord   
                                                        INNER JOIN {{customer}} AS customer ON ord.customer_id=customer.id 
                                                        INNER JOIN {{mas_country}} AS country ON customer.customer_country=country.id 
                                                        WHERE YEAR(ord.order_date) = "' . $year . '" AND MONTH(ord.order_date) = "' . $month . '" AND country.id="' . $country_id . '"')->queryAll();


        $this->render('order_country_details', array('graph_detail' => $graph_detail, 'action' => 'view_country_month_detail', 'month' => $month, 'year' => $year));
    }

    /***********************   start - order sales group *****************************************************/


    public function actionGetOrderSalesGroupDetail()
    {

        $lead_graph_details = array();
        $from_date = Yii::app()->request->getParam('fromdate');
        $end_date = Yii::app()->request->getParam('todate');
        $graph_data_quantity = Yii::app()->db->createCommand('SELECT sales_group.id AS SALES_GROUP_ID,sales_group.group_name AS x_value,SUM(ord.grand_total*ord.exchange_rate) AS amount,COUNT(ord.id) as y_value FROM {{order}} AS ord  
                                                        INNER JOIN {{mas_sales_group}} AS sales_group ON ord.sales_group_id=sales_group.id                                                         
                                                        WHERE ord.order_date BETWEEN "' . $from_date . '" AND "' . $end_date . '"  GROUP BY sales_group.id')->queryAll();

        $plot = '[';
        foreach ($graph_data_quantity as $m => $eachdata) {
            $color = substr(md5(rand()), 0, 6);
            $plot .= '{label:"' . $eachdata['x_value'] . '", value:"' . $eachdata['y_value'] . '", color: "#' . $color . '"},';
            $lead_graph_details[$m]['slno'] = $m + 1;
            $lead_graph_details[$m]['sales_group'] = $eachdata['x_value'];
            $lead_graph_details[$m]['order_count'] = $eachdata['y_value'];
            $lead_graph_details[$m]['amount'] = $eachdata['amount'];
            $lead_graph_details[$m]['order_color'] = "#" . $color;
            $lead_graph_details[$m]['sales_group_id'] = $eachdata['SALES_GROUP_ID'];
        }
        $plot .= ']';

        foreach ($lead_graph_details as $key => $value) {
            $rowData[] = array($value['slno'], $value['sales_group'], $value['order_count'], Yii::app()->numberFormatter->formatCurrency($value['amount'], ""), $value['order_color'], $value['sales_group_id']);
        }
        $data['data'] = $rowData;
        $data['plot'] = $plot;
        echo json_encode($data);
    }

    public function actionOrderSalesGroupDetails()
    {

        $group_id = $_POST['group_id'];
        $from_date = Yii::app()->request->getParam('fromdate');
        $end_date = Yii::app()->request->getParam('todate');
        $graph_detail = Yii::app()->db->createCommand('SELECT YEAR(ord.order_date) as y, MONTH(ord.order_date) as m, COUNT(ord.id) as TOTAL_COUNT,SUM(ord.grand_total) AS TOTAL_AMT FROM {{order}} AS ord
                                                        INNER JOIN {{mas_sales_group}} AS sales_group ON ord.sales_group_id=sales_group.id 
                                                        WHERE ord.order_date BETWEEN "' . $from_date . '" AND "' . $end_date . '" AND sales_group.id="' . $group_id . '" GROUP BY y, m ORDER BY y DESC, m ASC')->queryAll();

        $this->render('order_sales_group_details', array('graph_detail' => $graph_detail, 'group_id' => $group_id, 'action' => 'view_sales_group_detail'));
    }
    public function actionOrderSalesMonthDetails()
    {

        $group_id = $_POST['group_id'];
        $month = $_POST['month'];
        $year = $_POST['year'];
        $currentYear = date("Y");


        $graph_detail = Yii::app()->db->createCommand('SELECT ord.id AS order_id,ord.customer_id,ord.grand_total,ord.order_date,ord.delivery_date FROM {{order}} AS ord
                                                        INNER JOIN {{mas_sales_group}} AS sales_group ON ord.sales_group_id=sales_group.id 
                                                        WHERE YEAR(ord.order_date) = "' . $year . '" AND MONTH(ord.order_date) = "' . $month . '" AND sales_group.id="' . $group_id . '"')->queryAll();

        $this->render('order_sales_group_details', array('graph_detail' => $graph_detail, 'action' => 'view_sales_group_month_detail', 'month' => $month, 'year' => $year));
    }


    /***********************   End - order sales group *****************************************************/
    /***********************   start - order Items *****************************************************/
    public function actionOrder_items()
    {

        $orderid = $_POST['orderid'];
        $this->render('view_OrderItems', array('orderid' => $orderid));
    }
    /***********************   End - order Items *****************************************************/


    /***********************   Start  - Invoice Part *****************************************************/




    public function actioninvoice_graphdetails()
    {
        $type = (int) Yii::app()->request->getParam('type');
        $fromdate = Yii::app()->request->getParam('from_date');
        $todate = Yii::app()->request->getParam('end_date');
        $currentYear = date("Y");
        $fromdate = str_replace('/', '-', $fromdate);
        $from_date = date("Y-m-d", strtotime($fromdate));
        $todate = str_replace('/', '-', $todate);
        $end_date = date("Y-m-d", strtotime($todate));
        $month = date("m", strtotime($fromdate));
        $month_1 = date("m", strtotime($todate));
        $year = date("Y", strtotime($todate));
        Yii::app()->clientScript->scriptMap = array('*jquery.js' => false, '*jquery.min.js' => false, 'jquery.min.js' => false, '*jquery-ui.js' => false, '*jquery-ui.min.js' => false, '*jquery-2.1.4.min.js' => false, 'jquery-2.1.4.min.js' => false);
        if ($type == 1) {
            //$graph_data_quantity = Yii::app()->db->createCommand('SELECT CONCAT(user.first_name," ",user.last_name) AS x_value,COUNT(*) AS y_value FROM {{quotes}} AS quotes INNER JOIN blueskye_erp_boul_evard_main.{{user}} AS user ON quotes.{{user}}_id=user.id INNER JOIN {{master_file}} AS master_file ON quotes.file_id = master_file.id WHERE master_file.current_process_status = "Q"  GROUP BY user.id')->queryAll();

            $graph_data_quantity = Yii::app()->db->createCommand('SELECT CONCAT(user.first_name," ",user.last_name) AS x_value,sum(grand_total) AS y_value FROM {{invoice}} AS inv 
                                                           INNER JOIN {{master_file}} AS filedetail ON inv.file_id=filedetail.id 
                                                        INNER JOIN ' . User::MainDb . '.{{user}} AS user ON filedetail.lead_owner_id=user.id 
                                                        WHERE inv.invoice_date BETWEEN "' . $from_date . '" AND "' . $end_date . '" GROUP BY user.id')->queryAll();

            $plot = '[';
            foreach ($graph_data_quantity as $m => $eachdata) {
                $color = substr(md5(rand()), 0, 6);
                $plot .= '{label:"' . $eachdata['x_value'] . '", value:"' . $eachdata['y_value'] . '", color: "#' . $color . '"},';
            }
            $plot .= ']';
            $this->render('invoice_owner_view', array('plot' => $plot, 'fromdate' => $from_date, 'todate' => $end_date));
        } else if ($type == 2) {


            $graphdata = Yii::app()->db->createCommand('SELECT sum(grand_total) AS y_value,country.country_name AS x_value FROM {{invoice}} AS inv 
                                                        INNER JOIN {{customer}} AS customer ON inv.customer_id=customer.id
                                                        INNER JOIN {{mas_country}} AS country ON customer.customer_country=country.id 
                                                        WHERE YEAR(inv.invoice_date) = "' . $currentYear . '"  GROUP BY customer.customer_country')->queryAll();

            $plot = '[';
            foreach ($graphdata as $m => $eachdata) {
                $color = substr(md5(rand()), 0, 6);
                $plot .= '{label:"' . $eachdata['x_value'] . '", value:"' . $eachdata['y_value'] . '", color: "#' . $color . '"},';
            }
            $plot .= ']';

            $this->render('invoice_country_view', array('plot' => $plot, 'fromdate' => $from_date, 'todate' => $end_date));
        } else if ($type == 3) {


            $graphdata = Yii::app()->db->createCommand('SELECT sales_group.group_name AS x_value,SUM(inv.grand_total) AS y_value FROM {{invoice}} AS inv
                                                        INNER JOIN {{mas_sales_group}} AS sales_group ON inv.sales_group_id=sales_group.id 
                                                        WHERE YEAR(inv.invoice_date) = "' . $currentYear . '"  GROUP BY sales_group.id')->queryAll();


            $plot = '[';
            foreach ($graphdata as $m => $eachdata) {
                $color = substr(md5(rand()), 0, 6);
                $plot .= '{label:"' . $eachdata['x_value'] . '", value:"' . $eachdata['y_value'] . '", color: "#' . $color . '"},';
            }
            $plot .= ']';

            $this->render('invoice_sales_group_view', array('plot' => $plot, 'fromdate' => $from_date, 'todate' => $end_date));
        } else if ($type == 4) {
            $currentmonth = date("m");
            if ($year == $currentYear) {
                $month_1 = $currentmonth;
            }
            $plot = '[';
            for ($k = $month; $k <= $month_1; $k++) {
                $dateObj = DateTime::createFromFormat('!m', $k);
                $monthName = $dateObj->format('F');
                $graphdata3 = Yii::app()->db->createCommand('SELECT sum(grand_total) AS value FROM {{invoice}}  WHERE YEAR(invoice_date) = "' . $year . '" AND MONTH(invoice_date) = "' . $k . '"')->queryAll();

                foreach ($graphdata3 as $eachdata) {
                    $color = substr(md5(rand()), 0, 6);
                    $plot .= '{label:"' . $monthName . '", value:"' . $eachdata['value'] . '", color: "#' . $color . '" },';
                }

            }
            $plot .= ']';
            $this->render('invoice_current_year', array('plot' => $plot, 'fromdate' => $from_date, 'todate' => $end_date));
        } else if ($type == 5) {
            $currentmonth = (int) Yii::app()->request->getParam('month');

            $graphdata = Yii::app()->db->createCommand('SELECT invoice_no AS x_value,grand_total AS y_value FROM {{invoice}}
                                                        WHERE YEAR(invoice_date) = "' . $currentYear . '" AND MONTH(invoice_date) = "' . $currentmonth . '"')->queryAll();


            $plot = '[';
            foreach ($graphdata as $m => $eachdata) {
                $color = substr(md5(rand()), 0, 6);
                $plot .= '{label:"' . $eachdata['x_value'] . '", value:"' . $eachdata['y_value'] . '", color: "#' . $color . '"},';
            }
            $plot .= ']';

            $this->render('invoice_monthly', array('plot' => $plot, 'currentmonth' => $currentmonth));
        }
    }


    /***********************   start - Invoice Owner *****************************************************/

    public function actionGetInvoiceOwnerDetail()
    {
        $lead_graph_details = array();
        $from_date = Yii::app()->request->getParam('fromdate');
        $end_date = Yii::app()->request->getParam('todate');
        $graph_data_quantity = Yii::app()->db->createCommand('SELECT filedetail.lead_owner_id AS OWNERID,CONCAT(user.first_name," ",user.last_name) AS x_value,COUNT(*) AS y_value,sum(inv.grand_total) as amount FROM {{invoice}} AS inv 
                                                                INNER JOIN {{master_file}} AS filedetail ON inv.file_id=filedetail.id 
                                                                INNER JOIN ' . User::MainDb . '.{{user}} AS user ON filedetail.lead_owner_id=user.id  WHERE inv.invoice_date BETWEEN "' . $from_date . '" AND "' . $end_date . '" GROUP BY user.id')->queryAll();

        //$graph_data_quantity = Yii::app()->db->createCommand('SELECT CONCAT(user.first_name," ",user.last_name) AS x_value,COUNT(*) AS y_value FROM {{order}} AS ord INNER JOIN blueskye_erp_boul_evard_main.{{user}} AS user ON ord.{{user}}_id=user.id INNER JOIN {{master_file}} AS master_file ON ord.file_id = master_file.id WHERE master_file.current_process_status = "O"  GROUP BY user.id')->queryAll();
        $plot = '[';
        foreach ($graph_data_quantity as $m => $eachdata) {




            $color = substr(md5(rand()), 0, 6);
            $plot .= '{label:"' . $eachdata['x_value'] . '", value:"' . $eachdata['y_value'] . '", color: "#' . $color . '"},';
            $lead_graph_details[$m]['slno'] = $m + 1;
            $lead_graph_details[$m]['order_owner'] = $eachdata['x_value'];
            $lead_graph_details[$m]['order_count'] = $eachdata['y_value'];
            $lead_graph_details[$m]['amount'] = $eachdata['amount'];
            $lead_graph_details[$m]['order_color'] = "#" . $color;
            $lead_graph_details[$m]['order_owner_id'] = $eachdata['OWNERID'];
        }
        $plot .= ']';

        foreach ($lead_graph_details as $key => $value) {
            $SQL_cost_rate = "SELECT SUM(cost_rate * quantity) AS cost_rate,SUM(rate * quantity) AS selling_rice,SUM(tax_vat_amount) AS tax_vat_amount  FROM `erp_invoice_item` AS item 
                INNER JOIN erp_invoice INV ON item.invoice_id=INV.id  
                INNER JOIN erp_master_file AS file ON file_id=file.id 
                WHERE invoice_date BETWEEN '" . $from_date . "' AND '" . $end_date . "' AND file.lead_owner_id=" . $value['order_owner_id'];
            //echo $SQL_cost_rate;
            $arr_invoice_item_details = Yii::app()->db->createCommand($SQL_cost_rate)->queryRow();
            $profit = $arr_invoice_item_details['selling_price'] - $arr_invoice_item_details['cost_rate'];
            if (!empty($profit)) {
                $profit_percentage = ($profit * 100) / $arr_invoice_item_details['cost_rate'];
            }
            $rowData[] = array($value['slno'], $value['order_owner'], $value['order_count'], Yii::app()->numberFormatter->formatCurrency($value['amount'], ""), Yii::app()->numberFormatter->formatCurrency($arr_invoice_item_details['cost_rate'], ""), Yii::app()->numberFormatter->formatCurrency($profit, ""), Yii::app()->numberFormatter->formatCurrency($profit_percentage, ""), $value['order_color'], $value['order_owner_id']);
        }
        $data['data'] = $rowData;
        $data['plot'] = $plot;
        echo json_encode($data);
    }

    public function actioninvoiceGraphOwnerDetails()
    {

        $owner_id = $_POST['user_id'];
        $fromdate = Yii::app()->request->getParam('fromdate');
        $todate = Yii::app()->request->getParam('todate');
        $fromdate = str_replace('/', '-', $fromdate);
        $from_date = date("Y-m-d", strtotime($fromdate));
        $todate = str_replace('/', '-', $todate);
        $end_date = date("Y-m-d", strtotime($todate));

        $currentYear = date("Y");

        $graph_detail = Yii::app()->db->createCommand('SELECT YEAR(inv.invoice_date) as y, MONTH(inv.invoice_date) as m, COUNT(inv.id) as TOTAL_COUNT,SUM(inv.grand_total) AS TOTAL_AMT FROM {{invoice}} AS inv
                                        INNER JOIN {{master_file}} AS master_file ON inv.file_id = master_file.id
                                        WHERE inv.invoice_date BETWEEN "' . $from_date . '" AND "' . $end_date . '" AND master_file.lead_owner_id="' . $owner_id . '" GROUP BY y, m ORDER BY y DESC, m ASC')->queryAll();
        //echo $from_date;
        $this->render('invoice_owner_details', array('graph_detail' => $graph_detail, 'from_date' => $from_date, 'end_date' => $end_date, 'owner_id' => $owner_id, 'action' => 'view_quotes_detail'));
    }

    public function actionInvoiceGetMonthDetails()
    {

        $owner_id = $_POST['ownerid'];
        $month = $_POST['month'];
        $year = $_POST['year'];
        $currentYear = date("Y");

        $graph_detail = Yii::app()->db->createCommand('SELECT inv.id AS invoice_id,inv.customer_id,inv.grand_total,inv.invoice_date FROM {{invoice}} AS inv
                                                    INNER JOIN {{master_file}} AS master_file ON inv.file_id = master_file.id 
                                                WHERE YEAR(inv.invoice_date) = "' . $year . '" AND MONTH(inv.invoice_date) = "' . $month . '" AND master_file.lead_owner_id="' . $owner_id . '"')->queryAll();


        $this->render('invoice_owner_details', array('graph_detail' => $graph_detail, 'month' => $month, 'year' => $year, 'action' => 'view_country_month_detail'));
    }

    /***********************   End - Invoice Owner ************************************************************/

    /***********************   start - Invoice Country *****************************************************/


    public function actionGetInvoiceCountryDetail()
    {
        $lead_graph_details = array();
        $from_date = Yii::app()->request->getParam('fromdate');
        $end_date = Yii::app()->request->getParam('todate');
        $graph_data_quantity = Yii::app()->db->createCommand('SELECT country.id AS COUNTRY_ID,COUNT(*) AS y_value,country.country_name AS x_value,sum(inv.grand_total) as amount FROM {{invoice}} AS inv
                                                        INNER JOIN {{customer}} AS customer ON inv.customer_id=customer.id 
                                                        INNER JOIN {{mas_country}} AS country ON customer.customer_country=country.id 
                                                        WHERE inv.invoice_date BETWEEN "' . $from_date . '" AND "' . $end_date . '" GROUP BY customer.customer_country')->queryAll();

        $plot = '[';
        foreach ($graph_data_quantity as $m => $eachdata) {
            $color = substr(md5(rand()), 0, 6);
            $plot .= '{label:"' . $eachdata['x_value'] . '", value:"' . $eachdata['y_value'] . '", color: "#' . $color . '"},';
            $lead_graph_details[$m]['slno'] = $m + 1;
            $lead_graph_details[$m]['order_country'] = $eachdata['x_value'];
            $lead_graph_details[$m]['order_count'] = $eachdata['y_value'];
            $lead_graph_details[$m]['order_count'] = $eachdata['y_value'];
            $lead_graph_details[$m]['amount'] = $eachdata['amount'];
            $lead_graph_details[$m]['order_color'] = "#" . $color;
            $lead_graph_details[$m]['order_country_id'] = $eachdata['COUNTRY_ID'];
        }
        $plot .= ']';


        foreach ($lead_graph_details as $key => $value) {
            $SQL_cost_rate = "SELECT SUM(cost_rate * quantity) AS cost_rate,SUM(rate * quantity) AS selling_rice,SUM(tax_vat_amount) AS tax_vat_amount  FROM `erp_invoice_item` AS item 
                INNER JOIN erp_invoice INV ON item.invoice_id=INV.id  
                INNER JOIN {{customer}} AS customer ON INV.customer_id=customer.id 
                INNER JOIN {{mas_country}} AS country ON customer.customer_country=country.id 
                WHERE INV.invoice_date BETWEEN '" . $from_date . "' AND '" . $end_date . "' AND customer.customer_country=" . $value['order_country_id'];
            //echo $SQL_cost_rate;
            $arr_invoice_item_details = Yii::app()->db->createCommand($SQL_cost_rate)->queryRow();
            $profit = $arr_invoice_item_details['selling_rice'] - $arr_invoice_item_details['cost_rate'];
            $profit_percentage = ($profit * 100) / $arr_invoice_item_details['cost_rate'];
            $rowData[] = array($value['slno'], $value['order_country'], $value['order_count'], Yii::app()->numberFormatter->formatCurrency($arr_invoice_item_details['selling_rice'], ""), Yii::app()->numberFormatter->formatCurrency($arr_invoice_item_details['cost_rate'], ""), Yii::app()->numberFormatter->formatCurrency($profit, ""), Yii::app()->numberFormatter->formatCurrency($profit_percentage, ""), $value['order_color'], $value['order_country_id']);
        }
        $data['data'] = $rowData;
        $data['plot'] = $plot;
        echo json_encode($data);
    }

    public function actioninvoiceCountryDetails()
    {

        $country_id = $_POST['country_id'];
        $from_date = Yii::app()->request->getParam('fromdate');
        $end_date = Yii::app()->request->getParam('todate');
        $graph_detail = Yii::app()->db->createCommand('SELECT YEAR(inv.invoice_date) as y, MONTH(inv.invoice_date) as m, COUNT(inv.id) as TOTAL_COUNT,SUM(inv.grand_total) AS TOTAL_AMT  FROM {{invoice}} AS inv
                                                        INNER JOIN {{customer}} AS customer ON inv.customer_id=customer.id  
                                                        INNER JOIN {{mas_country}} AS country ON customer.customer_country=country.id 
                                                        WHERE inv.invoice_date BETWEEN "' . $from_date . '" AND "' . $end_date . '" AND country.id="' . $country_id . '" GROUP BY y, m ORDER BY y DESC, m ASC')->queryAll();

        $this->render('invoice_country_details', array('graph_detail' => $graph_detail, 'country_id' => $country_id, 'action' => 'view_country_detail'));
    }

    public function actionGetInvoiceMonthDetails()
    {

        $country_id = $_POST['country_id'];
        $month = $_POST['month'];
        $year = $_POST['year'];
        $currentYear = date("Y");

        $graph_detail = Yii::app()->db->createCommand('SELECT inv.id AS invoice_id,inv.customer_id,inv.grand_total,inv.invoice_date FROM {{invoice}} AS inv  
                                                        INNER JOIN {{customer}} AS customer ON inv.customer_id=customer.id 
                                                        INNER JOIN {{mas_country}} AS country ON customer.customer_country=country.id 
                                                        WHERE YEAR(inv.invoice_date) = "' . $year . '" AND MONTH(inv.invoice_date) = "' . $month . '" AND country.id="' . $country_id . '"')->queryAll();


        $this->render('invoice_country_details', array('graph_detail' => $graph_detail, 'action' => 'view_country_month_detail', 'month' => $month, 'year' => $year));
    }

    /***********************   start - invoice sales group *****************************************************/


    public function actionGetInvoiceSalesGroupDetail()
    {

        $lead_graph_details = array();
        //            $currentYear  = date("Y");
        $from_date = Yii::app()->request->getParam('fromdate');
        $end_date = Yii::app()->request->getParam('todate');
        $graph_data_quantity = Yii::app()->db->createCommand('SELECT sales_group.id AS SALES_GROUP_ID,sales_group.group_name AS x_value,SUM(inv.grand_total) AS y_value,COUNT(*) AS inv_count FROM {{invoice}} AS inv 
                                                        INNER JOIN {{mas_sales_group}} AS sales_group ON inv.sales_group_id =sales_group.id                                                          
                                                        WHERE inv.invoice_date BETWEEN "' . $from_date . '" AND "' . $end_date . '"  GROUP BY sales_group.id')->queryAll();

        $plot = '[';
        foreach ($graph_data_quantity as $m => $eachdata) {
            $color = substr(md5(rand()), 0, 6);
            $plot .= '{label:"' . $eachdata['x_value'] . '", value:"' . $eachdata['y_value'] . '", color: "#' . $color . '"},';
            $lead_graph_details[$m]['slno'] = $m + 1;
            $lead_graph_details[$m]['sales_group'] = $eachdata['x_value'];
            $lead_graph_details[$m]['amount'] = $eachdata['y_value'];
            $lead_graph_details[$m]['order_count'] = $eachdata['inv_count'];
            $lead_graph_details[$m]['order_color'] = "#" . $color;
            $lead_graph_details[$m]['sales_group_id'] = $eachdata['SALES_GROUP_ID'];
        }
        $plot .= ']';

        foreach ($lead_graph_details as $key => $value) {

            $SQL_cost_rate = "SELECT SUM(cost_rate * quantity) AS cost_rate,SUM(rate * quantity) AS selling_rice,SUM(tax_vat_amount) AS tax_vat_amount  FROM `erp_invoice_item` AS item 
                INNER JOIN erp_invoice INV ON item.invoice_id=INV.id  
                INNER JOIN {{mas_sales_group}} AS sales_group ON INV.sales_group_id=sales_group.id  
                WHERE invoice_date BETWEEN '" . $from_date . "' AND '" . $end_date . "' AND INV.sales_group_id=" . $value['sales_group_id'];
            //echo $SQL_cost_rate;
            $arr_invoice_item_details = Yii::app()->db->createCommand($SQL_cost_rate)->queryRow();
            $profit = $arr_invoice_item_details['selling_rice'] - $arr_invoice_item_details['cost_rate'];
            $profit_percentage = ($profit * 100) / $arr_invoice_item_details['cost_rate'];


            $rowData[] = array($value['slno'], $value['sales_group'], $value['order_count'], Yii::app()->numberFormatter->formatCurrency($arr_invoice_item_details['selling_rice'], ""), Yii::app()->numberFormatter->formatCurrency($arr_invoice_item_details['cost_rate'], ""), Yii::app()->numberFormatter->formatCurrency($profit, ""), Yii::app()->numberFormatter->formatCurrency($profit_percentage, ""), $value['order_color'], $value['sales_group_id']);
        }
        $data['data'] = $rowData;
        $data['plot'] = $plot;
        echo json_encode($data);
    }

    public function actionInvoiceSalesGroupDetails()
    {

        $group_id = $_POST['group_id'];
        //$currentYear  = date("Y");
        $from_date = Yii::app()->request->getParam('fromdate');
        $end_date = Yii::app()->request->getParam('todate');

        $graph_detail = Yii::app()->db->createCommand('SELECT YEAR(inv.invoice_date) as y, MONTH(inv.invoice_date) as m, COUNT(inv.id) as TOTAL_COUNT,SUM(inv.grand_total) AS TOTAL_AMT FROM {{invoice}} AS inv
                                                        INNER JOIN {{mas_sales_group}} AS sales_group ON inv.sales_group_id =sales_group.id                                                          
                                                        WHERE YEAR(inv.invoice_date) = "' . $from_date . '" AND "' . $end_date . '" AND sales_group.id="' . $group_id . '" GROUP BY y, m ORDER BY y DESC, m ASC')->queryAll();

        $this->render('invoice_sales_group_details', array('graph_detail' => $graph_detail, 'group_id' => $group_id, 'action' => 'view_sales_group_detail'));

    }
    public function actionInvoiceSalesMonthDetails()
    {

        $group_id = $_POST['group_id'];
        $month = $_POST['month'];
        $year = $_POST['year'];
        $currentYear = date("Y");


        $graph_detail = Yii::app()->db->createCommand('SELECT inv.id AS invoice_id,inv.customer_id,inv.grand_total,inv.invoice_date FROM {{invoice}} AS inv
                                                        INNER JOIN {{mas_sales_group}} AS sales_group ON inv.sales_group_id=sales_group.id  
                                                        WHERE YEAR(inv.invoice_date) = "' . $year . '" AND MONTH(inv.invoice_date) = "' . $month . '" AND sales_group.id="' . $group_id . '"')->queryAll();

        $this->render('invoice_sales_group_details', array('graph_detail' => $graph_detail, 'action' => 'view_sales_group_month_detail', 'month' => $month, 'year' => $year));
    }


    /***********************   End - invoice sales group *****************************************************/
    /***********************   start - invoice Items *****************************************************/
    public function actiongetInvoiceItems()
    {

        $invoice_id = $_POST['invoice_id'];
        $this->render('view_InvoiceItems', array('invoice_id' => $invoice_id));
    }
    /***********************   End - order Items *****************************************************/

    public function actionGetInvoiceDetail()
    {

        $lead_graph_details = array();
        $currentYear = date("Y");
        $currentmonth = date("m");
        $from_date = Yii::app()->request->getParam('fromdate');
        $end_date = Yii::app()->request->getParam('todate');
        $month = date("m", strtotime($from_date));
        $month_1 = date("m", strtotime($end_date));
        $year = date("Y", strtotime($end_date));
        if ($year == $currentYear) {
            $month_1 = $currentmonth;
        }
        $m = 1;
        $plot = '[';
        for ($k = $month; $k <= $month_1; $k++) {
            $dateObj = DateTime::createFromFormat('!m', $k);
            $monthName = $dateObj->format('F');
            $graphdata3 = Yii::app()->db->createCommand('SELECT sum(grand_total) AS value,count(id) as inv_count FROM {{invoice}}  WHERE YEAR(invoice_date) = "' . $year . '" AND MONTH(invoice_date) = "' . $k . '"')->queryAll();
            $SQL_cost_rate = 'SELECT SUM(cost_rate * quantity) AS cost_rate,SUM(rate * quantity) AS selling_rice,SUM(tax_vat_amount) AS tax_vat_amount  FROM `erp_invoice_item` INNER JOIN erp_invoice AS INV ON INV.id=invoice_id  WHERE YEAR(invoice_date) = "' . $year . '" AND MONTH(invoice_date) = "' . $k . '"';
            //echo $SQL_cost_rate;
            $arr_invoice_item_details = Yii::app()->db->createCommand($SQL_cost_rate)->queryRow();
            foreach ($graphdata3 as $eachdata) {


                $arr_invoice_item_details = Yii::app()->db->createCommand($SQL_cost_rate)->queryRow();


                $color = substr(md5(rand()), 0, 6);
                $plot .= '{label:"' . $monthName . '", value:"' . $eachdata['value'] . '", color: "#' . $color . '" },';
                $invoice_color = "#" . $color;

                $profit = $arr_invoice_item_details['selling_rice'] - $arr_invoice_item_details['cost_rate'];

                // $profit_percentage = ($profit * 100) / $arr_invoice_item_details['cost_rate'];
                $profit_percentage = ($arr_invoice_item_details['cost_rate'] != 0) ? ($profit * 100) / $arr_invoice_item_details['cost_rate'] : 0;
                $rowData[] = array(
                    $m++,
                    $monthName,
                    $eachdata['inv_count'],
                    Yii::app()->numberFormatter->formatCurrency($eachdata['value'], ""),
                    Yii::app()->numberFormatter->formatCurrency($arr_invoice_item_details['tax_vat_amount'], ""),
                    Yii::app()->numberFormatter->formatCurrency($arr_invoice_item_details['selling_rice'], ""),
                    Yii::app()->numberFormatter->formatCurrency($arr_invoice_item_details['cost_rate'], ""),
                    Yii::app()->numberFormatter->formatCurrency($profit, ""),
                    Yii::app()->numberFormatter->formatCurrency($profit_percentage, ""),
                    $k,
                    $year,
                    $invoice_color
                );

            }

        }
        $plot .= ']';
        //            $graph_data_quantity = Yii::app()->db->createCommand('SELECT invoice_no AS x_value,grand_total AS y_value,invoice_date FROM {{invoice}}  WHERE YEAR(invoice_date) = "'.$currentYear.'"')->queryAll();
//            $plot = '[';
//           foreach($graph_data_quantity as  $m=>$eachdata ){
//                $color = substr(md5(rand()), 0, 6);
//                $plot .= '{label:"'.$eachdata['x_value'].'", value:"'.$eachdata['y_value'].'", color: "#'.$color.'"},';
//                $lead_graph_details[$m]['slno']=$m+1;
//                $lead_graph_details[$m]['invoice_no']=$eachdata['x_value'];
//                $lead_graph_details[$m]['invoice_amount']=$eachdata['y_value'];
//                $lead_graph_details[$m]['invoice_date']=$eachdata['invoice_date'];
//                $lead_graph_details[$m]['invoice_color']="#".$color;
//            }
//            $plot .= ']';
//            
//            foreach ($lead_graph_details as $key => $value) {
//                $rowData[]=array($value['slno'],$value['invoice_no'],date('d/m/Y', strtotime($value['invoice_date'])),$value['invoice_amount'],$value['invoice_color']);
//            }
        $data['data'] = $rowData;
        $data['plot'] = $plot;
        echo json_encode($data);
    }

    public function actionGetMonthlyInvoice()
    {

        $lead_graph_details = array();
        $currentYear = date("Y");


        $currentmonth = $_POST['month'];
        $graph_data_quantity = Yii::app()->db->createCommand('SELECT invoice_no AS x_value,grand_total AS y_value,invoice_date FROM {{invoice}}  WHERE YEAR(invoice_date) = "' . $currentYear . '" AND MONTH(invoice_date) = "' . $currentmonth . '"')->queryAll();
        $plot = '[';
        foreach ($graph_data_quantity as $m => $eachdata) {
            $color = substr(md5(rand()), 0, 6);
            $plot .= '{label:"' . $eachdata['x_value'] . '", value:"' . $eachdata['y_value'] . '", color: "#' . $color . '"},';
            $lead_graph_details[$m]['slno'] = $m + 1;
            $lead_graph_details[$m]['invoice_no'] = $eachdata['x_value'];
            $lead_graph_details[$m]['invoice_amount'] = $eachdata['y_value'];
            $lead_graph_details[$m]['invoice_date'] = $eachdata['invoice_date'];
            $lead_graph_details[$m]['invoice_color'] = "#" . $color;
        }
        $plot .= ']';

        foreach ($lead_graph_details as $key => $value) {
            $rowData[] = array($value['slno'], $value['invoice_no'], date('d/m/Y', strtotime($value['invoice_date'])), $value['invoice_amount'], $value['invoice_color']);
        }
        $data['data'] = $rowData;
        $data['plot'] = $plot;
        echo json_encode($data);
    }

    public function actionInvoiceYear()
    {

        $month = $_POST['month'];
        $year = $_POST['year'];
        $model_invoice = Yii::app()->db->createCommand('SELECT id AS invoice_id,delivery_ids,invoice_no,grand_total,invoice_date FROM {{invoice}}  WHERE YEAR(invoice_date) = "' . $year . '" AND MONTH(invoice_date) = "' . $month . '"')->queryAll();
        $this->render('invoice_details_month', array('model_invoice' => $model_invoice));
    }

    public function actionGetOrderDetail()
    {

        $lead_graph_details = array();
        $currentYear = date("Y");
        $currentmonth = date("m");
        $from_date = Yii::app()->request->getParam('fromdate');
        $end_date = Yii::app()->request->getParam('todate');
        $month = date("m", strtotime($from_date));
        $month_1 = date("m", strtotime($end_date));
        $year = date("Y", strtotime($end_date));
        if ($year == $currentYear) {
            $month_1 = $currentmonth;
        }
        $m = 1;
        $plot = '[';
        for ($k = $month; $k <= $month_1; $k++) {
            $dateObj = DateTime::createFromFormat('!m', $k);
            $monthName = $dateObj->format('F');
            $graphdata3 = Yii::app()->db->createCommand('SELECT count(id) as x_value,sum(grand_total*exchange_rate) AS value FROM {{order}}  WHERE YEAR(order_date) = "' . $year . '" AND MONTH(order_date) = "' . $k . '"')->queryAll();

            foreach ($graphdata3 as $eachdata) {
                $color = substr(md5(rand()), 0, 6);
                $plot .= '{label:"' . $monthName . '", value:"' . $eachdata['x_value'] . '", color: "#' . $color . '" },';
                $invoice_color = "#" . $color;
                $rowData[] = array($m++, $monthName, $eachdata['x_value'], Yii::app()->numberFormatter->formatCurrency($eachdata['value'], ""), $k, $year, $invoice_color);

            }

        }
        $plot .= ']';
        $data['data'] = $rowData;
        $data['plot'] = $plot;
        echo json_encode($data);
    }

    public function actionOrderYear()
    {

        $month = $_POST['month'];
        $year = $_POST['year'];
        $model_order = Yii::app()->db->createCommand('SELECT id,grand_total,order_date,delivery_date FROM {{order}}  WHERE YEAR(order_date) = "' . $year . '" AND MONTH(order_date) = "' . $month . '"')->queryAll();
        $this->render('order_details_month', array('model_order' => $model_order));
    }
    public function actionLeadYear()
    {

        $month = $_POST['month'];
        $year = $_POST['year'];
        $model_lead = Yii::app()->db->createCommand('SELECT id,value,enq_date FROM {{lead}}  WHERE YEAR(enq_date) = "' . $year . '" AND MONTH(enq_date) = "' . $month . '"')->queryAll();
        $this->render('lead_details_month', array('model_lead' => $model_lead));
    }
    public function actionQuotesYear()
    {

        $month = $_POST['month'];
        $year = $_POST['year'];
        $model_quotes = Yii::app()->db->createCommand('SELECT id,grand_total,qtn_start_date,qtn_validity FROM {{quotes}}  WHERE YEAR(qtn_start_date) = "' . $year . '" AND MONTH(qtn_start_date) = "' . $month . '"')->queryAll();
        $this->render('quotes_details_month', array('model_quotes' => $model_quotes));
    }
    //     
//       public function actionloadInvoicesMtdGraph(){  
//            $currentYear  = date("Y");
//            $currentmonth  =$_POST['month'];                                      
//            $graphdata4 = Yii::app()->db->createCommand('SELECT CONCAT(user.first_name," ",user.last_name) AS lead_ownername,user.id AS leadowner_id FROM {{invoice}} AS inv 
//                                                           INNER JOIN {{master_file}} AS filedetail ON inv.file_id=filedetail.id 
//                                                        INNER JOIN '.User::MainDb.'.{{user}} AS user ON filedetail.lead_owner_id=user.id 
//                                                        WHERE YEAR(inv.invoice_date)="'.$currentYear.'" AND MONTH(inv.invoice_date)="'.$currentmonth.'" GROUP BY user.id')->queryAll();
//
//            $plot = '{ "xScale" : "ordinal", "yScale": "linear",  "main":[{ "className": ".pizza","data": [';
//
//
//            foreach($graphdata4 as $eachdata ){
//                    $total  =Yii::app()->db->createCommand('SELECT  sum(inv.grand_total) FROM {{invoice}} AS inv 
//                                                               INNER JOIN {{master_file}} AS filedetail ON inv.file_id=filedetail.id 
//                                                            INNER JOIN '.User::MainDb.'.{{user}} AS user ON filedetail.lead_owner_id=user.id 
//                                                            WHERE YEAR(inv.invoice_date)="'.$currentYear.'" AND MONTH(inv.invoice_date)="'.$currentmonth.'" AND user.id="'.$eachdata['leadowner_id'].'"')->queryScalar();                    
//                    $plot .= '{"x":"'.$eachdata['lead_ownername'].'", "y":'.$total.'},';
//            }
//
//            $plot .= ']';
//            $plot .= ' }]';
//            $plot .= ' };';
//           $data['plot'] = $plot;
//           echo json_encode($data);
//     }   
    public function actionloadInvoicesMtdGraph()
    {
        $month = explode("-", $_POST['month']);
        $currentyear = $month[0];
        $currentmonth = $month[1];
        $this->render('invoice_mtd_graph', array('currentyear' => $currentyear, 'currentmonth' => $currentmonth));
    }
    public function actionloadOrderMtdGraph()
    {
        $month = explode("-", $_POST['month']);
        $currentyear = $month[0];
        $currentmonth = $month[1];
        $this->render('order_mtd_graph', array('currentyear' => $currentyear, 'currentmonth' => $currentmonth));
    }

    //  public function actionCurrent_stock_details(){
    //     $query = 'SELECT G.brand AS brand, G.stock_value AS quantity FROM (SELECT
    //     B.product_class AS brand,
    //     SUM(P.quantity) * S.rate AS stock_value
    //     FROM crm_product_location P LEFT JOIN crm_store S ON S.id = P.stock_id
    //     LEFT JOIN crm_product_class B ON S.brand_class_id = B.id GROUP BY S.id ) AS G GROUP BY G.brand';
    // $graphdata4 = Yii::app()->db->createCommand($query)->queryAll();

    //     $plot = '[';
    //     foreach($graphdata4 as $eachdata ){
    //         $color = substr(md5(rand()), 0, 6);
    //         $plot .= '{label:"'.$eachdata['brand'].'", value:"'.$eachdata['quantity'].'", color: "#'.$color.'"},';
    //     }
    //     $plot .= ']';

    //      $this->render('stock_details_view', array('plot' => $plot,'graphdata4' => $graphdata4));
    //  }


    public function actionGetMonthlyBrandWiseDetails()
    {
        $year = Yii::app()->request->getParam('year');
        $month = Yii::app()->request->getParam('month');
        $monthNum = $this->getMonthNumber($month);
        $start_date = $year . "-" . $monthNum . "-01";
        $end_date = date("Y-m-t", strtotime($start_date));
        ;
        Yii::app()->clientScript->scriptMap = array('*jquery.js' => false, '*jquery.min.js' => false, 'jquery.min.js' => false, '*jquery-ui.js' => false, '*jquery-ui.min.js' => false, '*jquery-2.1.4.min.js' => false, 'jquery-2.1.4.min.js' => false);
        $SQL = "SELECT brandname,SUM(CASE transaction_type WHEN 'invoice' THEN net_amount WHEN 'creditnote' THEN -net_amount END) AS invoice_amount  
                        FROM `view_sales_item_brand` WHERE transaction_date BETWEEN '" . $start_date . "' AND '" . $end_date . "' GROUP BY brand_class_id";
        //echo $SQL."<br>";
        $arr_transaction_details = Yii::app()->db->createCommand($SQL)->queryAll();
        //$graph_data_quantity = Yii::app()->db->createCommand('SELECT CONCAT(user.first_name," ",user.last_name) AS x_value,SUM(quotes.grand_total) AS y_value FROM {{quotes}} AS quotes INNER JOIN '.User::MainDb.'.{{user}} AS user ON quotes.lead_owner_id=user.id WHERE quotes.qtn_start_date BETWEEN "'.$from_date.'" AND "'.$end_date.'"  GROUP BY user.id')->queryAll();
        $plot = '[';
        foreach ($arr_transaction_details as $m => $eachdata) {
            $color = substr(md5(rand()), 0, 6);
            $plot .= '{label:"' . $eachdata['brandname'] . '", value:"' . $eachdata['invoice_amount'] . '", color: "#' . $color . '"},';
        }
        $plot .= ']';
        //echo $plot;
        //exit;
        $this->render('brand_details', array('plot' => $plot, 'from_date' => $start_date, 'end_date' => $end_date));

    }

    public function actionGetBrandWiseDetail()
    {
        $from_date = Yii::app()->request->getParam('fromdate');
        $end_date = Yii::app()->request->getParam('todate');
        $SQL = "SELECT brand_class_id,brandname,SUM(CASE transaction_type WHEN 'invoice' THEN net_amount WHEN 'creditnote' THEN -net_amount END) AS invoice_amount  
                        FROM `view_sales_item_brand` WHERE transaction_date BETWEEN '" . $from_date . "' AND '" . $end_date . "' GROUP BY brand_class_id";
        $arr_transaction_details = Yii::app()->db->createCommand($SQL)->queryAll();
        $slno = 0;
        foreach ($arr_transaction_details as $key => $value) {
            $slno++;
            $rowData[] = array($slno, $value['brandname'], Yii::app()->numberFormatter->formatCurrency($value['invoice_amount'], ""), $value['brand_class_id']);
        }
        $data['data'] = $rowData;
        echo json_encode($data);
    }

    public function actionBrandGraphOwnerDetails()
    {
        $from_date = Yii::app()->request->getParam('fromdate');
        $end_date = Yii::app()->request->getParam('todate');
        $brand_class_id = Yii::app()->request->getParam('brand_class_id');

        $SQL = "SELECT lead_owner_id,brandname,SUM(CASE transaction_type WHEN 'invoice' THEN net_amount WHEN 'creditnote' THEN -net_amount END) AS invoice_amount  
                        FROM `view_sales_item_brand` WHERE brand_class_id=" . $brand_class_id . " AND transaction_date BETWEEN '" . $from_date . "' AND '" . $end_date . "' GROUP BY lead_owner_id";
        $arr_transaction_details = Yii::app()->db->createCommand($SQL)->queryAll();

        $this->render('brand_lead_owner_details', array('graph_detail' => $arr_transaction_details, 'brand_class_id' => $brand_class_id));

    }


    public function getMonthNumber($m)
    {
        if ($m == "January") {
            return "01";
        } else if ($m == "February") {
            return "02";
        } else if ($m == "March") {
            return "03";
        } else if ($m == "April") {
            return "04";
        } else if ($m == "May") {
            return "05";
        } else if ($m == "June") {
            return "06";
        } else if ($m == "July") {
            return "07";
        } else if ($m == "August") {
            return "08";
        } else if ($m == "September") {
            return "09";
        } else if ($m == "October") {
            return "10";
        } else if ($m == "November") {
            return "11";
        } else if ($m == "December") {
            return "12";
        }

    }
    public function actionFollowUps()
    {
        $this->render('reminder_index');
    }
    public function actionAIDashboard() 
    {
        //$this->layout = false;
        
        $id = 1001;
        
        $model = new Customer();
        $model = $model->findByPk($id);
        
        // Get contacts for this customer
        $contactsDataProvider = new CActiveDataProvider('CustomerContact', array(
            'criteria' => array(
                'condition' => 'customer_id=:customerId',
                'params' => array(':customerId' => $id),
                'order' => 'person_name ASC',
            ),
            'pagination' => array(
                'pageSize' => 10,
            ),
        ));
        
        // Get leads for this customer
        $leadsDataProvider = new CActiveDataProvider('Lead', array(
            'criteria' => array(
                'condition' => 'customer_id=:customerId',
                'params' => array(':customerId' => $id),
                'order' => 'created_datetime DESC',
            ),
            'pagination' => array(
                'pageSize' => 5,
            ),
        ));
        
        // Get quotes for this customer
        $quotesDataProvider = new CActiveDataProvider('Quotes', array(
            'criteria' => array(
                'condition' => 'customer_id=:customerId',
                'params' => array(':customerId' => $id),
                'order' => 'created_date_time DESC',
            ),
            'pagination' => array(
                'pageSize' => 5,
            ),
        ));
        
        // Get orders for this customer
        $ordersDataProvider = new CActiveDataProvider('Order', array(
            'criteria' => array(
                'condition' => 'customer_id=:customerId',
                'params' => array(':customerId' => $id),
                'order' => 'created_datetime DESC',
            ),
            'pagination' => array(
                'pageSize' => 5,
            ),
        ));
        
        // Get invoices for this customer
        $invoicesDataProvider = new CActiveDataProvider('Invoice', array(
            'criteria' => array(
                'condition' => 'customer_id=:customerId',
                'params' => array(':customerId' => $id),
                'order' => 'created_datetime DESC',
            ),
            'pagination' => array(
                'pageSize' => 5,
            ),
        ));
        
        $this->render('index_ai_dashboard', array(
            'model' => $model,
            'contactsDataProvider' => $contactsDataProvider,
            'leadsDataProvider' => $leadsDataProvider,
            'quotesDataProvider' => $quotesDataProvider,
            'ordersDataProvider' => $ordersDataProvider,
            'invoicesDataProvider' => $invoicesDataProvider,
        ));
        
        
        //$this->render('index_ai_dashboard');
    }

}