<?php
$total_value = 0;
$from_original_date = $fromdate;
$to_original_date = $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));
$invextra_cndt = '';
/*if (Yii::app()->user->authorised_user != 1 && User::isSalesman() == 'Y') {
    $invextra_cndt = ' AND lead_owner_id=' . Yii::app()->user->id;
}*/

/*$SQL = "SELECT COUNT(transaction_id) AS y_value,lead_owner_id,username AS x_value,IFNULL(SUM(invoice_amount - credit_note_amount),0) AS total_amount FROM `view_invoice_creditnote_details` WHERE ((transaction_date BETWEEN '" . $from_date . "' AND '" . $end_date . "') OR transaction_date IS NULL) " . $invextra_cndt . " GROUP BY lead_owner_id ORDER BY total_amount DESC";

$graph_data_quantity = Yii::app()->db->createCommand($SQL)->queryAll();*/

     $graph_data_quantity = Yii::app()->db->createCommand('SELECT salesperson_name AS x_value,sum(inv.grand_total*inv.exchange_rate) AS y_value FROM {{invoice}} AS inv 
  WHERE inv.invoice_date BETWEEN "'.$from_date.'" AND "'.$end_date.'"  '.$invextra_cndt.' GROUP BY salesperson_id')->queryAll(); 
//print_r($graph_data_quantity);
$invoice_plot = '[';
foreach ($graph_data_quantity as $eachdata) {
    $color = substr(md5(rand()), 0, 6);
    $invoice_plot .= '{label:"' . $eachdata['x_value'] . '", value:"' . round($eachdata['y_value'], 0) . '", color: "#' . $color . '"},';
}
$invoice_plot .= ']';

$currentYear = date("Y");
$currentmonth = date("m");
if ($year == $currentYear) {
    $month_1 = $currentmonth;
}
$invoice_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 {{invoice}} AS inv  WHERE YEAR(invoice_date) = "' . $year . '" AND MONTH(invoice_date) = "' . $k . '"  ' . $invextra_cndt . ' ')->queryAll();

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

//echo '<pre>';
//print_r($invoice_plot_3);

//Bar Chart
$fromdate_1 = str_replace('/', '-', $from_original_date);
;
$month = date("m", strtotime($fromdate_1));
$todate_1 = str_replace('/', '-', $to_original_date);
$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');
}
$inv_value = explode('-', $selected);
$inv_year = $inv_value[0];
$inv_month = $inv_value[1];
/* $model_sales_total_invoice = Invoice::model()->find(array('select'=>'sum(grand_total*exchange_rate) as grand_total','condition' =>'YEAR(invoice_date)="'.$inv_year.'" AND MONTH(invoice_date)="'.$inv_month.'"'));
  $total_sale_amount=$model_sales_total_invoice->grand_total;
  $model_lead_owner = User::model()->findAll(array('condition' =>'is_lead_owner="Y"'));
  $chartData = '';
  foreach ($model_lead_owner as $key => $value) {
  $model_sales_invoice = Invoice::model()->find(array('select'=>'sum(grand_total*exchange_rate) as grand_total','condition' =>'YEAR(invoice_date)="'.$inv_year.'" AND MONTH(invoice_date)="'.$inv_month.'" AND lead_owner_id="'.$value->id.'"'));
  $sale_invoice_amount=$model_sales_invoice->grand_total;
  $total_inv_amount=$sale_invoice_amount;
  if($total_inv_amount>0){
  $percentage_sales= number_format(($sale_invoice_amount/$total_sale_amount)*100,2);
  $chartData.='{"lead_owner": "'.$value->Fullname.'","total_amount": "'.$sale_invoice_amount.'","percentage_amount": "'.$percentage_sales.'"},';
  }
  } */

$model_sales_total_invoice = Invoice::model()->find(array('select' => 'sum(grand_total*exchange_rate) as grand_total', 'condition' => 'YEAR(invoice_date)="' . $inv_year . '" AND MONTH(invoice_date)="' . $inv_month . '"'));

//$model_total_credit_note = Creditnote::model()->find(array('select' => 'IFNULL(SUM(credited_amount*exchange_rate),0) as credited_amount', 'condition' => 'YEAR(credited_date)="' . $inv_year . '" AND MONTH(credited_date)="' . $inv_month . '"'));
//$total_sale_amount = ($model_sales_total_invoice->grand_total - $model_total_credit_note->credited_amount);
$total_sale_amount = ($model_sales_total_invoice->grand_total);
$total_sales_only = $model_sales_total_invoice->grand_total;
//$total_sales_return = $model_total_credit_note->credited_amount;
$model_lead_owner = Yii::app()->db->createCommand('SELECT salesperson_name,salesperson_id FROM {{invoice}} AS inv  GROUP BY salesperson_id')->queryAll();

