@extends('layouts.app')

@section('header')
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
    Admin Dashboard
</h2>
@endsection

@section('content')
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
    <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
        <div class="p-6 text-gray-900">
            Welcome, Admin! Here you can manage roles, users, and departments.
        </div>
    </div>

    <!-- Graphs Section -->
    <div class="mt-6">
        <h3 class="text-lg font-semibold">Analytics</h3>
        <div id="graphs-container" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-2 gap-6 mt-4">
            <!-- First three graphs -->
            <div class="bg-white p-4 shadow rounded">
                <h4 class="text-md font-semibold mb-4">Comparison of All Models by Department</h4>
                <div class="flex flex-row sm:flex-row sm:items-center sm:justify-between">
                    <select id="departmentSelector" class="mb-4 px-7 border rounded">
                    @foreach($departments as $department)
                    <option value="{{ $department->id }}">{{ $department->name }}</option>
                    @endforeach
                </select>
                <select id="comparisonYearSelector" class="mb-4 px-7 border rounded">
                    <option value="all">All Years</option>
                    @foreach($years as $year)
                        <option value="{{ $year }}">{{ $year }}</option>
                    @endforeach
                </select>
                </div>
                
                
                <canvas id="comparisonChart"></canvas>
            </div>

            <div class="bg-white p-4 shadow rounded">
                <h4 class="text-md font-semibold mb-4">Total Contribution by Department</h4>
                <div class="flex flex-row sm:flex-row sm:items-center sm:justify-between">
                    <select id="modelSelector" class="mb-4 sm:mb-0 p-2 border rounded">
                        <option value="all">All Categories</option>
                        <option value="ActivitiesAttended">Activities Attended</option>
                        <option value="ActivitiesOrganised">Activities Organised</option>
                        <option value="BooksPublished">Books Published</option>
                        <option value="ExternalEngagement">External Engagement</option>
                        <option value="IvOrganised">IV Organised</option>
                        <option value="OnlineCourse">Online Courses</option>
                        <option value="Patent">Patents</option>
                        <option value="Publication">Publications</option>
                    </select>
                    <select id="contributionYearSelector" class="mb-4 sm:ml-4 px-7 border rounded">
                        <option value="all">All Years</option>
                        @foreach($years as $year)
                            <option value="{{ $year }}">{{ $year }}</option>
                        @endforeach
                    </select>
                </div>
                <canvas id="contributionChart"></canvas>
            </div>
    </div>
</div>
@endsection

<!-- <style>
    #graphs-container canvas {
        max-width:500px; /* Set a maximum width for each graph */
        max-height:500px; /* Set a maximum height for each graph */
        margin: auto; /* Center the graphs */
    }
</style> -->

