@use('Illuminate\Support\Arr')
@php
$ridestatuscolorClasses = getRideStatusColorClasses();
$dateRange = getStartAndEndDate(request('sort'), request('start'), request('end'));
$start_date = $dateRange['start'] ?? null;
$end_date = $dateRange['end'] ?? null;
$serviceCategories = getAllServices();

$commissions = getMonthlyCommissions();
$adminCommission = array_values($commissions['admin_commission'] ?? []);
$driverCommission = array_values($commissions['driver_commission'] ?? []);
$fleetCommission = array_values($commissions['fleet_commission'] ?? []);
@endphp

{{-- Average Revenue --}}
<div class="col-xxl-7">
    <div class="card revenue-chart p-0">
        <div class="card-header">
            <h3>
                {{ __('cabbooking::static.widget.average_revenue') }}
            </h3>
        </div>
        <div class="card-body p-0">
            <div id="revenue-report">

            </div>
        </div>
    </div>
</div>

{{-- Recent Rides --}}
@can('ride.index')
<div class="col-xxl-5 col-xl-6">
    <div class="card top-drivers-card p-0">
        <div class="card-header">
            <h3>{{ __('cabbooking::static.widget.recent_rides') }}</h3>
            <a href="{{ route('admin.ride.index') }}">{{ __('cabbooking::static.widget.view_all') }}</a>
        </div>
        <div class="rides-tab analytics-section">
            <ul class="nav nav-tabs horizontal-tab custom-scroll" id="ride-tabs" role="tablist">
                @forelse ($serviceCategories as $key => $serviceCategory)
                <li class="nav-item" role="presentation">
                    <a class="nav-link @if ($key === 0) active @endif" id="tab-{{ $serviceCategory->id }}-tab"
                        data-bs-toggle="tab" href="#tab-{{ $serviceCategory->id }}" role="tab"
                        aria-controls="tab-{{ $serviceCategory->id }}"
                        aria-selected="{{ $key === 0 ? 'true' : 'false' }}">
                        {{ $serviceCategory->name }}
                    </a>
                </li>
                @empty
                <li class="nav-item" role="presentation">
                    <a class="nav-link disabled" href="#" role="tab" aria-disabled="true">
                        {{ __('cabbooking::static.widget.no_categories_available') }}
                    </a>
                </li>
                @endforelse
            </ul>
        </div>
        <div class="recent-rides-card custom-scrollbar">

            <div class="card-body top-drivers recent-rides p-0 ">
                <div class="tab-content">

                    @forelse ($serviceCategories as $key => $serviceCategory)

                    <div class="tab-pane fade @if ($key === 0) show active @endif" id="tab-{{ $serviceCategory->id }}"
                        role="tabpanel" aria-labelledby="tab-{{ $serviceCategory->id }}-tab">

                        @php
                        $categoryRides = getRecentRides($start_date, $end_date, $serviceCategory?->id);
                        @endphp
                        @if(count($categoryRides))
                        <table class="recent-rides-table">
                            <thead>
                                <tr>
                                    <th>{{ __('cabbooking::static.widget.ride_id') }}</th>
                                    <th>{{ __('cabbooking::static.widget.driver_name') }}</th>
                                    <th>{{ __('cabbooking::static.widget.distance') }}</th>
                                    <th>{{ __('cabbooking::static.widget.status') }}</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse ($categoryRides as $ride)
                                @if ($ride?->driver && $ride)
                                <tr>
                                    <td>
                                        <a href="{{ route('admin.ride.details', $ride?->id) }}">
                                            <span class="id-wrapper">#{{ $ride?->ride_number ?? 'N/A' }}</span>
                                        </a>
                                    </td>
                                    <td>
                                        <div class="driver-info">
                                            @if ($ride?->driver?->profile_image?->original_url)
                                            <img src="{{ $ride?->driver?->profile_image?->original_url }}" alt="">
                                            @else
                                            <div class="user-initials">
                                                <span>{{ strtoupper($ride?->driver?->name[0]) }}</span>
                                            </div>
                                            @endif
                                            <div>
                                                <h4>{{ $ride?->driver?->name ?? 'N/A' }}</h4>
                                                <span>@if(isDemoModeEnabled())
                                                    {{ __('cabbooking::static.demo_mode') }}
                                                    @else
                                                    {{ $ride?->driver?->email }}
                                                    @endif
                                                </span>
                                            </div>
                                        </div>
                                    </td>
                                    <td>{{ $ride?->distance ?? 0 }} {{ ucfirst($ride?->distance_unit ?? 'N/A') }} </td>
                                    <td>
                                        @if($ride?->ride_status)
                                        <span class="status {{ $ride?->ride_status?->slug }}">{{
                                            $ride?->ride_status?->name }}</span>
                                        @else
                                        <span class="status secondary">N/A</span>
                                        @endif
                                    </td>
                                </tr>
                                @endif
                                @empty

                                @endforelse
                            </tbody>
                        </table>
                        @else
                        <div class="table-no-data">
                            <img src="{{ asset('images/dashboard/data-not-found.svg') }}" alt="data not found" />
                            <h6 class="text-center">
                                {{ __('cabbooking::static.widget.no_data_available') }}</h6>
                        </div>
                        @endif
                    </div>
                    @empty
                    <div>N/A</div>
                    @endempty
                </div>
            </div>
        </div>
    </div>
