<?php
ob_start();
require("includes/check_auth_user.php");
require("includes/dbconnect.php");
include('includes/function.php');

$formname = 'Dashboard For Challan';

$admin = $_SESSION["admin_" . $dbname];
$zdb = $_SESSION["zdbyear_" . $dbname];
mysqli_select_db($conn, $zdb);
include("includes/linkshead.php");
$weeklyfrmdt = date('Y-m-d', strtotime('monday last week'));
$weeklytodt = date('Y-m-d', strtotime('sunday last week'));
//$weeklytodt = strtotime("next sunday");
?>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>

</head>
<body style="background: white;">
    <div class="container-fluid">

        <div class="row">

            <div class='col-lg-3 col-md-3 col-sm-12 col-xs-12 pad'>
            </div>
            <div class='col-lg-2 col-md-2 col-sm-12 col-xs-12 pad'>
                <select name="month" class="form-control select2 month" id="month">
                    <option value=""></option>
                    <option value="01" id="1">January</option>
                    <option value="02" id="2">February</option>
                    <option value="03" id="3">March</option>
                    <option value="04" id="4">April</option>
                    <option value="05" id="5">May</option>
                    <option value="06" id="6">June</option>
                    <option value="07" id="7">July</option>
                    <option value="08" id="8">August</option>
                    <option value="09" id="9">September</option>
                    <option value="10" id="10">October</option>
                    <option value="11" id="11">November</option>
                    <option value="12" id="12">December</option>
                </select>
            </div>

            <div class='col-lg-1 col-md-1 col-sm-12 col-xs-12 pad text-right'>
                <i class="fa fa-caret-left weeklyfrmdtbtn" aria-hidden="true" style="color: #1B1B1B;font-size: 35px;"></i>
            </div>
            <div class='col-lg-1 col-md-1 col-sm-12 col-xs-12 pad'  style="width: 10%;">
                <input type='date' class='form-control weeklyfrmdt' name='weeklyfrmdt' id="weeklyfrmdt" value='<?php echo $weeklyfrmdt ?>'>
            </div>
            <div class='col-lg-2 col-md-2 col-sm-12 col-xs-12 pad'  style="width: 10%;">
                <input type='date' class='form-control weeklytodt weeklyfrmdtbtn' name='weeklytodt' id="weeklytodt" value='<?php echo $weeklytodt; ?>' readonly>
            </div>
            <div class='col-lg-1 col-md-1 col-sm-12 col-xs-12 pad' >
                <a><i class="fa fa-caret-right weeklytodtbtn" aria-hidden="true"  style="color: #1B1B1B;font-size: 35px;"></i></a>
            </div>
        </div>


        <div class="row">
            <div class="col-lg-2 col-md-2 col-sm-12 col-xs-12"></div>
            <div class="col-lg-8 col-md-8 col-sm-12 col-xs-12">
                <div class="chart-container">
                    <canvas id="myChart2" style="position: relative; height:120vw;"></canvas>
                </div>
            </div>
        </div>
    </div>


    <script>
        $(document).ready(function () {
            $("body").on("click", ".weeklyfrmdtbtn", PrevWeekChart);
            $("body").on("click", ".weeklytodtbtn", NextWeekChart);
            $("body").on("blur", ".weeklyfrmdt", WeeklyTopCustChartDateFunc);
            $("body").on("change", ".month", MonthChartFunc);


            function MonthChartFunc() {
                TopCustomerChart('month');
            }

            function PrevWeekChart() {
                PrevNextWeekChart('P');
            }

            function NextWeekChart() {
                PrevNextWeekChart('N');
            }


            function WeeklyTopCustChartDateFunc() {
                var wfrmdate = new Date($(".weeklyfrmdt").val());
                if (wfrmdate.getDay() !== 1) {
                    alert("Date is not Monday");
                    var curr = new Date();
                    var firstday = new Date(curr.setDate(curr.getDate() - curr.getDay()));
                    var formattedDate = firstday.getFullYear() + "-" + (firstday.getMonth() + 1) + "-" + firstday.getDate();
                    $(".weeklyfrmdt").val(formattedDate);
                } else {
                    var dt = wfrmdate;
                    var ndt1 = dt.setDate(dt.getDate() + 6);
                    var ndt = new Date(ndt1);

                    var dd = String(ndt.getDate()).padStart(2, '0');
                    var mm = String(ndt.getMonth() + 1).padStart(2, '0'); //January is 0!
                    var yyyy = ndt.getFullYear();

                    var today = yyyy + '-' + mm + '-' + dd;

                    $(".weeklytodt").val(today);
                    TopCustomerChart();
                }
            }

            function PrevNextWeekChart(para) {
                var dt = new Date($(".weeklyfrmdt").val());
                var mpara = para;
                if (mpara == 'P')
                    var ndt1 = dt.setDate(dt.getDate() - 7);
                else {
                    var ndt1 = dt.setDate(dt.getDate() + 7);
                }
                var ndt = new Date(ndt1);

                var dd = String(ndt.getDate()).padStart(2, '0');
                var mm = String(ndt.getMonth() + 1).padStart(2, '0'); //January is 0!
                var yyyy = ndt.getFullYear();

                var today = yyyy + '-' + mm + '-' + dd;

                $(".weeklyfrmdt").val(today);
                WeeklyTopCustChartDateFunc();
            }


            TopCustomerChart();
            function TopCustomerChart(para) {
                $('#myChart2').replaceWith('<canvas id="myChart2" style="position: relative; height:120vw;"></canvas>');
                var ctx2 = document.getElementById('myChart2').getContext('2d');

                var mpara = para, lbltext;

                if (mpara == 'month') {
                    if ($('.month').val() !== '') {
                        lbltext = 'Top Performing Customers - Monthly';
                    } else {
                        lbltext = 'Top Performing Customers - Weekly';
                    }
                } else {
                    lbltext = 'Weekly Chart';
                    $(".month").val('').trigger('change');
                }
                var month = $('.month').val();

                var weeklyfrmdt = $(".weeklyfrmdt").val();
                var weeklytodt = $(".weeklytodt").val();

                $.ajax({
                    type: 'GET',
                    dataType: 'json',
                    url: "getmistopcust.php",
                    data: {weeklyfrmdt: weeklyfrmdt, weeklytodt: weeklytodt, month: month},
                    success: function (response) {

                        var mcustcode = [], mcount = [];
                        $.each(response, function () {
                            mcustcode.push(this.custcode);
                            mcount.push(this.count);
                        });

                        var data = {
                            labels: [mcustcode[0], mcustcode[1], mcustcode[2], mcustcode[3], mcustcode[4]],
                            datasets: [{
                                    label: '',
                                    data: [mcount[0], mcount[1], mcount[2], mcount[3], mcount[4]],
                                    backgroundColor: [
//                                        'rgb(255,255,255)',
                                        'rgb(66,133,244)',
                                        'rgb(234,67,53)',
                                        'rgb(251,188,5)',
                                        'rgb(52,168,83)',
                                        'rgb(181,181,181)'
                                    ],
                                    borderColor: [
//                                        'rgba(255,255,255, 1)',
                                        'rgba(66,133,244,1)',
                                        'rgba(234,67,53,1)',
                                        'rgba(251,188,5,1)',
                                        'rgba(52,168,83,1)',
                                        'rgba(181,181,181,1)'
                                    ],
                                    borderWidth: 1
                                }]
                        };

                        var chartOptions = {
                            responsive: true,
                            legend: {
                                position: "top",
                                backgroundColor: 'rgb(255,255,255)'
                            },
                            title: {
                                display: true,
                                text: lbltext,
                                fontSize: 25,
                            },
                            scales: {
                                yAxes: [{
                                        ticks: {
                                            beginAtZero: true
                                        },
                                        scaleLabel: {
                                            display: true,
                                            labelString: 'Customers',
                                            fontSize: 18
                                        }
                                    }],
                                xAxes: [{
                                        scaleLabel: {
                                            display: true,
                                            labelString: 'No. of Challans',
                                            fontSize: 18
                                        }
                                    }]
                            },
                            onClick: function (e, element) {
                            }
                        }
                        var DailyBar = new Chart(ctx2, {
                            type: "horizontalBar",
                            data: data,
                            options: chartOptions
                        });


                        document.getElementById("myChart2").onclick = function (evt, element) {
                            var activePoints = DailyBar.getElementsAtEvent(evt);
                            var firstPoint = activePoints[0];
                            var label = DailyBar.data.labels[0];
                            var value = DailyBar.data.datasets[0].data[0];
                            var location = 'mistopcustomer_rep.php?&count=' + value + '&party=' + label +
                                    '&fdate=' + weeklyfrmdt + '&tdate=' + weeklytodt + '&month=' + month + '&cancel=no';
                            window.open(location, '_blank');
//                            alert(label + ": " + value + ':' + bartitle);
                        };

//                        DailyBar.update();
                    },
                    error: function (request, textStatus, errorThrown) {
                    }
                });
            }
        });
    </script>
    <?php include("includes/linksfoot.php"); ?>
</body>
</html>
