<?php
        //Quotation Owner
        $total_value = 0;
        $from_date_original = $fromdate;
        $to_date_original = $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));
    $month=date("m",strtotime($fromdate));
    $month_1=date("m",strtotime($todate));
    $year=date("Y",strtotime($todate));
    $orderextra_cndt='';
    if(Yii::app()->user->authorised_user != 1 && User::isSalesman()=='Y'){
        $orderextra_cndt =' AND ord.lead_owner_id='.Yii::app()->user->id;
    }
    /* $graph_data_quantity = Yii::app()->db->createCommand('SELECT CONCAT(user.first_name," ",user.last_name) AS x_value,sum(grand_total*exchange_rate) AS y_value FROM {{order}} AS ord INNER JOIN '.MasCompany::MainDB.'.{{user}} AS user ON ord.lead_owner_id=user.id  WHERE ord.order_date BETWEEN "'.$from_date.'" AND "'.$end_date.'"  '.$orderextra_cndt.'  GROUP BY user.id')->queryAll();
      $order_plot = '[';
     foreach($graph_data_quantity as $eachdata ){
          $color = substr(md5(rand()), 0, 6);
          $order_plot .= '{label:"'.$eachdata['x_value'].'", value:'.round($eachdata['y_value'],0).', color: "#'.$color.'"},';
      }
      $order_plot .= ']';
  //Country
        $graphdata = Yii::app()->db->createCommand('SELECT sum(grand_total*exchange_rate) AS value,emirates.emirates_name AS label FROM {{order}} AS ord INNER JOIN {{customer}} AS customer ON ord.customer_id=customer.id INNER JOIN {{mas_emirates_list}} AS emirates ON customer.customer_emirates_name=emirates.id WHERE ord.order_date BETWEEN "'.$from_date.'" AND "'.$end_date.'"   '.$orderextra_cndt.'  GROUP BY customer.customer_emirates_name
 ')->queryAll();
     $order_plot_1 = '[';
     foreach($graphdata as $eachdata ){
         $color = substr(md5(rand()), 0, 6);
         $order_plot_1 .= '{label:"'.$eachdata['label'].'", value:"'.round($eachdata['value'],0).'", color: "#'.$color.'"},';
         $total_value += $eachdata['value'];
     }
     $order_plot_1 .= ']';*/
     $graphdata2 = Yii::app()->db->createCommand('SELECT sales_group.group_name AS label,sum(grand_total*exchange_rate) AS 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.'"   '.$orderextra_cndt.'  GROUP BY sales_group.id')->queryAll();
    $order_plot_2 = '[';
    foreach($graphdata2 as $eachdata ){
         $color = substr(md5(rand()), 0, 6);
         $order_plot_2 .= '{label:"'.$eachdata['label'].'", value:"'.round($eachdata['value'],0).'", color: "#'.$color.'" },';
     }
     $order_plot_2 .= ']';
     
    $currentYear  = date("Y");
    $currentmonth  = date("m");
    if($year==$currentYear){
        $month_1=$currentmonth;
    }
    $order_plot_3 = '[';
    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 {{order}} AS ord  WHERE YEAR(order_date) = "'.$year.'" AND MONTH(order_date) = "'.$k.'"   '.$orderextra_cndt.' ')->queryAll();

        foreach($graphdata3 as $eachdata ){
             $color = substr(md5(rand()), 0, 6);
             $order_plot_3 .= '{label:"'.$monthName.'", value:"'.round($eachdata['value'],0).'", color: "#'.$color.'" },';
         }
        
    }
     $order_plot_3 .= ']';
     
     
     
     $currentYear  = date("Y");
    $currentmonth  = date("m");
    if($year==$currentYear){
        $month_1=$currentmonth;
    }
    
    
    $order_plot_year = '[';
   
        $graphdatayear = Yii::app()->db->createCommand('SELECT sum(grand_total*exchange_rate) AS value FROM {{order}} AS ord  WHERE YEAR(order_date) = "'.$year.'" GROUP BY YEAR(order_date) ')->queryAll();
    
       
        foreach ($graphdatayear as $eachdata) {
            // Generate a random color for each month
            $color = substr(md5(rand()), 0, 6);
            
            // Add data for each month to the plot
            $order_plot_year .= '{label:"Year-' . $currentYear . '", value:"'.round($eachdata['value'], 0).'", color: "#'.$color.'" },';
        }
   // }
    $order_plot_year .= ']';

    
    
    
      //Bar Chart
        $fromdate_1= str_replace('/', '-',$from_date_original);;
                    $month=date("m",strtotime($fromdate_1));   
                    $todate_1= str_replace('/', '-',$to_date_original);
                    $end_year= date("Y", strtotime($todate_1));
                    $month_1=date("m",strtotime($todate_1));
       $selected=$end_year.'-01';
                $currentYear_1  = date("Y");
                if($end_year==$currentYear_1){
                     $selected=$end_year.'-'.date('n');
                 }

        $ord_value=explode('-',$selected);
        $ord_year=$ord_value[0];
        $ord_month=$ord_value[1];
         $total_amount  =Yii::app()->db->createCommand('SELECT sum(ord.grand_total*exchange_rate) FROM {{order}} AS ord 
                                                        INNER JOIN '.MasCompany::MainDB.'.{{user}} AS user ON ord.lead_owner_id=user.id 
                                                        WHERE YEAR(ord.order_date)="'.$ord_year.'" AND MONTH(ord.order_date)="'.$ord_month.'"   '.$orderextra_cndt.' ')->queryScalar();                    
        $graphdata4 = Yii::app()->db->createCommand('SELECT CONCAT(user.first_name," ",user.last_name) AS lead_ownername,user.id AS leadowner_id FROM {{order}} AS ord 
                                                        INNER JOIN '.MasCompany::MainDB.'.{{user}} AS user ON ord.lead_owner_id=user.id 
                                                        WHERE YEAR(ord.order_date)="'.$ord_year.'" AND MONTH(ord.order_date)="'.$ord_month.'"   '.$orderextra_cndt.'  GROUP BY user.id')->queryAll();
 
        $plot = '{ "xScale" : "ordinal", "yScale": "linear",  "main":[{ "className": ".pizza","data": [';
        $total=0;
        $percentage_amount=0.00;
        foreach($graphdata4 as $eachdata ){
                 $total  =Yii::app()->db->createCommand('SELECT sum(ord.grand_total*exchange_rate) FROM {{order}} AS ord 
                                                        INNER JOIN '.MasCompany::MainDB.'.{{user}} AS user ON ord.lead_owner_id=user.id 
                                                        WHERE YEAR(ord.order_date)="'.$ord_year.'" AND MONTH(ord.order_date)="'.$ord_month.'" AND user.id="'.$eachdata['leadowner_id'].'"   '.$orderextra_cndt.' ')->queryScalar();                    
//                $plot .= '{"x":"'.$eachdata['lead_ownername'].'", "y":'.$total.'},';
                  $percentage_amount= number_format(($total/$total_amount)*100,2);
                  $plot.='{"y": '.$total.',"x": "'.$eachdata['lead_ownername']." ( $percentage_amount% )".'"},';
        }
           
        $plot .= ']';
        $plot .= ' }]';
        $plot .= ' };';
        
        
           $total_amount  =Yii::app()->db->createCommand('SELECT sum(ord.grand_total*exchange_rate) FROM {{order}} AS ord 
                                                        INNER JOIN '.MasCompany::MainDB.'.{{user}} AS user ON ord.lead_owner_id=user.id 
                                                        WHERE YEAR(ord.order_date)="'.$ord_year.'" AND MONTH(ord.order_date)="'.$ord_month.'"')->queryScalar();                    
        /*$graphdata4 = Yii::app()->db->createCommand('SELECT CONCAT(user.first_name," ",user.last_name) AS lead_ownername,user.id AS leadowner_id FROM {{order}} AS ord 
                                                        INNER JOIN '.MasCompany::MainDB.'.{{user}} AS user ON ord.lead_owner_id=user.id 
                                                        WHERE YEAR(ord.order_date)="'.$ord_year.'" AND MONTH(ord.order_date)="'.$ord_month.'" GROUP BY user.id')->queryAll();*/
                                                        $graphdata4 = Yii::app()->db->createCommand('SELECT CONCAT(user.first_name) AS lead_ownername,user.id AS leadowner_id FROM {{order}} AS ord 
                                                        INNER JOIN '.MasCompany::MainDB.'.{{user}} AS user ON ord.lead_owner_id=user.id 
                                                        WHERE YEAR(ord.order_date)="'.$ord_year.'" AND MONTH(ord.order_date)="'.$ord_month.'"   '.$orderextra_cndt.'  GROUP BY user.id')->queryAll();
 
        
        
        $chartData = '';
   $percentage_amount=0.00;
  foreach($graphdata4 as $eachdata ){
               $total  =Yii::app()->db->createCommand('SELECT sum(ord.grand_total*exchange_rate) FROM {{order}} AS ord 
                                                        INNER JOIN '.MasCompany::MainDB.'.{{user}} AS user ON ord.lead_owner_id=user.id 
                                                        WHERE YEAR(ord.order_date)="'.$ord_year.'" AND MONTH(ord.order_date)="'.$ord_month.'" AND user.id="'.$eachdata['leadowner_id'].'"   '.$orderextra_cndt.' ')->queryScalar();                    
//                $plot .= '{"x":"'.$eachdata['lead_ownername'].'", "y":'.$total.'},';                 
                $percentage_amount= number_format(($total/$total_amount)*100,2);
                
                $chartData.='{"lead_owner": "'.$eachdata['lead_ownername'].'","total_amount": "'.$total.'","percentage_amount": "'.$percentage_amount.'"},';

        }

?>

<div class="clearfix"></div>
<br>
<div class="clearfix">
    <!--div class="col-lg-3" data-initial-class="col-lg-3" id="pieChartParent">
        <section class="panel">
            <header class="panel-heading">
                Lead Owner 
            </header>
            <div class="panel-body text-center">
                <div class="clearfix canvas-holder">
                    <?php if (isset(Yii::app()->user->havePermissionOn['dashboard_dril_level1_view']) ||
                                                    Yii::app()->user->authorised_user == 1) {
                                                ?>
                    <canvas id="order_myChart" width="400" height="400" onclick="loadPopupModal('dashboard/order_graphdetails&type=1&from_date=<?php echo $from_date_original; ?>&end_date=<?php echo $to_date_original?>','Order- Lead Owner','lg');"></canvas>
                    <?php }else{ ?>
                    <canvas id="order_myChart" width="400" height="400"></canvas>
                    <?php } ?>
                </div>
            </div>
        </section>
    </div>
    <div class="col-lg-3" data-initial-class="col-lg-3" id="pieChartParent_1">
        <section class="panel">
            <header class="panel-heading">
                Emirates 
            </header>
            <div class="panel-body text-center">
                <div class="clearfix canvas-holder">
                    <?php if (isset(Yii::app()->user->havePermissionOn['dashboard_dril_level1_view']) ||
                                                    Yii::app()->user->authorised_user == 1) {
                                                ?>
                    <canvas id="order_myChart_1" width="400" height="400" onclick="loadPopupModal('dashboard/order_graphdetails&type=2&from_date=<?php echo $from_date_original; ?>&end_date=<?php echo $to_date_original?>','Order- Emirates','lg');"></canvas>
                    <?php }else{ ?>
                    <canvas id="order_myChart_1" width="400" height="400"></canvas>
                    <?php } ?>
                </div>
            </div>
        </section>
    </div-->
    
    
     <div class="col-lg-3" data-initial-class="col-lg-3" id="pieChartParent_year">
        <section class="panel">
            <header class="panel-heading">
                Year Wise
            </header>
            <div class="panel-body text-center">
                <div class="clearfix canvas-holder">
                    <?php if (isset(Yii::app()->user->havePermissionOn['dashboard_dril_level1_view']) ||
                                                    Yii::app()->user->authorised_user == 1) {
                                                ?>
                    <canvas id="order_myChart_year" width="400" height="400" onclick="loadPopupModal('dashboard/order_graphdetails&type=year&from_date=<?php echo $from_date_original; ?>&end_date=<?php echo $to_date_original?>','Order (Year Wise)- <?php echo $end_year; ?>','lg');"></canvas>
                    <?php }else{ ?>
                    <canvas id="order_myChart_year" width="400" height="400"></canvas>
                    <?php } ?>
                </div>
            </div>
        </section>
    </div>
    
    
    
    <div class="col-lg-3" data-initial-class="col-lg-3" id="pieChartParent_2">
        <section class="panel">
            <header class="panel-heading">
                Sales Group
            </header>
            <div class="panel-body text-center">
                <div class="clearfix canvas-holder">
                    <?php if (isset(Yii::app()->user->havePermissionOn['dashboard_dril_level1_view']) ||
                                                    Yii::app()->user->authorised_user == 1) {
                                                ?>
                    <canvas id="order_myChart_2" width="400" height="400" onclick="loadPopupModal('dashboard/order_graphdetails&type=3&from_date=<?php echo $from_date_original; ?>&end_date=<?php echo $to_date_original?>','Order- Sales Group','lg');"></canvas>
                    <?php }else{ ?>
                    <canvas id="order_myChart_2" width="400" height="400"></canvas>
                    <?php } ?>
                </div>
            </div>
        </section>
    </div>
      <div class="col-lg-3" data-initial-class="col-lg-3" id="pieChartParent_3">
        <section class="panel">
            <header class="panel-heading">
                   Months
            </header>
            <div class="panel-body text-center">
                <div class="clearfix canvas-holder">
                    <?php if (isset(Yii::app()->user->havePermissionOn['dashboard_dril_level1_view']) ||
                                                    Yii::app()->user->authorised_user == 1) {
                                                ?>
                    <canvas id="order_myChart_3" width="400" height="400" onclick="loadPopupModal('dashboard/order_graphdetails&type=4&from_date=<?php echo $from_date_original; ?>&end_date=<?php echo $to_date_original?>','Order- <?php echo $end_year; ?>','lg');"></canvas>
                    <?php }else{ ?>
                    <canvas id="order_myChart_3" width="400" height="400"></canvas>
                    <?php } ?>
                </div>
            </div>
        </section>
    </div>
    <div class="has-animate-child" id="div_graphorder_detailed_list" style="display:none;">
    <!--<div class="col-lg-8" data-initial-class="col-lg-3" id="pieChartParent_4">-->
    <div class="col-sm-12">
    <section class="panel">
      <header class="panel-heading">
        Order MTD <?php 
        
        $current_month = date('n');
        if($current_month<10){
            $current_month="0".$current_month;
        }
        
         $total_month_order_amount  =Yii::app()->db->createCommand('SELECT sum(ord.grand_total) FROM {{order}} AS ord 
                                                        INNER JOIN '.MasCompany::MainDB.'.{{user}} AS user ON ord.lead_owner_id=user.id 
                                                        WHERE YEAR(ord.order_date)="'.$end_year.'" AND MONTH(ord.order_date)="'.$current_month.'"')->queryScalar();     
               /* echo 'SELECT sum(ord.grand_total) FROM {{order}} AS ord 
                                                        INNER JOIN '.MasCompany::MainDB.'.{{user}} AS user ON ord.lead_owner_id=user.id 
                                                        WHERE YEAR(ord.order_date)="'.$end_year.'" AND MONTH(ord.order_date)="'.$current_month.'"';*/
                 echo CHtml::dropDownList('order_month', '', Dashboard::getMonths1($end_year,$month,$month_1), array(
               'options' => array($selected=>array('selected'=>true)),
                "onChange" => "loadOrderMtdGraph(this.value);"));
                ?> - <?php echo Yii::app()->numberFormatter->formatCurrency($total_month_order_amount,"");?>
      </header>
      <div class="panel-body">
        <div id="order_mtd_graph"></div>	
      </div>
      </section>
    </div>
    

    
    
</div>
</div>
</div>

<script type="text/javascript">

//Mileage Chart
var chart_mileage = AmCharts.makeChart("order_mtd_graph", {
    "theme": "light",
    "type": "serial",
    "dataProvider": [ <?php echo $chartData; ?> ],
    "valueAxes": [{
        "stackType": "3d",
        "unit": " AED",
        "position": "left",
        "title": "Total in AED",
    }],
    "startDuration": 1,
    "graphs": [{
        "balloonText": "[[total_amount]] ([[percentage_amount]]%)",
        "fillAlphas": 0.9,
        "lineAlpha": 0.2,
        "title": "ThisYear",
        "type": "column",
        "valueField": "total_amount"
    }/*, {
        "balloonText": "Fuel Expense [[category]] Last Year: <b>[[value]]</b>",
        "fillAlphas": 0.9,
        "lineAlpha": 0.2,
        "title": "LastYear",
        "type": "column",
        "valueField": "last_year"
    }*/],
    "plotAreaFillAlphas": 0.1,
    "depth3D": 60,
    "angle": 30,
    "categoryField": "lead_owner",
    "categoryAxis": {
        "gridPosition": "start",
	    "labelRotation": 90,
    },
    "export": {
    	"enabled": true
     },
  "hideCredits":true,
});
jQuery('.chart-input').off().on('input change',function() {
	var property	= jQuery(this).data('property');
	var target		= chart_mileage;
	chart_mileage.startDuration = 0;

	if ( property == 'topRadius') {
		target = chart_mileage.graphs[0];
      	if ( this.value == 0 ) {
          this.value = undefined;
      	}
	}

	target[property] = this.value;
	chart_mileage.validateNow();
});




</script>
<style>
#order_mtd_graph {
  width: 100%;
  height: 500px;
}																				
</style>

<script type="text/javascript">
    $(function(){
//        var data1 = [
//            { value : 300, color : "#F7464A", highlight : "#FF5A5E", label : "Red"},
//            { value : 50, color : "#46BFBD", highlight : "#5AD3D1", label : "Green"},
//            { value : 100, color : "#FDB45C", highlight : "#FFC870", label : "Yellow"}
//        ];
//var order_data1=<?php echo $order_plot;?>;
//var order_data2=<?php echo $order_plot_1;?>;
var order_data3=<?php echo $order_plot_2;?>;
var order_data4=<?php echo $order_plot_3;?>;
var order_data_year=<?php echo $order_plot_year;?>;
//var order_data5=<?php echo $plot;?>;
        /*var canvas1 =document.getElementById("order_myChart");
        Chart.defaults.global.responsive = true;
        var ctx = canvas1.getContext("2d");
        var pieChart = new Chart(ctx).Pie(order_data1);
        
         var canvas_1 =document.getElementById("order_myChart_1");
        Chart.defaults.global.responsive = true;
        var ctx_1 = canvas_1.getContext("2d");
        var pieChart_1 = new Chart(ctx_1).Pie(order_data2);*/
        
        var canvas_2 =document.getElementById("order_myChart_2");
        Chart.defaults.global.responsive = true;
        var ctx_2 = canvas_2.getContext("2d");
        var pieChart_2 = new Chart(ctx_2).Pie(order_data3);
        
        var canvas_3 =document.getElementById("order_myChart_3");
        Chart.defaults.global.responsive = true;
        var ctx_3 = canvas_3.getContext("2d");
        var pieChart_3 = new Chart(ctx_3).Pie(order_data4);
         //var myChart = new xChart('bar', order_data5, '#order_myChart_4');
         
         var canvas_year =document.getElementById("order_myChart_year");
        Chart.defaults.global.responsive = true;
        var ctx_year = canvas_year.getContext("2d");
        var pieChart_year = new Chart(ctx_year).Pie(order_data_year);
    });
    var c_size={
        //md:"col-xs-6 col-xs-offset-3",
      //  lg:"col-xs-8 col-xs-offset-2",
       // xl:"col-xs-12"
    }
    var returnNextItem= function(item){
        switch(item) {
            case "md":
                return "lg";
                break;
            case "lg":
                return "xl";
                break;
            case "xl":
                return "init";
                break;
            default:
                return "md";
        }
    }
    var growChart = function(id){
        var $el=$(id);
        var cs= returnNextItem($el.attr('data-size'));
        $el.attr('data-size',cs);
        if(cs!="init"){
            $el.attr('class',c_size[cs]);
        }else if(cs=="init"){
            $el.attr('class',$el.attr('data-initial-class'));
        }
        resizeWindow();
    }
</script>

<?php
$cs = Yii::app()->getClientScript();
$cs->registerScript('loadOrderMtdGraph', 'function loadOrderMtdGraph(month){
        jQuery.ajax({
            "data" : "month="+month,
            "type"  : "post",
            "url": "' . Yii::app()->createUrl('dashboard/loadOrderMtdGraph') . '",
            "success":function(data){
                $("#div_graphorder_detailed_list").html(data);
            },
           
       });
};', CClientScript::POS_HEAD);
?>
 <style>
#order_myChart_4 .axisX text{
   writing-mode:tb-rl;
    white-space:pre-wrap;
 text-anchor: unset !important;
 font-weight:200;
    display:block;
    bottom:0;
    width:20px;
    height:20px;		
	}
.demo-xchart {
    height: 280px;
    width: 100%;
}	
	
#order_myChart_4	svg {
    height: 444px  !important;
    width: 100%;
}
</style>







