<?php
$datearray_json = json_encode($datearray);
$bookingcomplete_json= json_encode($bookingcomplete);
$nosales_json= json_encode($nosales);
$totalsale_json= json_encode($totalsale);
$retailsale_json= json_encode($retailsale);

?>
<div class="admin-page-title">
    <h1 class="mb-0">Dashboard</h1>
    <span class="admin-page-subtitle">Operational pulse, revenue signals, and delivery performance.</span>
</div>

   <!-- Delivery Statistics Section -->
   <?php if (isset($stats)): ?>
   <div class="row mb-4">
       <div class="col-md-12">
           <div class="admin-hero-card">
               <div class="d-flex flex-column flex-lg-row justify-content-between gap-3">
                   <div>
                       <h5 class="mb-1">Delivery Operations Overview</h5>
                       <p class="mb-0">Snapshot of orders, revenue, and fulfillment cadence.</p>
                   </div>
                   <div class="admin-chip"><i class="fa-solid fa-circle me-1"></i> Live</div>
               </div>
           </div>
       </div>
   </div>
   <div class="row g-3">
       <div class="col-md-3">
           <div class="admin-stat-tile primary">
               <span class="label">Orders Today</span>
               <div class="value"><?php echo isset($stats['ordersToday']) ? $stats['ordersToday'] : 0; ?></div>
               <span class="meta">$<?php echo isset($stats['revenueToday']) ? number_format($stats['revenueToday'], 2) : '0.00'; ?></span>
           </div>
       </div>
       <div class="col-md-3">
           <div class="admin-stat-tile success">
               <span class="label">Orders This Week</span>
               <div class="value"><?php echo isset($stats['ordersWeek']) ? $stats['ordersWeek'] : 0; ?></div>
               <span class="meta">$<?php echo isset($stats['revenueWeek']) ? number_format($stats['revenueWeek'], 2) : '0.00'; ?></span>
           </div>
       </div>
       <div class="col-md-3">
           <div class="admin-stat-tile info">
               <span class="label">Orders This Month</span>
               <div class="value"><?php echo isset($stats['ordersMonth']) ? $stats['ordersMonth'] : 0; ?></div>
               <span class="meta">$<?php echo isset($stats['revenueMonth']) ? number_format($stats['revenueMonth'], 2) : '0.00'; ?></span>
           </div>
       </div>
       <div class="col-md-3">
           <div class="admin-stat-tile warning">
               <span class="label">Active Drivers</span>
               <div class="value"><?php echo isset($activeDrivers) ? $activeDrivers : 0; ?></div>
               <span class="meta">Currently on duty</span>
           </div>
       </div>
   </div>

   <div class="row g-3 mt-2">
       <div class="col-md-4">
           <div class="admin-stat-tile">
               <span class="label">Pending Deliveries</span>
               <div class="value"><?php echo isset($stats['pendingDeliveries']) ? $stats['pendingDeliveries'] : 0; ?></div>
               <span class="meta">Awaiting fulfillment</span>
           </div>
       </div>
       <div class="col-md-4">
           <div class="admin-stat-tile success">
               <span class="label">Completed Deliveries</span>
               <div class="value"><?php echo isset($stats['completedDeliveries']) ? $stats['completedDeliveries'] : 0; ?></div>
               <span class="meta">Delivered successfully</span>
           </div>
       </div>
       <div class="col-md-4">
           <div class="admin-stat-tile info">
               <span class="label">Order Mix</span>
               <div class="d-flex justify-content-between">
                   <div>
                       <div class="value" style="font-size: 1.4rem;">
                           <?php echo isset($stats['cannabusInventoryOrders']) ? $stats['cannabusInventoryOrders'] : 0; ?>
                       </div>
                       <span class="meta">Cannabus</span>
                   </div>
                   <div>
                       <div class="value" style="font-size: 1.4rem;">
                           <?php echo isset($stats['storefrontOrders']) ? $stats['storefrontOrders'] : 0; ?>
                       </div>
                       <span class="meta">Storefront</span>
                   </div>
               </div>
           </div>
       </div>
   </div>
   
   <?php if (!empty($stats['revenueByCity'])): ?>
   <div class="row mt-4">
       <div class="col-md-12">
           <div class="admin-table-card">
               <table class="table mb-0">
                   <thead>
                       <tr>
                           <th>City</th>
                           <th>Orders</th>
                           <th>Revenue</th>
                           <th>Active Drivers</th>
                       </tr>
                   </thead>
                   <tbody>
                       <?php foreach ($stats['revenueByCity'] as $cityName => $revenue): ?>
                       <tr>
                           <td><?php echo $cityName; ?></td>
                           <td><?php echo isset($stats['ordersByCity'][$cityName]) ? $stats['ordersByCity'][$cityName] : 0; ?></td>
                           <td>$<?php echo number_format($revenue, 2); ?></td>
                           <td><?php echo isset($stats['driversByCity'][$cityName]) ? $stats['driversByCity'][$cityName] : 0; ?></td>
                       </tr>
                       <?php endforeach; ?>
                   </tbody>
               </table>
           </div>
       </div>
   </div>
   <?php endif; ?>
   <?php endif; ?>

   <div class="row g-3 mt-4">
       <div class="col-md-3">
           <div class="admin-stat-tile">
               <span class="label">Completed Bookings</span>
               <div class="value" id="totalbooking">0</div>
               <span class="meta">Total</span>
           </div>
       </div>
       <div class="col-md-3">
           <div class="admin-stat-tile">
               <span class="label">Product Sales</span>
               <div class="value" id="totalproductsale">0</div>
               <span class="meta">Total</span>
           </div>
       </div>
       <div class="col-md-3">
           <div class="admin-stat-tile">
               <span class="label">Base Revenue</span>
               <div class="value" id="totalsale">0</div>
               <span class="meta">Total</span>
           </div>
       </div>
       <div class="col-md-3">
           <div class="admin-stat-tile">
               <span class="label">Retail Revenue</span>
               <div class="value" id="retailsale">0</div>
               <span class="meta">Total</span>
           </div>
       </div>
   </div>

   <div class="row my-2">
       <div class="my-2"></div>
       <div class="col-md-12">
           <div class="admin-chart-card">
               <div class="d-flex justify-content-between align-items-center mb-3">
                   <div>
                       <h5 class="mb-1">Weekly Performance</h5>
                       <span class="admin-page-subtitle">Bookings, sales, and revenue trends.</span>
                   </div>
                   <div class="admin-pill">Last 7 days</div>
               </div>
               <!-- Modal -->
               <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel"
                   aria-hidden="true">
                   <div class="modal-dialog">
                       <div class="modal-content">
                           <div class="modal-header">
                               <h1 class="modal-title fs-5" id="exampleModalLabel">Select Custom Date</h1>
                               <button type="button" class="btn-close" data-bs-dismiss="modal"
                                   aria-label="Close"></button>
                           </div>
                           <div class="modal-body">
                               <input class="form-control" type="text" id="dateRangePicker"
                                   style="margin-bottom: 20px;">
                           </div>

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


               <div id="chart"></div>
           </div>
       </div>
   </div>
   <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>

   <script>
       var dateArray = <?php echo $datearray_json; ?>;
       var bookingArray=<?php echo $bookingcomplete_json; ?>;
       var valuesArray = Object.values(bookingArray);
       var nosaleArray=<?php echo $nosales_json; ?>;
       var saleArray = Object.values(nosaleArray);
       var totalsale_Array=<?php echo $totalsale_json; ?>;
       var totalsaleArray = Object.values(totalsale_Array);
       var retailsale_Array=<?php echo $retailsale_json; ?>;
       var retailsaleArray = Object.values(retailsale_Array);
       
       
        