$chartData = '';
$chartSalesData = "";
$chartSalesReturnData = "";
foreach ($model_lead_owner as $key => $value) {
    $model_sales_invoice = Invoice::model()->find(array('select' => 'sum(grand_total*exchange_rate) as grand_total', 'condition' => 'YEAR(invoice_date)="' . $inv_year . '" AND MONTH(invoice_date)="' . $inv_month . '" AND salesperson_id="' . $value['salesperson_id'] . '"'));
    //echo 'YEAR(invoice_date)="' . $inv_year . '" AND MONTH(invoice_date)="' . $inv_month . '" AND salesperson_id="' . $value['salesperson_id'] . '"';
    //echo '<pre>';
    //print_r($model_sales_invoice);
    $sale_invoice_amount = ($model_sales_invoice->grand_total);
    $total_inv_amount = $sale_invoice_amount;
    
    if($total_sales_only>0){
    $percentage_sales = number_format(($model_sales_invoice->grand_total / $total_sales_only) * 100, 2);
    }else{
    $percentage_sales = 0.00;
    }
    $percentage_sales_return_amount = 0.00;
    $chartData .= '{"lead_owner": "' . $value['salesperson_name'] . '","total_amount": "' . $sale_invoice_amount . '","percentage_amount": "' . $percentage_sales . '"},';
    $chartSalesData .= '{"lead_owner": "' . $value['salesperson_name'] . '","total_amount": "' .  $model_sales_invoice->grand_total . '","percentage_amount": "' . $percentage_sales . '"},';
    $chartSalesReturnData .= '{"lead_owner": "' . $value['salesperson_name'] . '","total_amount": "' .  $model_credit_note->credited_amount . '","percentage_sales_return_amount": "' . $percentage_sales_return_amount . '"},';
    //}
}
?>
<div class="clearfix"></div>
<br>
<div class="clearfix">
    <input type="hidden" id="invoice_datefrom" name="invoice_datefrom" value="<?php echo $from_original_date; ?>"/>
    <input type="hidden" id="invoice_dateto" name="invoice_dateto" value="<?php echo $to_original_date; ?>"/>
    <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">
                        <canvas id="invice_myChart" width="400" height="400" onclick="loadPopupModal('dashboard/invoice_graphdetails&type=1&from_date=<?php echo $from_original_date; ?>&end_date=<?php echo $to_original_date ?>', 'Invoice- Invoice Owner', 'lg');"></canvas>
                </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">
                        <canvas id="invice_myChart_3" width="400" height="400" onclick="loadPopupModal('dashboard/invoice_graphdetails&type=4&from_date=<?php echo $from_original_date; ?>&end_date=<?php echo $to_original_date ?>', 'Invoice- <?php echo $end_year; ?>', 'lg');"></canvas>
                </div>
            </div>
        </section>
    </div>
<?php //if (Yii::app()->user->authorised_user == 1 || User::isSalesman() != 'Y') { ?>
        <div class="has-animate-child" id="div_graph_detailed_list">
            <div class="col-lg-12" id="pieChartParent_4">

<!--                <section class="panel" >
                    <header class="panel-heading">
                        Invoices MTD <?php
                        echo CHtml::dropDownList('invoice_month', '', Dashboard::getMonths1($end_year, $month, $month_1), array(
                            'options' => array($selected => array('selected' => true)),
                            "onChange" => "loadInvoicesMtdGraph(this.value);"));
                        ?> - <?php echo Yii::app()->numberFormatter->formatCurrency($total_sale_amount, ""); ?>
                    </header>
                    <div class="panel-body">
                        <div id="invoice_mtd_graph"></div>	
                    </div>
                </section>-->
                <!--sales graph-->
                <section class="panel">
                    <header class="panel-heading">
                        Sales  MTD <?php
                        echo CHtml::dropDownList('invoice_month', '', Dashboard::getMonths1($end_year, $month, $month_1), array(
                            'options' => array($selected => array('selected' => true)),
                            "onChange" => "loadInvoicesMtdGraph(this.value);"));
                        ?> - <?php echo Yii::app()->numberFormatter->formatCurrency($total_sales_only, ""); ?>
                    </header>
                    <div class="panel-body">
                        <div id="sales_mtd_graph"></div>	
                    </div>
                </section>
                 <!--sales return  graph-->
                 <section class="panel" style="display:none;">
                    <header class="panel-heading">
                        Sales  Return MTD <?php
                        echo CHtml::dropDownList('invoice_month', '', Dashboard::getMonths1($end_year, $month, $month_1), array(
                            'options' => array($selected => array('selected' => true)),
                            "onChange" => "loadInvoicesMtdGraph(this.value);"));
                        ?> - <?php echo Yii::app()->numberFormatter->formatCurrency($total_sales_return, ""); ?>
                    </header>
                    <div class="panel-body">
                        <div id="sales_return_mtd_graph"></div>	
                    </div>
                </section>
            </div>
        </div>
    <?php //} ?>
</div>

<script type="text/javascript">

