<?php
include "pin/header.php";
include "pin/sidenav.php";

if (isset($_GET['which_month'])) {
    $firstDayLast = date('Y-m-01', strtotime(trim($_GET['which_month'])));
    $lastDayLast = date('Y-m-t', strtotime(trim($_GET['which_month'])));
} else {
    $firstDayLast =  date('Y-m-d', strtotime('first day of last month'));
    $lastDayLast =  date('Y-m-d', strtotime('last day of last month'));
}

// echo $firstDayLast,$lastDayLast;

?>



<!-- ============================================================== -->
<!-- Start Page Content here -->
<!-- ============================================================== -->

<div class="content-page" style="position:relative;">

    <style>
        #loader-wrapper {

            width: 100%;
            height: 100vh;
            background: #fff;
            position: absolute;
            top: 0;
            z-index: 99;
            display: none;
        }

        .loader {
            /* border: 1px solid white; */
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
        }

        .loading-container {
            display: flex;
            justify-content: center;
            align-items: center;
            position: relative;
        }

        .spinner {
            height: 8rem;
            width: 8rem;
            border-width: 5px;
            border-style: solid;
            /* border-color: #c5c5c5; */
            border-color: #000;
            /* border-left-color: #00000070; */
            border-left-color: #fff;
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
            animation: spin infinite 1.5s linear;
        }

        .spinner-text {
            position: absolute;
            font-size: 14px;
            color: #000;
            top: 50%;
            transform: translateY(-50%);
            font-weight: 600;
            letter-spacing: 1.5px;
            text-transform: uppercase;
        }

        .load-text {
            color: #000;
            font-size: 14pt;
            margin-top: 1rem;
        }

        .no-scroll {
            overflow: hidden;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }
    </style>
    <div id="loader-wrapper">
        <div class="loader">
            <div class="loading-container">
                <p class="spinner-text">
                    loading...
                </p>
                <div class="spinner"></div>
            </div>
            <p class="load-text">Please wait ...</p>
        </div>
    </div>

    <div class="content">
        <div class="container-fluid">

            <div class="row page-title align-items-center">
                <div class="col-sm-4 col-xl-6">
                    <h4 class="mb-1 mt-0">Dashboard `<span id="monthName"></span>`</h4>
                </div>
                <div class="col-sm-8 col-xl-6">
                    <div class="form-inline float-sm-right mt-3 mt-sm-0">
                        <div class="form-group mb-sm-0 mr-2">
                            <!-- <input type="month" class="form-control" id="statusDate" onchange="loadStatusCount();" value="2023-03"> -->
                            <input type="month" class="form-control" id="statusDate" onchange="loadStatusCount();" value="<?php echo date('Y-m', strtotime($firstDayLast)); ?>">
                        </div>
                    </div>
                </div>
            </div>

            <!-- content -->
            <div class="row">
                <div class="col-md-6 col-xl-4">
                    <div class="card h-100">
                        <div class="card-body p-0">
                            <div class="media p-3 pb-2 border-bottom">
                                <div class="media-body">
                                    <span class="text-muted text-uppercase font-size-12 font-weight-bold">Total New Joining</span>
                                    <h2 class="mb-0" id="newJoining"></h2>
                                </div>
                            </div>
                            <div>
                                <div id="joining-pi-chart" class="apex-charts"></div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-md-6 col-xl-4">
                    <div class="card h-100">
                        <div class="card-body p-0">
                            <div class="media p-3 pb-2 border-bottom">
                                <div class="media-body">
                                    <span class="text-muted text-uppercase font-size-12 font-weight-bold">Total Resignation</span>
                                    <h2 class="mb-0" id="resignation"></h2>
                                </div>
                            </div>
                            <div>
                                <div id="resignation-pi-chart" class="apex-charts"></div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-md-6 col-xl-4">
                    <div class="card h-100">
                        <div class="card-body p-0">
                            <div class="media p-3 pb-2 border-bottom">
                                <div class="media-body">
                                    <span class="text-muted text-uppercase font-size-12 font-weight-bold">Total Termination</span>
                                    <h2 class="mb-0" id="termination"></h2>
                                </div>
                            </div>
                            <div>
                                <div id="termination-pi-chart" class="apex-charts"></div>
                            </div>
                        </div>
                    </div>
                </div>

            </div>

            <!-- stats + charts -->

            <div class="row justify-content-end mt-5">
                <div class="col-sm-8">
                    <div class="form-inline float-sm-right mt-3 mt-sm-0">
                        <div class="form-group mb-sm-0 mr-2">
                            <input type="month" class="form-control" id="yearMonth1" value="<?php echo date('Y-01'); ?>">
                        </div>
                        <div class="form-group mb-sm-0 mr-2">
                            <input type="month" class="form-control" id="yearMonth2" value="<?php echo date('Y-12'); ?>">
                        </div>
                        <div class="btn-group">
                            <button type="button" class="btn btn-primary" onclick="loadCharts();">
                                Load<i class="uil uil-down-arrow ml-1"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-12">
                    <h4>Total Expenses</h4>
                </div>
                <div class="col-lg-6">
                    <div class="card h-100">
                        <div class="card-body">
                            <h5 class="card-title mb-0 header-title">Total Expenses</h5>
                            <div id="total-expenses-linear-chart" class="apex-charts mt-3"></div>
                        </div>
                    </div>
                </div>
                <div class="col-lg-6">
                    <div class="card h-100">
                        <div class="card-body">
                            <h5 class="card-title mb-0 header-title">Total Expenses</h5>
                            <div id="total-expenses-pi-chart" class="apex-charts mt-3"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-12">
                    <h4>Payable Expenses</h4>
                </div>
                <div class="col-lg-6">
                    <div class="card h-100">
                        <div class="card-body">
                            <h5 class="card-title mb-0 header-title">Payable Expenses</h5>
                            <div id="payable-expenses-linear-chart" class="apex-charts mt-3"></div>
                        </div>
                    </div>
                </div>
                <div class="col-lg-6">
                    <div class="card h-100">
                        <div class="card-body">
                            <h5 class="card-title mb-0 header-title">Payable Expenses</h5>
                            <div id="payable-expenses-pi-chart" class="apex-charts mt-3"></div>
                        </div>
                    </div>
                </div>


            </div>
            <!-- row -->


        </div>
    </div> <!-- content -->