console.log(dateArray,bookingArray,valuesArray); 
var chartOptions = {
    series: [{
        name: 'Completed Bookings',
        data: valuesArray
    }, {
        name: 'Product Sales',
        data: saleArray // Weekly aggregated data
    }, {
        name: 'Base Revenue',
        data: totalsaleArray // Weekly aggregated data
    }, {
        name: 'Retail Revenue',
        data: retailsaleArray // Weekly aggregated data
    }],
    colors: ['#39D6FF', '#7A8192', '#FF5733', '#33FF57'], // Different colors for each series
    chart: {
        height: 350,
        type: 'area',
    },
    dataLabels: {
        enabled: false
    },
    stroke: {
        curve: 'smooth'
    },
    xaxis: {
        type: 'datetime',
        categories: dateArray
    },
    tooltip: {
        x: {
            format: 'dd MMM yyyy' // Show date in day/month/year format for weeks
        },
    },
};

var chart = new ApexCharts(document.querySelector("#chart"), chartOptions);
chart.render();

$(function() {
    $('#dateRangePicker').daterangepicker({
        opens: 'left',
        locale: {
            format: 'YYYY-MM-DD'
        }
    }, function(start, end, label) {
        var startDate = start.format('YYYY-MM-DD');
        var endDate = end.format('YYYY-MM-DD');
        // console.log("data select")
        // Update chart data based on the selected date range
        updateChartData(startDate, endDate);
    });
});

function updateChartData(startDate, endDate) {
    // Fetch new data based on the selected date range and update the chart
    // This is just an example. Replace it with your data fetching logic.
    var newCategories = [
        "2018-09-19T00:00:00.000Z",
        "2018-09-19T01:30:00.000Z",
        "2018-09-19T02:30:00.000Z",
        "2018-09-19T03:30:00.000Z",
        "2018-09-19T04:30:00.000Z",
        "2018-09-19T05:30:00.000Z",
        "2018-09-19T06:30:00.000Z"
    ];
    var newData = [{
        name: 'Completed Bookings',
        data: [11, 32, 45, 32, 34, 52, 41] // Update with filtered data
    }, {
        name: 'Product Sales',
        data: [11, 32, 45, 32, 34, 52, 41] // Update with filtered data
    }, {
        name: 'Base Revenue',
        data: [20, 30, 40, 50, 60, 70, 80] // Update with filtered data
    }, {
        name: 'Retail Revenue',
        data: [15, 25, 35, 45, 55, 65, 75] // Update with filtered data
    }];

    chart.updateOptions({
        xaxis: {
            categories: newCategories
        },
        series: newData
    });
}

   </script>