//Mileage Chart
    var chart_mileage = AmCharts.makeChart("invoice_mtd_graph", {
        "theme": "light",
        "type": "serial",
        "legend": {
            "horizontalGap": 10,
            "maxColumns": 1,
            "position": "right",
            "useGraphSettings": true,
            "markerSize": 10
        },
        "dataProvider": [<?php echo $chartData; ?>],
        "valueAxes": [{
                "stackType": "3d",
                "unit": " AED",
                "position": "left",
                "title": "Total in AED",
            }],
        "startDuration": 1,
        "graphs": [{
                "balloonText": "[[lead_owner]] - [[total_amount]]",
                "fillAlphas": 0.8,
                "lineAlpha": 0.3,
                "title": "Sales",
                "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,
    });
    
    // sales
         var chart_mileage = AmCharts.makeChart("sales_mtd_graph", {
        "theme": "light",
        "type": "serial",
        "legend": {
            "horizontalGap": 10,
            "maxColumns": 1,
            "position": "right",
            "useGraphSettings": true,
            "markerSize": 10
        },
        "dataProvider": [<?php echo $chartSalesData; ?>],
        "valueAxes": [{
                "stackType": "3d",
                "unit": " AED",
                "position": "left",
                "title": "Total in AED",
            }],
        "startDuration": 1,
        "graphs": [{
                "balloonText": "[[lead_owner]] - [[total_amount]] ([[percentage_amount]]%)",
                "fillAlphas": 0.8,
                "lineAlpha": 0.3,
                "title": "Sales",
                "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,
    });
    /// end 
    
        // sales
         var chart_mileage = AmCharts.makeChart("sales_return_mtd_graph", {
        "theme": "light",
        "type": "serial",
        "legend": {
            "horizontalGap": 10,
            "maxColumns": 1,
            "position": "right",
            "useGraphSettings": true,
            "markerSize": 10
        },
        "dataProvider": [<?php echo $chartSalesReturnData; ?>],
        "valueAxes": [{
                "stackType": "3d",
                "unit": " AED",
                "position": "left",
                "title": "Total in AED",
            }],
        "startDuration": 1,
        "graphs": [{
                "balloonText": "[[lead_owner]] - [[total_amount]] ([[percentage_sales_return_amount]]%)",
                "fillAlphas": 0.8,
                "lineAlpha": 0.3,
                "title": "Sales Return",
                "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,
    });
    /// end 
    
    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>
    #invoice_mtd_graph, #sales_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 $invoice_plot; ?>;
        var order_data4 =<?php echo $invoice_plot_3; ?>;
        //var order_data2 =<?php echo $invoice_plot_1; ?>;
        //var order_data3 =<?php echo $invoice_plot_2; ?>;
        
        //alert(order_data1);
        
//var order_data5=<?php echo $plot; ?>;
        var canvas1 = document.getElementById("invice_myChart");
        Chart.defaults.global.responsive = true;
        var ctx = canvas1.getContext("2d");
        var pieChart = new Chart(ctx).Pie(order_data1);
        

       /* var canvas_1 = document.getElementById("invice_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("invice_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("invice_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, '#invice_myChart_4',{
         axisPaddingTop: 5,
         }),
         rotateTimer,
         toggles = d3.selectAll('.multi button'),
         t = 3500;    */

    });
    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("loadmonthinvoice", "function loadmonthinvoice() {
    var month=$('#invoice_month').val();
    loadPopupModal('dashboard/invoice_graphdetails&type=5&month='+month,'Invoices MTD','lg');
};", CClientScript::POS_HEAD);

$cs->registerScript("loadleadinvoice", "function loadleadinvoice() {
    var fromdate  = $('#invoice_datefrom').val();
    var todate  = $('#invoice_dateto').val();
    loadPopupModal('dashboard/invoice_graphdetails&type=1&fromdate='+fromdate+'&todate='+todate,'Invoice- Invoice Owner','lg');
};", CClientScript::POS_HEAD);

//$cs->registerScript('loadInvoicesMtdGraph', 'function loadInvoicesMtdGraph(month){
//        jQuery.ajax({
//            "dataType":"json",
//            "data" : "month="+month,
//            "type"  : "post",
//            "url": "' . Yii::app()->createUrl('dashboard/loadInvoicesMtdGraph') . '",
//            "success":function(data){
//                    var myChart = new xChart("bar", data.plot,"#invice_myChart_4");
//            },
//           
//       });
//};', CClientScript::POS_HEAD);

$cs->registerScript('loadInvoicesMtdGraph', 'function loadInvoicesMtdGraph(month){
        jQuery.ajax({
            "data" : "month="+month,
            "type"  : "post",
            "url": "' . Yii::app()->createUrl('dashboard/loadInvoicesMtdGraph') . '",
            "success":function(data){
                $("#div_graph_detailed_list").html(data);
            },
           
       });
};', CClientScript::POS_HEAD);
?>
<style>
    #invice_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%;
    }	

    #invice_myChart_4	svg {
        height: 444px  !important;
        width: 100%;
    }
</style>