@section('scripts')
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Comparison Chart Script
        const departmentSelector = document.getElementById('departmentSelector');
        const comparisonYearSelector = document.getElementById('comparisonYearSelector');

        function fetchComparisonData(departmentId, year) {
            const yearParam = year === 'all' ? '' : `&year=${year}`;
            fetch(`{{ route('admin.analytics.comparison', ['department_id' => '']) }}${departmentId}${yearParam}`)
                .then(response => response.json())
                .then(data => {
                    const ctx = document.getElementById('comparisonChart').getContext('2d');
                    if (window.comparisonChartInstance) {
                        window.comparisonChartInstance.destroy();
                    }
                    // Map each bar to its corresponding page
                    const modelPages = [
                        'ActivitiesAttendedResponses',
                        'ActivitiesOrganisedResponses',
                        'BooksPublishedResponses',
                        'ExternalEngagementResponses',
                        'IvOrganisedResponses',
                        'OnlineCoursesResponses',
                        'PatentsResponses',
                        'PublicationsResponses'
                    ];
                    const barLinks = modelPages.map(page => `/admin/${page}`);
                    window.comparisonChartInstance = new Chart(ctx, {
                        type: 'bar',
                        data: {
                            labels: data.labels,
                            datasets: [{
                                label: 'Comparison by Department',
                                data: data.values,
                                backgroundColor: [
                                    'rgba(255, 99, 132, 0.2)',
                                    'rgba(54, 162, 235, 0.2)',
                                    'rgba(255, 206, 86, 0.2)',
                                    'rgba(75, 192, 192, 0.2)',
                                    'rgba(153, 102, 255, 0.2)',
                                    'rgba(255, 159, 64, 0.2)',
                                    'rgba(128, 0, 128, 0.2)', // Purple
                                    'rgba(0, 200, 0, 0.2)',   // Green
                                    'rgba(255, 165, 0, 0.2)', // Orange
                                    'rgba(0, 0, 255, 0.2)'    // Blue
                                ],
                                borderColor: [
                                    'rgba(255, 99, 132, 1)',
                                    'rgba(54, 162, 235, 1)',
                                    'rgba(255, 206, 86, 1)',
                                    'rgba(75, 192, 192, 1)',
                                    'rgba(153, 102, 255, 1)',
                                    'rgba(255, 159, 64, 1)',
                                    'rgba(128, 0, 128, 1)', // Purple
                                    'rgba(0, 128, 0, 1)',   // Green
                                    'rgba(255, 165, 0, 1)', // Orange
                                    'rgba(0, 0, 255, 1)'    // Blue
                                ],
                                borderWidth: 1
                            }]
                        },
                        plugins: [ChartDataLabels],
                        options: {
                            plugins: {
                                legend: {
                                    position: 'bottom',
                                    display: false
                                },
                                tooltip: {
                                    callbacks: {
                                        label: function(tooltipItem) {
                                            return `${tooltipItem.label}: ${tooltipItem.raw}`;
                                        }
                                    }
                                },
                                datalabels: {
                                    formatter: (value, ctx) => {
                                        return value;
                                    }
                                }
                            },
                            responsive: true,
                            scales: {
                                x: {
                                    beginAtZero: true
                                },
                                y: {
                                    beginAtZero: true
                                }
                            },
                            onClick: function(evt, elements) {
                                if (elements.length > 0) {
                                    const idx = elements[0].index;
                                    const departmentId = departmentSelector.value;
                                    // Only redirect if the bar index is within the modelPages range
                                    if (idx < barLinks.length) {
                                        window.location.href = `${barLinks[idx]}?department_id=${departmentId}`;
                                    }
                                }
                            }
                        }
                    });
                    // Update or create the total element
                    let comparisonTotal = document.getElementById('comparisonTotal');
                    if (!comparisonTotal) {
                        comparisonTotal = document.createElement('p');
                        comparisonTotal.id = 'comparisonTotal';
                        comparisonTotal.classList.add('text-center', 'font-bold', 'mt-2');
                        document.getElementById('comparisonChart').parentElement.appendChild(comparisonTotal);
                    }
                    comparisonTotal.textContent = `Total: ${data.total}`;
                });
        }

        // Initial fetch for department 1 and all years
        fetchComparisonData(1, 'all');

        // Update chart on department or year change
        departmentSelector.addEventListener('change', function() {
            fetchComparisonData(this.value, comparisonYearSelector.value);
        });

        comparisonYearSelector.addEventListener('change', function() {
            fetchComparisonData(departmentSelector.value, this.value);
        });

        // Contribution Chart Script
        const modelSelector = document.getElementById('modelSelector');
        const contributionYearSelector = document.getElementById('contributionYearSelector');

        function fetchContributionData(model, year) {
            const yearParam = year === 'all' ? '' : `&year=${year}`;
            fetch(`{{ route('admin.analytics.contribution', ['model' => '']) }}${model}${yearParam}`)
                .then(response => response.json())
                .then(data => {
                    const ctx = document.getElementById('contributionChart').getContext('2d');
                    if (window.contributionChartInstance) {
                        window.contributionChartInstance.destroy();
                    }
                    // Define bar links for each label (customize as needed)
                    const barLinks = data.labels.map((label, idx) => {
                        // Example: redirect to /admin/contribution/{id} (replace with your actual route/logic)
                        return `/admin/contribution/${data.ids ? data.ids[idx] : idx+1}`;
                    });
                    window.contributionChartInstance = new Chart(ctx, {
                        type: 'bar',
                        data: {
                            labels: data.labels,
                            datasets: [{
                                label: 'Total Contribution by Department',
                                data: data.values,
                                backgroundColor: [
                                    'rgba(255, 99, 132, 0.2)',
                                    'rgba(54, 162, 235, 0.2)',
                                    'rgba(255, 206, 86, 0.2)',
                                    'rgba(75, 192, 192, 0.2)',
                                    'rgba(153, 102, 255, 0.2)',
                                    'rgba(255, 159, 64, 0.2)',
                                    'rgba(128, 0, 128, 0.2)', // Purple
                                    'rgba(0, 200, 0, 0.2)',   // Green
                                    'rgba(255, 165, 0, 0.2)', // Orange
                                    'rgba(0, 0, 255, 0.2)'    // Blue
                                ],
                                borderColor: [
                                    'rgba(255, 99, 132, 1)',
                                    'rgba(54, 162, 235, 1)',
                                    'rgba(255, 206, 86, 1)',
                                    'rgba(75, 192, 192, 1)',
                                    'rgba(153, 102, 255, 1)',
                                    'rgba(255, 159, 64, 1)',
                                    'rgba(128, 0, 128, 1)', // Purple
                                    'rgba(0, 128, 0, 1)',   // Green
                                    'rgba(255, 165, 0, 1)', // Orange
                                    'rgba(0, 0, 255, 1)'    // Blue
                                ],
                                borderWidth: 1
                            }]
                        },
                        plugins: [ChartDataLabels],
                        options: {
                            plugins: {
                                legend: {
                                    position: 'bottom',
                                    display: false
                                },
                                tooltip: {
                                    callbacks: {
                                        label: function(tooltipItem) {
                                            return `${tooltipItem.label}: ${tooltipItem.raw}`;
                                        }
                                    }
                                }
                            },
                            datalabels: {
                                color: '#000',
                                font: {
                                    weight: 'bold'
                                },
                                formatter: (value, ctx) => {
                                    return value;
                                }
                            },
                            responsive: true,
                            scales: {
                                x: {
                                    beginAtZero: true
                                },
                                y: {
                                    beginAtZero: true
                                }
                            },
                            onClick: function(evt, elements) {
                                if (elements.length > 0) {
                                    const idx = elements[0].index;
                                    window.location.href = barLinks[idx];
                                }
                            }
                        }
                    });
                    // Update or create the total element
                    let contributionTotal = document.getElementById('contributionTotal');
                    if (!contributionTotal) {
                        contributionTotal = document.createElement('p');
                        contributionTotal.id = 'contributionTotal';
                        contributionTotal.classList.add('text-center', 'font-bold', 'mt-2');
                        document.getElementById('contributionChart').parentElement.appendChild(contributionTotal);
                    }
                    contributionTotal.textContent = `Total: ${data.total}`;
                });
        }

        // Initial fetch for all categories and all years
        fetchContributionData('all', 'all');

        // Update chart on model or year change
        modelSelector.addEventListener('change', function() {
            fetchContributionData(this.value, contributionYearSelector.value);
        });

        contributionYearSelector.addEventListener('change', function() {
            fetchContributionData(modelSelector.value, this.value);
        });
    });

</script>
@endsection