@extends('admin.layout.page-app')
@section('page_title', __('label.analytics_reports'))
@section('tab_title', __('label.analytics_reports'))

@section('content')
    @include('admin.layout.sidebar')

    <!-- Select2 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" />

    <div class="right-content">
        @include('admin.layout.header')

        <div class="body-content">
            <!-- mobile title -->
            <h1 class="page-title-sm"> {{__('label.analytics_reports')}} </h1>

            <div class="border-bottom row mb-3">
                <div class="col-sm-8">
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="{{ route('admin.dashboard') }}">{{__('label.dashboard')}}</a></li>
                        <li class="breadcrumb-item active" aria-current="page">{{__('label.analytics_reports')}}</li>
                    </ol>
                </div>
                <div class="col-sm-4">
                    <div class="form-group">
                        <select name="department_id" class="form-control" id="department_id">
                            <option value="0">{{__('label.all_department')}}</option>
                            @for ($i = 0; $i < count($department); $i++) 
                            <option value="{{ $department[$i]['id'] }}">
                                {{ $department[$i]['name'] }}
                            </option>
                            @endfor
                        </select>
                    </div>
                </div>
            </div>

            <!-- Chart -->
            <div class="row pl-3">
                <div class="col-12 col-xl-12 cart-bg mb-2">
                    <div class="box-title">
                        <h2 class="title"><i class="fa-solid fa-chart-line fa-lg mr-2"></i>{{__('label.department_efficiency_overview')}}</h2>
                    </div>
                    <div class="row">
                        <div class="col-12 col-sm-12">
                            <div id="DepartmentChart"></div>
                        </div>
                    </div>
                </div>
                <div class="col-12 col-xl-12 cart-bg mt-3">
                    <div class="box-title">
                        <h2 class="title"><i class="fa-solid fa-chart-column fa-lg mr-2"></i>{{__('label.monthly_request_trends')}}</h2>
                    </div>
                    <div class="row mt-2 mb-2">
                        <div class="col-12 col-sm-12">
                            <Button id="year" class="btn btn-default mr-3">{{__('label.this_year')}}</Button>
                            <Button id="month" class="btn btn-default mr-3">{{__('label.this_month')}}</Button>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-12 col-sm-12">
                            <div id="Monthly_Request"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('pagescript')
    <!-- Chart.js Library -->
    <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
    <!-- Select2 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
    <!-- Export Files LInk (PDF, CSV, MS-Excel) -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.3.1/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.4.2/js/dataTables.buttons.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/pdfmake.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/vfs_fonts.js"></script>

    <script>
        $("#department_id").select2();
        // Sidebar Scroll Down
		sidebar_down($(document).height());

        getChartData(0);
        // department change
        $('#department_id').on('change', function () {
            let departmentId = $(this).val();
            getChartData(departmentId);
        });
        let months = [
            '{{__("label.jan")}}','{{__("label.feb")}}','{{__("label.mar")}}','{{__("label.apr")}}',
            '{{__("label.may")}}','{{__("label.jun")}}','{{__("label.jul")}}','{{__("label.aug")}}',
            '{{__("label.sep")}}','{{__("label.oct")}}','{{__("label.nov")}}','{{__("label.dec")}}'
        ];
        function getChartData (departmentId) {
            $.ajax({
                url: "{{ route('analytics-report.index') }}",
                type: "GET",
                data: { department_id: departmentId },
                success: function (res) {
                    
                    // Extract chart data
                    const depPerformance = res.dep_performance || [];
                    const performanceData = depPerformance.map(item => item.performance);
                    chart.updateOptions({
                        series: [{ name: '{{__("label.performance")}} (%)', data: performanceData }],
                        xaxis: { categories: months},
                        tooltip: {
                            y: {
                                formatter: function (val, { dataPointIndex }) {
                                    const data = depPerformance[dataPointIndex];
                                    return val + "% (Completed: " + data.completed + " / Total: " + data.total + ")";
                                }
                            }
                        }
                    });

                    // Safe access helpers
                    const yearlyData = res.yearly_request_trend || [];
                    const monthlyData = res.monthly_request_trend || [];

                    // Update main chart (default: yearly)
                    request_chart.updateOptions({
                        series: [{ name: '{{__("label.requests")}}', data: yearlyData }],
                        xaxis: { categories: months}
                    });

                    // Year toggle
                    $("#year").off().on("click", function() {
                        request_chart.updateOptions({
                            series: [{ name: '{{__("label.requests")}}', data: yearlyData }],
                            xaxis: { categories: months}
                        });
                    });

                    // Month toggle
                    $("#month").off().on("click", function() {
                        request_chart.updateOptions({
                            series: [{ name: '{{__("label.requests")}}', data: monthlyData }],
                            xaxis: { categories: Array.from({length: monthlyData.length}, (_, i) => i+1) }
                        });
                    });
                },
                error: function (xhr) {
                    console.error("AJAX error:", xhr.responseText);
                }
            });
        }

        // Init charts
        var options = {
            chart: {
                type: 'line',
                height: 350,
                toolbar: { show: false }
            },
            hover: {
                mode: 'nearest',
                intersect: true,
                animationDuration: 400,
            },
            series: [{ name: '{{__("label.performance")}}', data: [] }],   // default empty
            xaxis: { categories: [] },  
            colors: ['#4e45b8'],
            stroke: {
                curve: 'smooth',
                width: 3
            },
            markers: {
                size: 5
            }
        };
        var chart = new ApexCharts(document.querySelector("#DepartmentChart"), options);
        chart.render();

        let request_options = {
            chart: {
                type: 'bar',
                height: 400,
                toolbar: { show: false }
            },
            dataLabels: { enabled: false },
            plotOptions: {
                bar: { horizontal: false, columnWidth: '70%', endingShape: 'rounded' }
            },
            fill: {
                type: 'gradient',
                gradient: {
                    shade: 'light',
                    type: 'vertical',
                    shadeIntensity: 0.5,
                    gradientToColors: ['#4e45b8'],
                    inverseColors: false,
                    opacityFrom: 1,
                    opacityTo: 0.8,
                    stops: [0, 100]
                }
            },
            colors: ['#6a11cb', '#f7971e'],
            grid: { borderColor: '#9a9a9a', strokeDashArray: 4 },
            tooltip: { theme: 'dark', style: { fontSize: '14px' } },
            series: [
                { name: "{{__('label.requests')}}", data: [] }
            ],
            xaxis: {
                categories: [],
            },
            legend: {
                position: 'bottom',
                fontSize: '16px',
                fontWeight: 'bold',
                labels: { colors: ['#333'], useSeriesColors: false }
            },
        };
        var request_chart = new ApexCharts(document.querySelector("#Monthly_Request"), request_options);
        request_chart.render();
    </script>  
@endsection