<?php use \Modules\CabBooking\Enums\ServicesEnum; ?>
<?php use \Modules\CabBooking\Enums\ServiceCategoryEnum; ?>
<?php use \Modules\CabBooking\Enums\RoleEnum; ?>
<?php
$cabRides = getTotalRidesByServices(ServicesEnum::CAB, request('start_date'), request('end_date'));
$parcelRides = getTotalRidesByServices(ServicesEnum::PARCEL);
$freightRides = getTotalRidesByServices(ServicesEnum::FREIGHT);
$ambulanceRides = getTotalRidesByServices(ServicesEnum::AMBULANCE);
$totalRides = getTotalRides();

$dateRange = getStartAndEndDate(request('sort'), request('start'), request('end'));

$start_date = $dateRange['start'] ?? null;
$end_date = $dateRange['end'] ?? null;

$intercityRides = getTotalRidesByServiceCategory(ServiceCategoryEnum::INTERCITY, $start_date, $end_date);
$rideRides = getTotalRidesByServiceCategory(ServiceCategoryEnum::RIDE, $start_date, $end_date);
$rentalRides = getTotalRidesByServiceCategory(ServiceCategoryEnum::RENTAL, $start_date, $end_date);
$scheduledRides = getTotalRidesByServiceCategory(ServiceCategoryEnum::SCHEDULE, $start_date, $end_date);
$packageRides = getTotalRidesByServiceCategory(ServiceCategoryEnum::PACKAGE, $start_date, $end_date);
$totalRides = getTotalRides($start_date, $end_date);
$roleName = getCurrentRoleName();

$services = [
ServicesEnum::CAB => ['name' => 'Cab', 'categories' => [ServiceCategoryEnum::RIDE, ServiceCategoryEnum::INTERCITY,
ServiceCategoryEnum::PACKAGE, ServiceCategoryEnum::SCHEDULE, ServiceCategoryEnum::RENTAL]],
ServicesEnum::FREIGHT => ['name' => 'Freight', 'categories' => [ServiceCategoryEnum::RIDE,
ServiceCategoryEnum::INTERCITY, ServiceCategoryEnum::SCHEDULE]],
ServicesEnum::PARCEL => ['name' => 'Parcel', 'categories' => [ServiceCategoryEnum::RIDE, ServiceCategoryEnum::INTERCITY,
ServiceCategoryEnum::SCHEDULE]],
ServicesEnum::AMBULANCE => ['name' => 'Ambulance', 'categories' => []],
];
?>


<?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('ride.index')): ?>
<div class="col-xxl-5 col-md-6">
    <div class="card service-chart">
        <div class="card-header p-0">
            <h3>
                <?php echo e(__('cabbooking::static.vehicle_types.services')); ?>

            </h3>
        </div>
        <div class="card-body p-0">
            <div id="service-chart"></div>
        </div>
    </div>
</div>


<?php if($roleName != RoleEnum::DRIVER): ?>
<?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('driver.index')): ?>
<div class="col-xxl-4 col-xl-6">
    <div class="card top-drivers-card p-0">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h3 class="mb-0"><?php echo e(__('cabbooking::static.widget.top_drivers')); ?></h3>
            <a href="<?php echo e(route('admin.driver.index')); ?>" class="view-all">View All</a>
        </div>
        <div class="table-responsive custom-scrollbar">
            <table class="table top-drivers-table">
                <thead>
                    <tr>
                        <th><?php echo e(__('cabbooking::static.driver_name')); ?></th>
                        <th><?php echo e(__('cabbooking::static.reports.ratings')); ?></th>
                        <th><?php echo e(__('cabbooking::static.drivers.total_rides')); ?></th>
                        <th><?php echo e(__('cabbooking::static.reports.earnings')); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php $__empty_1 = true; $__currentLoopData = getTopDrivers($start_date,$end_date); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $driver): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                    <?php if($driver): ?>
                    <tr>
                        <td>
                            <div class="driver-info">
                                <?php if($driver?->profile_image?->original_url): ?>
                                <img src="<?php echo e($driver?->profile_image?->original_url); ?>" alt="">
                                <?php else: ?>
                                <div class="initial-letter">
                                    <span><?php echo e(strtoupper($driver->name[0])); ?></span>
                                </div>
                                <?php endif; ?>
                                <div>
                                    <h6><a href="<?php echo e(route('admin.driver.show', ['driver' => $driver?->id])); ?>">
                                            <?php echo e($driver?->name); ?>

                                        </a></h6>
                                    <small> <?php if(isDemoModeEnabled()): ?>
                                        <?php echo e(__('cabbooking::static.demo_mode')); ?>

                                        <?php else: ?>
                                        <?php echo e($driver?->email); ?>

                                        <?php endif; ?>
                                    </small>
                                </div>
                            </div>
                        </td>

                        <td>
                            <span class="rating">
                                <svg>
                                    <use xlink:href="<?php echo e(asset('images/dashboard/details/icon-sprite.svg#star')); ?>">
                                    </use>
                                </svg>
                                (<?php echo e(number_format($driver->rating_count, 1)); ?>)
                            </span>
                        </td>
                        <td><?php echo e(getTotalDriverRides($driver?->id)); ?></td>
                        <td><?php echo e(formatCurrency(getDriverWallet($driver->id)) ?? 0); ?></td>
                    </tr>
                    <?php endif; ?>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                    <div class="table-no-data">
                        <img src="<?php echo e(asset('images/dashboard/data-not-found.svg')); ?>" class="img-fluid"
                            alt="data not found">
                        <h6 class="text-center">
                            <?php echo e(__('cabbooking::static.widget.no_data_available')); ?>

                        </h6>
                    </div>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php endif; ?>