</div>
@endcan

@can('ride.index')

@push('scripts')
<script src="{{ asset('js/apex-chart.js') }}"></script>
<script>
    // Convert PHP arrays to JavaScript using json_encode() with proper flags
        const adminCommission = @json($adminCommission ?? []);
        const driverCommission = @json($driverCommission ?? []);
        const fleetCommission = @json($fleetCommission ?? []);

        // Optional: Fallback to empty arrays of 12 zeros if data is missing/incomplete
        function padArray(arr, length = 12, fill = 0) {
            return arr.length >= length ? arr.slice(0, length) : [...arr, ...Array(length - arr.length).fill(fill)];
        }

        // var revenueChart = {
        //     series: [
        //         {
        //             name: "Fleet Commission",
        //             type: "column",
        //             data: padArray(fleetCommission)
        //         },
        //         {
        //             name: "Admin Commission",
        //             type: "line",
        //             data: padArray(adminCommission)
        //         },
        //         {
        //             name: "Driver Commission",
        //             type: "line",
        //             data: padArray(driverCommission)
        //         }
        //     ],

        //     chart: {
        //         height: 350,
        //         type: "line",
        //         toolbar: { show: false },
        //         stacked: false,
        //         dropShadow: {
        //             enabled: true,
        //             enabledOnSeries: [1, 2],
        //             top: 8,
        //             left: 0,
        //             blur: 8,
        //             color: "#000",
        //             opacity: 0.35
        //         }
        //     },

        //     stroke: {
        //         width: [0, 3, 3],
        //         curve: "smooth"
        //     },

        //     colors: ["#EEEEEE", "#2196F3", "#FC776D"],

        //     tooltip: {
        //         theme: "dark"
        //     },

        //     plotOptions: {
        //         bar: {
        //             columnWidth: "45%",
        //             borderRadius: 0
        //         }
        //     },

        //     fill: {
        //         opacity: [1, 1, 1]
        //     },

        //     markers: {
        //         size: 0
        //     },

        //     grid: {
        //         borderColor: "#0d0d0d",
        //         strokeDashArray: 2,
        //         yaxis: {
        //             lines: { show: true }
        //         }
        //     },

        //     xaxis: {
        //         categories: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
        //         labels: {
        //             style: {
        //                 fontSize: "13px",
        //                 fontWeight: 500,
        //                 colors: "#8A8A9C"
        //             }
        //         },
        //         axisBorder: { show: false },
        //         axisTicks: { show: false }
        //     },

        //     yaxis: {
        //         min: 0,
        //         tickAmount: 8,
        //         labels: {
        //             formatter: function (val) {
        //                 return val.toFixed(0);
        //             },
        //             style: {
        //                 fontSize: "13px",
        //                 fontWeight: 500,
        //                 colors: "#8A8A9C"
        //             }
        //         }
        //     },

        //     legend: {
        //         position: "top",
        //         horizontalAlign: "right",
        //         fontSize: "13px",
        //         markers: { radius: 4 }
        //     }
        // };

        // var chart = new ApexCharts(document.querySelector("#revenue-report"), revenueChart);
        // chart.render();
        var revenueChart = {
            series: [
                {
                    name: "Admin Commission",
                    data: padArray(fleetCommission)
                },
                {
                    name: "Driver Commission",
                    data: padArray(adminCommission)
                },
                {
                    name: "Fleet Commission",
                    data: padArray(driverCommission)
                }
            ],

            chart: {
                height: 440,
                type: "area",          
                stacked: true,        
                toolbar: { show: false }
            },

            stroke: {
                curve: "smooth",
                width: 2
            },

            colors: ["#030912", "#6B7380", "#9CA3AF"],

            fill: {
                type: "solid",
                opacity: 0.6          
            },

            markers: {
                size: 0
            },

            dataLabels: {
                enabled: false
            },

            grid: {
                borderColor: "#E5E7EB",
                strokeDashArray: 4,
                xaxis: { lines: { show: true } },
                yaxis: { lines: { show: true } }
            },

            xaxis: {
                categories: ["Jan","Feb","Mar","Apr","May","Jun",
                            "Jul","Aug","Sep","Oct","Nov","Dec"],
                labels: {
                    style: {
                        fontSize: "13px",
                        fontWeight: 500,
                        colors: "#8A8A9C"
                    }
                },
                axisBorder: { show: false },
                axisTicks: { show: false }
            },

            yaxis: {
                min: 0,
                tickAmount: 8,
                labels: {
                    formatter: function (val) {
                        return val.toFixed(0);
                    },
                    style: {
                        fontSize: "13px",
                        fontWeight: 500,
                        colors: "#8A8A9C"
                    }
                }
            },

            legend: {
                position: "top",
                horizontalAlign: "right",
                fontSize: "13px",
                markers: { radius: 4 }
            }
        };

        var chart = new ApexCharts(
            document.querySelector("#revenue-report"),
            revenueChart
        );

        chart.render();
</script>
@endpush
@endcan