</div>

<!-- ============================================================== -->
<!-- End Page content -->
<!-- ============================================================== -->



<?php
include "pin/footer.php";
?>

<script>
    // Declare a global variable to hold the chart instance
    var joiningPiChart = null;
    var resignationPiChart = null;
    var terminationPiChart = null;
    async function loadStatusCount() {
        let val = $("#statusDate").val();

        let piJoiningSeriesLabels = [];
        let piJoiningSeriesData = [];

        let piResSeriesLabels = [];
        let piResSeriesData = [];

        let piTerSeriesLabels = [];
        let piTerSeriesData = [];

        await $.ajax({
            url: "fun/function",
            type: "POST",
            data: {
                statusCountDate: val
            },
            success: function(result) {
                // console.log(result);
                let data = JSON.parse(result);
                // console.log(data);

                $("#monthName").text(data.monthName);

                if (data.newJoining[0] == 0) {
                    $("#newJoining").parent().parent().parent().parent().parent().hide();
                } else {
                    $("#newJoining").parent().parent().parent().parent().parent().show();
                    $("#newJoining").text(data.newJoining[0]);
                }

                if (data.resignation[0] == 0) {
                    $("#resignation").parent().parent().parent().parent().parent().hide();
                } else {
                    $("#resignation").parent().parent().parent().parent().parent().show();
                    $("#resignation").text(data.resignation[0]);
                }

                if (data.termination[0] == 0) {
                    $("#termination").parent().parent().parent().parent().parent().hide();
                } else {
                    $("#termination").parent().parent().parent().parent().parent().show();
                    $("#termination").text(data.termination[0]);
                }

                for (const [department, count] of Object.entries(data.newJoining[1])) {
                    piJoiningSeriesLabels.push(department);
                    piJoiningSeriesData.push(parseInt(count));
                }
                for (const [department, count] of Object.entries(data.resignation[1])) {
                    piResSeriesLabels.push(department);
                    piResSeriesData.push(parseInt(count));
                }
                for (const [department, count] of Object.entries(data.termination[1])) {
                    piTerSeriesLabels.push(department);
                    piTerSeriesData.push(parseInt(count));
                }

            }
        });

        var options = {
            series: piJoiningSeriesData,
            chart: {
                type: 'pie',
            },
            labels: piJoiningSeriesLabels,
            noData: {
                text: "Empty",
                style: {
                    fontSize: '24px',
                }
            }
        };
        if (joiningPiChart) {
            joiningPiChart.updateOptions({
                series: piJoiningSeriesData,
                labels: piJoiningSeriesLabels
            });
        } else {
            joiningPiChart = new ApexCharts(document.querySelector("#joining-pi-chart"), options);
            joiningPiChart.render();
        }

        var options = {
            series: piResSeriesData,
            chart: {
                type: 'pie',
            },
            labels: piResSeriesLabels,
            noData: {
                text: "Empty",
                style: {
                    fontSize: '24px',
                }
            }
        };
        if (resignationPiChart) {
            resignationPiChart.updateOptions({
                series: piResSeriesData,
                labels: piResSeriesLabels
            });
        } else {
            resignationPiChart = new ApexCharts(document.querySelector("#resignation-pi-chart"), options);
            resignationPiChart.render();
        }

        var options = {
            series: piTerSeriesData,
            chart: {
                type: 'pie',
            },
            labels: piTerSeriesLabels,
            noData: {
                text: "Empty",
                style: {
                    fontSize: '24px',
                }
            }
        };
        if (terminationPiChart) {
            terminationPiChart.updateOptions({
                series: piTerSeriesData,
                labels: piTerSeriesLabels
            });
        } else {
            terminationPiChart = new ApexCharts(document.querySelector("#termination-pi-chart"), options);
            terminationPiChart.render();
        }

    }
    // loadStatusCount();

    // Declare a global variable to hold the chart instance
    var linearPayableChart = null;
    var piPayableChart = null;
    var piExpensesChart = null;
    var linearExpensesChart = null;
    async function loadCharts() {
        $(window).scrollTop(0);
        $("#loader-wrapper").show();
        $('body').addClass('no-scroll');

        let date1 = $("#yearMonth1").val();
        let date2 = $("#yearMonth2").val();

        let linearPaySeriesCat = [];
        let linearPaySeriesData = [];

        let linearExSeriesCat = [];
        let linearExSeriesData = [];

        let piPaySeriesLabels = [];
        let piPaySeriesData = [];

        let piExSeriesLabels = [];
        let piExSeriesData = [];

        await $.ajax({
            url: "fun/function",
            type: "POST",
            data: {
                chartsStartDate: date1,
                chartsEndDate: date2,
            },
            success: function(result) {
                // console.log(result);
                let data = JSON.parse(result);
                // console.log(data);

                // linear payable chart
                for (const [month, amount] of Object.entries(data.linearPayable)) {
                    linearPaySeriesCat.push(month);
                    linearPaySeriesData.push(parseInt(amount));
                }

                // linear Expenses chart
                for (const [month, amount] of Object.entries(data.linearExpenses)) {
                    linearExSeriesCat.push(month);
                    linearExSeriesData.push(parseInt(amount));
                }

                // pi payable chart
                for (const [department, amount] of Object.entries(data.piPayable)) {
                    piPaySeriesLabels.push(department);
                    piPaySeriesData.push(parseInt(amount));
                }

                // pi Expenses chart
                for (const [department, amount] of Object.entries(data.piExpenses)) {
                    piExSeriesLabels.push(department);
                    piExSeriesData.push(parseInt(amount));
                }

            }
        });


        var options = {
            series: [{
                name: 'Pay this Month',
                data: linearExSeriesData
            }],
            chart: {
                type: 'area'
            },
            dataLabels: {
                enabled: false
            },
            stroke: {
                curve: 'smooth'
            },
            xaxis: {
                categories: linearExSeriesCat
            },
            noData: {
                text: "Empty",
                style: {
                    fontSize: '24px',
                }
            }
        };
        if (linearExpensesChart) {
            linearExpensesChart.updateSeries([{
                name: 'Total Expenses',
                data: linearExSeriesData
            }]);
            linearExpensesChart.updateOptions({
                xaxis: {
                    categories: linearExSeriesCat
                }
            });
        } else {
            linearExpensesChart = new ApexCharts(document.querySelector("#total-expenses-linear-chart"), options);
            linearExpensesChart.render();
        }

        var options = {
            series: piExSeriesData,
            chart: {
                type: 'pie',
            },
            labels: piExSeriesLabels,
            noData: {
                text: "Empty",
                style: {
                    fontSize: '24px',
                }
            }
        };
        if (piExpensesChart) {
            piExpensesChart.updateOptions({
                series: piExSeriesData,
                labels: piExSeriesLabels
            });
        } else {
            piExpensesChart = new ApexCharts(document.querySelector("#total-expenses-pi-chart"), options);
            piExpensesChart.render();
        }

        var options = {
            series: [{
                name: 'Pay this Month',
                data: linearPaySeriesData
            }],
            chart: {
                type: 'area'
            },
            dataLabels: {
                enabled: false
            },
            stroke: {
                curve: 'smooth'
            },
            xaxis: {
                categories: linearPaySeriesCat
            },
            noData: {
                text: "Empty",
                style: {
                    fontSize: '24px',
                }
            }
        };
        if (linearPayableChart) {
            linearPayableChart.updateSeries([{
                name: 'Total Expenses',
                data: linearPaySeriesData
            }]);
            linearPayableChart.updateOptions({
                xaxis: {
                    categories: linearPaySeriesCat
                }
            });
        } else {
            linearPayableChart = new ApexCharts(document.querySelector("#payable-expenses-linear-chart"), options);
            linearPayableChart.render();
        }

        var options = {
            series: piPaySeriesData,
            chart: {
                type: 'pie',
            },
            labels: piPaySeriesLabels,
            noData: {
                text: "Empty",
                style: {
                    fontSize: '24px',
                }
            }
        };
        if (piPayableChart) {
            piPayableChart.updateOptions({
                series: piPaySeriesData,
                labels: piPaySeriesLabels
            });
        } else {
            piPayableChart = new ApexCharts(document.querySelector("#payable-expenses-pi-chart"), options);
            piPayableChart.render();
        }

        $("#loader-wrapper").fadeOut();
        $('body').removeClass('no-scroll');
    }
    // loadCharts();
</script>