<?php endif; ?>


<div class="col-xxl-3 col-md-6">
    <div class="card target-chart">
        <div class="card-header p-0">
            <h3>
                <?php echo e(__(__('cabbooking::static.widget.service_categories'))); ?>

            </h3>
            <select id="serviceSelector" class="form-select form-select-sm w-auto">
                <?php $__currentLoopData = $services; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $service): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <option value="<?php echo e($key); ?>"><?php echo e($service['name']); ?></option>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </select>
        </div>
        <div class="card-body p-0">
            <div id="no-data" class="text-center d-none">
                <p> <?php echo e(__('cabbooking::static.widget.no_data_available')); ?></p>
            </div>
            <div id="service-category-chart">
            </div>
        </div>
    </div>
</div>

<?php $__env->startPush('scripts'); ?>
<script src="<?php echo e(asset('js/apex-chart.js')); ?>"></script>
<script>
    var isDark = document.body.classList.contains("dark");

        var cab = <?php echo json_encode(array_values($cabRides)); ?>;
        var parcel = <?php echo json_encode(array_values($parcelRides)); ?>;
        var freight = <?php echo json_encode(array_values($freightRides)); ?>;
        var ambulance = <?php echo json_encode(array_values($ambulanceRides)); ?>;
        var totalRides = <?php echo $totalRides ?>;

        // service-chart
        var options = {
            chart: {
                type: 'bar',
                height: 350,
                stacked: false,
                toolbar: {
                    show: false
                }
            },

            tooltip: {
                theme: isDark ? "dark" : "light"
            },

            series: [
                { name: "Cab", data: cab },
                { name: "Parcel", data: parcel },
                { name: "Freight", data: freight },
                { name: "Ambulance", data: ambulance }
            ],

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

            plotOptions: {
                bar: {
                    horizontal: false,
                    columnWidth: '35%',
                    borderRadius: 4,
                    borderRadiusApplication: 'end'
                }
            },

            dataLabels: {
                enabled: false
            },

            xaxis: {
                categories: ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
                            "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
            },

            yaxis: {
                tickAmount: 8,
                title: { text: '' }
            },

            legend: {
                position: 'top',
                horizontalAlign: 'right',
                markers: {
                    shape: 'circle',
                    radius: 12
                }
            },

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

            fill: {
                opacity: 1
            }
        };

        var chart = new ApexCharts(
            document.querySelector("#service-chart"),
            options
        );

        chart.render();


        const categoryChartData = {
        <?php $__currentLoopData = $services; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $serviceKey => $service): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
            "<?php echo e(strtolower($serviceKey)); ?>": {
                labels: [
                    <?php $__currentLoopData = $service['categories']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $cat): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        "<?php echo e(ucfirst(strtolower($cat))); ?>",
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                ],
                values: [
                    <?php $__currentLoopData = $service['categories']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $cat): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <?php echo e(getTotalRidesByServiceCategory($cat, $start_date, $end_date, $serviceKey)); ?>,
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                ]
            },
        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        };

        let serviceCategoryChart;
        var isDark = document.body.classList.contains("dark");

        function renderCategoryChart(serviceKey) {
            const data = categoryChartData[serviceKey.toLowerCase()] ?? null;
            const hasData = data && data.values && data.values.length > 0 && data.values.some(v => v > 0);

            document.getElementById('no-data').classList.toggle('d-none', hasData);
            document.getElementById('service-category-chart').classList.toggle('d-none', !hasData);

            if (!hasData) {
                if (serviceCategoryChart) {
                    serviceCategoryChart.destroy();
                    serviceCategoryChart = null;
                }
                return;
            }

            const options = {
                series: data.values,
                labels: data.labels,
                chart: {
                    type: "donut",
                    height: 300,
                    offsetY: 35
                },
                dataLabels: {
                    enabled: false,
                },
                legend: {
                    show: false,
                },
                stroke: {
                    width: 4,
                },
                plotOptions: {
                    pie: {
                        expandOnClick: false,
                        donut: {
                            size: "70%",
                            background: isDark ? "#1F2837" : "#F4F5F6",
                            labels: {
                                show: true,
                                name: {
                                    offsetY: 0,
                                },
                                total: {
                                    show: true,
                                    fontSize: "18px",
                                    fontFamily: "'lexend', sans-serif",
                                    fontWeight: 500,
                                    label: "Total Rides",
                                    formatter: function(w) {
                                        return w.globals.seriesTotals.reduce((a, b) => a + b, 0)
                                    },
                                    color: "#9CA3AF",
                                },
                            },
                        },
                    },
                },
                tooltip: {
                    theme: isDark ? "dark" : "light"
                },
                states: {
                    normal: { filter: { type: "none" } },
                    hover: { filter: { type: "none" } },
                    active: { allowMultipleDataPointsSelection: false, filter: { type: "none" } },
                },
                colors: ["#030912", "#1F2837", "#6B7380", "#9CA3AF", "#E5E7EB"],
            };

            if (serviceCategoryChart) {
                serviceCategoryChart.destroy();
            }

            serviceCategoryChart = new ApexCharts(
                document.querySelector("#service-category-chart"),
                options
            );
            serviceCategoryChart.render();
        }

        document.addEventListener('DOMContentLoaded', function() {
            const selector = document.getElementById('serviceSelector');

            if (selector) {
                renderCategoryChart(selector.value);

                selector.addEventListener('change', function() {
                    renderCategoryChart(this.value);
                });
            }
        });
</script>
<?php $__env->stopPush(); ?>
<?php endif; ?><?php /**PATH /home/webiotspc/GitHub/taxify-laravel/resources/views/modules/cabbooking/admin/widgets/services.blade.php ENDPATH**/ ?>