@extends('template.app')

@section('meta')
@endsection

@section('title')
Dashboard
@endsection

@section('styles')
<style>
    .card-chart{
        align-items:unset !important;
    }


    .obf-wrapper {
        position: relative;
        border-radius: 15px;
        padding: 25px 20px 20px 20px;
        background: #f8f9fc; /* match your UI background */
    }

    /* Gradient Border */
    .obf-wrapper::before {
        content: "";
        position: absolute;
        inset: 0;
        border-radius: 15px;
        padding: 2px;
        background: linear-gradient(135deg, #4facfe, #00f2fe, #43e97b);
        -webkit-mask: 
            linear-gradient(#fff 0 0) content-box, 
            linear-gradient(#fff 0 0);
        -webkit-mask-composite: xor;
        mask-composite: exclude;
        z-index: 1;
        pointer-events: none;
    }

    /* Heading (this will CUT the border properly) */
    .obf-heading {
        position: absolute;
        top: -15px;
        left: 20px;
        background: inherit; /* SAME as wrapper background */
        padding: 0 12px;
        font-weight: 600;
        font-size: 23px;
        color: #333;
        z-index: 2; /* ABOVE border */
    }
</style>

@endsection

@section('content')


    @if(auth()->user()->name_of_company)
        <div class="container-fluid">
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-body">
                            <form action="{{ route('change_password.save') }}" name="form" id="form" method="post" enctype="multipart/form-data">
                                @csrf
                                @method('POST')
                                
                                @if(session('message'))
                                    <div class="alert alert-success">
                                        {{ session('message') }}
                                    </div>
                                @endif
        
                                <div class="row">
                                    <div class="form-group col-sm-5">
                                        <label for="password">Enter New Password</label>
                                        <input type="password" name="new_password" class="form-control" placeholder="Please enter password">
                                        <span class="kt-form__help error password"></span>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <button type="submit" class="btn waves-effect waves-light btn-rounded btn-outline-primary">Submit</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    @else
        <div class="container-fluid">

            <div class="row">
                <div class="col-xl-6 mb-2">
                    <div class="obf-wrapper p-3">
                        <div class="obf-heading">OBFs</div>
                        <div class="row mt-3">
                            
                            <div class="col-xl-3 col-md-3 mb-2">
                                <a href="{{route('obf')}}" style="text-decoration:none;">    
                                    <div class="card border-left-success shadow h-100 py-2">
                                        <div class="card-body">
                                            <div class="row no-gutters align-items-center">
                                                <div class="col mr-2">
                                                    <div class="text-xs font-weight-bold text-primary text-uppercase mb-1 card-text">
                                                        OBF Created
                                                    </div>
                                                    <div class="h5 mb-0 font-weight-bold text-gray-800 white_text card-value">
                                                        {{ $total_obf }}
                                                    </div>
                                                </div>
                                                <div class="card-icon">
                                                    <i class="fas fa-calendar fa-2x text-gray-300"></i>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </a>
                            </div>

                            <div class="col-xl-3 col-md-6 mb-2">
                                <div class="card border-left-success shadow h-100 py-2">
                                    <div class="card-body">
                                        <a href="{{route('obf_approval', ['status' => 'pending'])}}">   
                                            <div class="row no-gutters align-items-center">
                                                <div class="col mr-2">
                                                    <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                                        Pending For TL Approval</div>
                                                    <div class="h5 mb-0 font-weight-bold text-gray-800 white_text">{{ $tl_pending }}</div>
                                                </div>
                                                <div class="col-auto">
                                                    <i class="fas fa-dollar-sign fa-2x text-gray-300"></i>
                                                </div>
                                            </div>
                                        </a>
                                    </div>
                                </div>
                            </div>  

                            <div class="col-xl-3 col-md-6 mb-2">
                                <div class="card border-left-success shadow h-100 py-2">
                                    <div class="card-body">
                                        <a href="{{route('obf_approval', ['status' => 'obf_tl_accepted'])}}">  
                                            <div class="row no-gutters align-items-center">
                                                <div class="col mr-2">
                                                    <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                                        Pending For SM Approval</div>
                                                    <div class="h5 mb-0 font-weight-bold text-gray-800 white_text">{{ $sm_pending }}</div>
                                                </div>
                                                <div class="col-auto">
                                                    <i class="fas fa-dollar-sign fa-2x text-gray-300"></i>
                                                </div>
                                            </div>
                                        </a>
                                    </div>
                                </div>
                            </div>  

                            <div class="col-xl-3 col-md-6 mb-2">
                                <div class="card border-left-success shadow h-100 py-2">
                                    <div class="card-body">
                                        <a href="{{route('obf_approval', ['status' => 'obf_sm_accepted'])}}">      
                                            <div class="row no-gutters align-items-center">
                                                <div class="col mr-2">
                                                    <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                                        Pending For GM Approval</div>
                                                    <div class="h5 mb-0 font-weight-bold text-gray-800 white_text">{{ $gm_pending }}</div>
                                                </div>
                                                <div class="col-auto">
                                                    <i class="fas fa-dollar-sign fa-2x text-gray-300"></i>
                                                </div>
                                            </div>
                                        </a>
                                    </div>
                                </div>
                            </div>      
                        </div>
                    </div>
                </div>

                @if(!in_array(auth()->user()->roles[0]['name'], ['KEC', 'Team leader']))
                <div class="col-xl-6 mb-2">
                    <div class="obf-wrapper p-3">
                        <div class="obf-heading">INVENTORIES - {{ $total_inventory }}</div>
                        <div class="row mt-3">
                            <div class="col-xl-3 col-md-3 mb-2">
                                <div class="card border-left-success shadow h-100 py-2">
                                    <div class="card-body">
                                        <a href="{{route('inventory', ['status' => 'active'])}}">
                                            <div class="row no-gutters align-items-center">
                                                <div class="col mr-2">
                                                    <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                                        Live Inventory</div>
                                                    <div class="h5 mb-0 font-weight-bold text-gray-800 white_text">{{ $live_inventory }}</div>
                                                </div>
                                                <div class="col-auto">
                                                    <i class="fas fa-bookmark fa-2x text-gray-300"></i>
                                                </div>
                                            </div>
                                        </a>
                                    </div>
                                </div>
                            </div>

                            <div class="col-xl-3 col-md-3 mb-2">
                                <div class="card border-left-success shadow h-100 py-2">
                                    <div class="card-body">
                                        <a href="{{route('transit-inventory', ['status' => 'active'])}}">
                                            <div class="row no-gutters align-items-center">
                                                <div class="col mr-2">
                                                    <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                                        In Transit</div>
                                                    <div class="h5 mb-0 font-weight-bold text-gray-800 white_text">{{ $transit_inventory }}</div>
                                                </div>
                                                <div class="col-auto">
                                                    <i class="fas fa-bookmark fa-2x text-gray-300"></i>
                                                </div>
                                            </div>
                                        </a>
                                    </div>
                                </div>
                            </div>

                            <div class="col-xl-3 col-md-3 mb-2">
                                <div class="card border-left-success shadow h-100 py-2">
                                    <div class="card-body">
                                        <a href="{{route('inventory', ['status' => 'allocated'])}}">
                                            <div class="row no-gutters align-items-center">
                                                <div class="col mr-2">
                                                    <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                                        Allocated Customer</div>
                                                    <div class="h5 mb-0 font-weight-bold text-gray-800 white_text">{{ $customer_alloted }}</div>
                                                </div>
                                                <div class="col-auto">
                                                    <i class="fas fa-bookmark fa-2x text-gray-300"></i>
                                                </div>
                                            </div>
                                        </a>
                                    </div>
                                </div>
                            </div>

                            <div class="col-xl-3 col-md-3 mb-2">
                                <div class="card border-left-success shadow h-100 py-2">
                                    <div class="card-body">
                                        <a href="{{route('inventory.car_allocate_delearlist')}}">
                                            <div class="row no-gutters align-items-center">
                                                <div class="col mr-2">
                                                    <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                                        Allocated Dealer</div>
                                                    <div class="h5 mb-0 font-weight-bold text-gray-800 white_text">{{ $dealer_alloted }}</div>
                                                </div>
                                                <div class="col-auto">
                                                    <i class="fas fa-bookmark fa-2x text-gray-300"></i>
                                                </div>
                                            </div>
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                @endif
            </div>   

            <div class="row">
                @if(!in_array(auth()->user()->roles[0]['name'], ['KEC', 'Team leader']))
                <div class="col-xl-6 mb-2 mt-3">
                    <div class="obf-wrapper p-3">
                        <div class="obf-heading">ORDERs</div>
                        <div class="row mt-3">

                            <div class="col-xl-4 col-md-6 mb-2">
                                <div class="card border-left-success shadow h-100 py-2">
                                    <div class="card-body">
                                        <a href="{{route('order', ['status' => 'all_payment_done'])}}">
                                            <div class="row no-gutters align-items-center">
                                                <div class="col mr-2">
                                                    <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                                        All Payment Done</div>
                                                    <div class="h5 mb-0 font-weight-bold text-gray-800 white_text">{{ $all_payment_done }}</div>
                                                </div>
                                                <div class="col-auto">
                                                    <i class="fas fa-dollar-sign fa-2x text-gray-300"></i>
                                                </div>
                                            </div>
                                        </a>
                                    </div>
                                </div>
                            </div>  

                            <div class="col-xl-4 col-md-6 mb-2">
                                <div class="card border-left-success shadow h-100 py-2">
                                    <div class="card-body">
                                        <a href="{{route('order', ['status' => 'invoice_create'])}}">
                                            <div class="row no-gutters align-items-center">
                                                <div class="col mr-2">
                                                    <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                                        Invoice Created</div>
                                                    <div class="h5 mb-0 font-weight-bold text-gray-800 white_text">{{ $invoice_create }}</div>
                                                </div>
                                                <div class="col-auto">
                                                    <i class="fas fa-dollar-sign fa-2x text-gray-300"></i>
                                                </div>
                                            </div>
                                        </a>
                                    </div>
                                </div>
                            </div>  

                            <div class="col-xl-4 col-md-6 mb-2">
                                <div class="card border-left-success shadow h-100 py-2">
                                    <div class="card-body">
                                        <a href="{{route('order', ['status' => 'delivered'])}}">
                                            <div class="row no-gutters align-items-center">
                                                <div class="col mr-2">
                                                    <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                                        Delivered</div>
                                                    <div class="h5 mb-0 font-weight-bold text-gray-800 white_text">{{ $delivered }}</div>
                                                </div>
                                                <div class="col-auto">
                                                    <i class="fas fa-dollar-sign fa-2x text-gray-300"></i>
                                                </div>
                                            </div>
                                        </a>
                                    </div>
                                </div>
                            </div>      
                        </div>
                    </div>
                </div>

                
                <div class="col-xl-6 mb-2 mt-3">
                    <div class="obf-wrapper p-3">
                        <div class="obf-heading">REPORTs</div>
                        <div class="row mt-3">

                            <div class="col-xl-4 col-md-3 mb-2">
                                <div class="card border-left-success shadow h-100 py-2">
                                    <div class="card-body">
                                        <a href="{{route('allReport')}}">
                                            <div class="row no-gutters align-items-center">
                                                <div class="col mr-2">
                                                    <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                                        Mis Report</div>
                                                    <div class="h5 mb-0 font-weight-bold text-gray-800 white_text">30</div>
                                                </div>
                                                <div class="col-auto">
                                                    <i class="fas fa-bookmark fa-2x text-gray-300"></i>
                                                </div>
                                            </div>
                                        </a>
                                    </div>
                                </div>
                            </div>

                            @if(auth()->user()->can('day-book-report'))
                                <div class="col-xl-4 col-md-3 mb-2">
                                    <div class="card border-left-success shadow h-100 py-2">
                                        <div class="card-body">
                                            <a href="{{route('DayBookReportFetch')}}">
                                                <div class="row no-gutters align-items-center">
                                                    <div class="col mr-2">
                                                        <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                                            Day Book Report</div>
                                                        <div class="h5 mb-0 font-weight-bold text-gray-800 white_text">1</div>
                                                    </div>
                                                    <div class="col-auto">
                                                        <i class="fas fa-bookmark fa-2x text-gray-300"></i>
                                                    </div>
                                                </div>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            @endif    

                            @if(auth()->user()->can('booking-retail-report'))
                                <div class="col-xl-4 col-md-3 mb-2">
                                    <div class="card border-left-success shadow h-100 py-2">
                                        <div class="card-body">
                                            <a href="{{route('BookingRetailReport')}}">
                                                <div class="row no-gutters align-items-center">
                                                    <div class="col mr-2">
                                                        <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                                            Booking Retail Report</div>
                                                        <div class="h5 mb-0 font-weight-bold text-gray-800 white_text">1</div>
                                                    </div>
                                                    <div class="col-auto">
                                                        <i class="fas fa-bookmark fa-2x text-gray-300"></i>
                                                    </div>
                                                </div>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            @endif      
                        </div>
                    </div>
                </div>
                @endif
            </div>     
        
            <div class="row mt-2">
                <div class="col-xl-6 col-lg-6 col-sm-12">
                    <div id="piechart-1"></div>
                </div>
                
                <div class="col-xl-6 col-lg-6 col-sm-12">
                    <div id="piechart-2"></div>
                </div>
                
                <div class="col-xl-6 col-lg-6 col-sm-12">
                    <div id="piechart-3"></div>
                </div>
                
                <div class="col-xl-6 col-lg-6 col-sm-12">
                    <div id="piechart-4"></div>
                </div>
            </div>    
            
            <div class="row">
                <div class="col-md-4">
                    <div class="card shadow mb-4 inventory-card card-chart">
                        <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                            <h6 class="m-0 font-weight-bold text-primary">Branch Wise OBF</h6>
                        </div>
                        <div class="card-body">
                            <div id="chart4"></div>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-4">
                    <div class="card shadow mb-4 inventory-card card-chart">
                        <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                            <h6 class="m-0 font-weight-bold text-primary">Car Model Wise OBF</h6>
                        </div>
                        <div class="card-body">
                            <div id="chart5"></div>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-4">
                    <div class="card shadow mb-4 inventory-card card-chart">
                        <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                            <h6 class="m-0 font-weight-bold text-primary">Fuel Type OBF</h6>
                        </div>
                        <div class="card-body">
                            <div id="chart6"></div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="row">
                <!-- Chart 1 -->
                <div class="col-md-4">
                    <div class="card shadow mb-4 inventory-card card-chart">
                        <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                            <h6 class="m-0 font-weight-bold text-primary">Inventory Type</h6>
                        </div>
                        <div class="card-body">
                            <div id="chart1"></div>
                        </div>
                    </div>
                </div>
        
                <!-- Chart 2 -->
                <div class="col-md-4">
                    <div class="card shadow mb-4 type-card card-chart">
                        <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                            <h6 class="m-0 font-weight-bold text-warning">Model Wise Inventory</h6>
                        </div>
                        <div class="card-body">
                            <div id="chart2"></div>
                        </div>
                    </div>
                </div>
        
                <!-- Chart 3 -->
                <div class="col-md-4">
                    <div class="card shadow mb-4 car-card card-chart">
                        <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                            <h6 class="m-0 font-weight-bold text-success">Fuel Type Inventory</h6>
                        </div>
                        <div class="card-body">
                            <div id="chart3"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    @endif
@endsection

@section('scripts')

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
    google.charts.load('current', { packages: ['corechart'] });

    function fetchChartData() {
        var formattedData1 = [['Inventory Type', 'Value']];
        var formattedData2 = [['Model Name', 'Value']];
        var formattedData3 = [['Fuel Type', 'Value']];
        var formattedData4 = [['Branch Name', 'Value']];
        var formattedData5 = [['Car Model', 'Value']];
        var formattedData6 = [['Fuel Type', 'Value']];

        $.when(
            $.getJSON("{{ url('dashboard/inventory_type_chart') }}", function(response) {
                response.forEach(item => {
                    formattedData1.push([item.inventory_type_name, item.total_inventory]);
                });
            }),
            $.getJSON("{{ url('dashboard/model_wise_inventory_chart') }}", function(response) {
                response.forEach(item => {
                    formattedData2.push([item.model_name, item.total_inventory]);
                });
            }),
            $.getJSON("{{ url('dashboard/fuel_type_inventory_chart') }}", function(response) {
                response.forEach(item => {
                    formattedData3.push([item.fuel_name, item.total_inventory]);
                });
            }),
            $.getJSON("{{ url('dashboard/branches_wise_obf_chart') }}", function(response) {
                response.forEach(item => {
                    formattedData4.push([item.name, item.total_inventory]);
                });
            }),
            $.getJSON("{{ url('dashboard/car_model_wise_obf_chart') }}", function(response) {
                response.forEach(item => {
                    formattedData5.push([item.name, item.total_inventory]);
                });
            }),
            $.getJSON("{{ url('dashboard/fuel_type_obf_chart') }}", function(response) {
                response.forEach(item => {
                    formattedData6.push([item.fuel_type_name, item.total_inventory]);
                });
            })
        ).done(function() {
            drawCharts(formattedData1, formattedData2, formattedData3, formattedData4, formattedData5, formattedData6);
        });
    }

    function drawCharts(data1, data2, data3, data4, data5, data6) {
        // console.log("Chart 1 Data:", data1);
        var options = {
            height: 350,
            width: "100%", 
            chartArea: { width: "90%", height: "80%" },
            legend: { textStyle: { color: '#fff' }, position: 'top' },
            titleTextStyle: { color: '#fff' },
            tooltip: { textStyle: { color: '#000000' } }
        };

        new google.visualization.PieChart(document.getElementById('chart1')).draw(google.visualization.arrayToDataTable(data1), options);
        new google.visualization.PieChart(document.getElementById('chart2')).draw(google.visualization.arrayToDataTable(data2), options);
        new google.visualization.PieChart(document.getElementById('chart3')).draw(google.visualization.arrayToDataTable(data3), options);
        new google.visualization.PieChart(document.getElementById('chart4')).draw(google.visualization.arrayToDataTable(data4), options);
        new google.visualization.PieChart(document.getElementById('chart5')).draw(google.visualization.arrayToDataTable(data5), options);
        new google.visualization.PieChart(document.getElementById('chart6')).draw(google.visualization.arrayToDataTable(data6), options);
    }

    google.charts.setOnLoadCallback(fetchChartData);
    $(window).resize(fetchChartData);
        
        $(document).ready(function () {
            $.ajax({
                type: "GET",
                url: "{{ url('dashboard/car_wise_inventory_chart') }}",
                dataType: "json",
                success: function (response) {
                    let container = $("#carWiseChart");
                    container.empty();
        
                    if (response.length > 0) {
                        let progressHtml = "";
        
                        response.forEach(function (item, index) {
                            let color = getColor(item.model_name, index);
                            
                            progressHtml += `
                                <div class="text-white text-center mb-2">${item.model_name} - ${item.percentage_value}%</div>
                                <div class="progress mb-3" style="height: 12px;">
                                    <div class="progress-bar" role="progressbar" 
                                        style="width: ${item.percentage_value}%; background-color: ${color};"
                                        aria-valuenow="${item.percentage_value}" aria-valuemin="0" aria-valuemax="100">
                                    </div>
                                </div>
                            `;
                        });
        
                        container.html(progressHtml);
                    } else {
                        container.html('<p class="text-white text-center">No Data Available</p>');
                    }
                },
                error: function (xhr, status, error) {
                    console.error("Error fetching car-wise inventory data:", {
                        status: xhr.status,
                        statusText: xhr.statusText,
                        responseText: xhr.responseText,
                    });
                    $("#carWiseChart").html('<p class="text-white text-center">Error loading data. Please try again later.</p>');
                }
            });
    
            function getColor(model, index) {
                let colors = {
                    'Carens': '#3ef683',
                    'Sonet': '#dc3545',
                    'Seltos': '#ffc107',
                    'Syros': '#ff5733',
                    'Carnival': '#6610f2',
                    'EV6': '#17a2b8'
                };
        
                return colors[model] || generateRandomColor(index);
            }
            function generateRandomColor(index) {
                let colors = ['#007bff', '#28a745', '#fd7e14', '#20c997', '#e83e8c', '#6c757d'];
                return colors[index % colors.length];
            }
        });
    
        document.addEventListener("DOMContentLoaded", function () {
            fetch("{{ url('dashboard/obf_pie_chart') }}")
            .then(response => response.json())
            .then(data => {
                if (!data || data.length === 0) {
                    document.getElementById("chartLegend").innerHTML = "<p class='text-center text-danger'>No Data Available</p>";
                    return;
                }
    
                let labels = [];
                let dataset = [];
                let colors = [
                    "#007bff", "#69de57", "#dc3545", "#17a2b8", "#343a40", "#6d67db",
                    "#f8d77f", "#aef8b4", "#e1792c", "#c2793e", "#bcddb3", "#ffc7b0",
                    "#0afa1e", "#d2e8e0", "#879c67", "#29675c", "#87413f", "#dd9944"
                ];
    
                data.forEach((item, index) => {
                    //labels.push(item.status);
                    let formattedStatus = item.status.replace(/_/g, ' ') // Replace underscores with spaces
                                     .replace(/\b\w/g, c => c.toUpperCase()); // Capitalize first letter of each word
                    labels.push(formattedStatus);
                    dataset.push(item.count);
                });
    
                var ctx = document.getElementById("myPieChart").getContext("2d");
    
                new Chart(ctx, {
                    type: 'doughnut',
                    data: {
                        labels: labels,
                        datasets: [{
                            data: dataset,
                            backgroundColor: colors.slice(0, labels.length)
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: false // Hide default legend to use a custom one
                            }
                        }
                    }
                });
    
                // Generate Custom Legend
                let legendHTML = labels.map((label, index) => 
                    `<span class="mr-2">
                        <i class="fas fa-circle" style="color:${colors[index]};"></i> ${label}
                    </span>`
                ).join(" ");
                
                document.getElementById("chartLegend").innerHTML = legendHTML;
            })
            .catch(error => {
                console.error("Error loading OBF Pie Chart data:", error);
                document.getElementById("chartLegend").innerHTML = "<p class='text-center text-danger'>Error Loading Data</p>";
            });
        });
        
        document.addEventListener("DOMContentLoaded", function () {
            fetch("{{ url('dashboard/branches_wise_bar_chart') }}")
            .then(response => response.json())
            .then(data => {
                if (data.length === 0) {
                    document.getElementById("myChartContainer").innerHTML = "<p class='text-center text-white'>No Data Available</p>";
                    return;
                }
        
                let branchNames = data.map(item => {
                    let nameParts = item.name.split(" ");
                    return nameParts[nameParts.length - 1]; 
                });
        
                let inventoryValues = data.map(item => item.total_inventory);
        
                let barColors = ["#df4e4e", "#3b8935", "#c9e33a", "#de9e19", "#3e877c"];
        
                let ctx = document.getElementById("myChart").getContext("2d");
                new Chart(ctx, {
                    type: "bar",
                    data: {
                        labels: branchNames,
                        datasets: [{
                            backgroundColor: barColors.slice(0, branchNames.length),
                            data: inventoryValues
                        }]
                    },
                    options: {
                        legend: { display: false },
                        title: {
                            display: true,
                            text: "Branch Wise Inventory"
                        },
                        scales: {
                            y: { beginAtZero: true },
                            x: { 
                                ticks: { autoSkip: false }
                            }
                        }
                    }
                });
            })
            .catch(error => {
                console.error("Fetch error:", error);
                document.getElementById("myChartContainer").innerHTML = `<p class='text-center text-white'>Error: ${error.message}</p>`;
            });
        });
    </script>
    
    <script src="{{ asset('assets/vendor/chart.js/Chart.min.js') }}"></script>
    <script src="{{ asset('assets/js/demo/chart-area-demo.js') }}"></script>
    <script src="{{ asset('assets/js/demo/chart-pie-demo.js') }}"></script>
@endsection



