<?php
$datearray_json = json_encode($datearray);
$bookingcomplete_json = json_encode($bookingcomplete);
$totalsale_json = json_encode($totalsale);

?>
<div class="row">
       <div class="col-md-8 my-2">
           <h3 class="fmon">Dashboard</h3>
       </div>
   </div>

   <!-- Booking App Key Metrics -->
   <div class="row mb-4">
       <div class="col-md-4 mb-3">
           <div class="card border-primary shadow-sm">
               <div class="card-body">
                   <div class="d-flex align-items-center justify-content-between">
                       <div>
                           <h6 class="text-muted mb-2">Total Users</h6>
                           <h2 class="mb-0 text-primary"><?php echo isset($totalUsers) ? $totalUsers : 0; ?></h2>
                           <small class="text-muted">
                               <span class="text-success"><?php echo isset($activeUsers) ? $activeUsers : 0; ?></span> Active
                           </small>
                       </div>
                       <div class="text-primary" style="font-size: 48px; opacity: 0.2;">
                           <i class="fas fa-users"></i>
                       </div>
                   </div>
               </div>
           </div>
       </div>
       <div class="col-md-4 mb-3">
           <div class="card border-success shadow-sm">
               <div class="card-body">
                   <div class="d-flex align-items-center justify-content-between">
                       <div>
                           <h6 class="text-muted mb-2">Total Drivers</h6>
                           <h2 class="mb-0 text-success"><?php echo isset($totalDrivers) ? $totalDrivers : 0; ?></h2>
                           <small class="text-muted">
                               <span class="text-success"><?php echo isset($activeDrivers) ? $activeDrivers : 0; ?></span> Active
                           </small>
                       </div>
                       <div class="text-success" style="font-size: 48px; opacity: 0.2;">
                           <i class="fas fa-car"></i>
                       </div>
                   </div>
               </div>
           </div>
       </div>
       <div class="col-md-4 mb-3">
           <div class="card border-info shadow-sm">
               <div class="card-body">
                   <div class="d-flex align-items-center justify-content-between">
                       <div>
                           <h6 class="text-muted mb-2">Total Bookings</h6>
                           <h2 class="mb-0 text-info"><?php echo isset($totalBookings) ? $totalBookings : 0; ?></h2>
                           <small class="text-muted">
                               <span class="text-success"><?php echo isset($completedBookings) ? $completedBookings : 0; ?></span> Completed | 
                               <span class="text-warning"><?php echo isset($pendingBookings) ? $pendingBookings : 0; ?></span> Pending
                           </small>
                       </div>
                       <div class="text-info" style="font-size: 48px; opacity: 0.2;">
                           <i class="fas fa-calendar-check"></i>
                       </div>
                   </div>
               </div>
           </div>
       </div>
   </div>

   <!-- Booking Statistics Section -->
   <?php if (isset($stats)): ?>
   <div class="row mb-4">
       <div class="col-md-12">
           <div class="card shadow">
               <div class="card-header bg-primary text-white">
                   <h5 class="mb-0">Booking Operations Overview</h5>
               </div>
               <div class="card-body">
                   <div class="row">
                       <!-- Bookings Today/Week/Month -->
                       <div class="col-md-3 mb-3">
                           <div class="card border-primary shadow-sm h-100">
                               <div class="card-body text-center">
                                   <div class="mb-2">
                                       <i class="fas fa-calendar-day text-primary" style="font-size: 2rem;"></i>
                                   </div>
                                   <h6 class="text-muted mb-2">Bookings Today</h6>
                                   <h3 class="text-primary mb-2"><?php echo isset($stats['ordersToday']) ? $stats['ordersToday'] : 0; ?></h3>
                                   <small class="text-muted d-block">
                                       <i class="fas fa-dollar-sign me-1"></i>
                                       <?php echo isset($stats['revenueToday']) ? number_format($stats['revenueToday'], 2) : '0.00'; ?>
                                   </small>
                               </div>
                           </div>
                       </div>
                       <div class="col-md-3 mb-3">
                           <div class="card border-success shadow-sm h-100">
                               <div class="card-body text-center">
                                   <div class="mb-2">
                                       <i class="fas fa-calendar-week text-success" style="font-size: 2rem;"></i>
                                   </div>
                                   <h6 class="text-muted mb-2">Bookings This Week</h6>
                                   <h3 class="text-success mb-2"><?php echo isset($stats['ordersWeek']) ? $stats['ordersWeek'] : 0; ?></h3>
                                   <small class="text-muted d-block">
                                       <i class="fas fa-dollar-sign me-1"></i>
                                       <?php echo isset($stats['revenueWeek']) ? number_format($stats['revenueWeek'], 2) : '0.00'; ?>
                                   </small>
                               </div>
                           </div>
                       </div>
                       <div class="col-md-3 mb-3">
                           <div class="card border-info shadow-sm h-100">
                               <div class="card-body text-center">
                                   <div class="mb-2">
                                       <i class="fas fa-calendar-alt text-info" style="font-size: 2rem;"></i>
                                   </div>
                                   <h6 class="text-muted mb-2">Bookings This Month</h6>
                                   <h3 class="text-info mb-2"><?php echo isset($stats['ordersMonth']) ? $stats['ordersMonth'] : 0; ?></h3>
                                   <small class="text-muted d-block">
                                       <i class="fas fa-dollar-sign me-1"></i>
                                       <?php echo isset($stats['revenueMonth']) ? number_format($stats['revenueMonth'], 2) : '0.00'; ?>
                                   </small>
                               </div>
                           </div>
                       </div>
                       <div class="col-md-3 mb-3">
                           <div class="card border-warning shadow-sm h-100">
                               <div class="card-body text-center">
                                   <div class="mb-2">
                                       <i class="fas fa-user-check text-warning" style="font-size: 2rem;"></i>
                                   </div>
                                   <h6 class="text-muted mb-2">Active Drivers</h6>
                                   <h3 class="text-warning mb-2"><?php echo isset($stats['activeDrivers']) ? $stats['activeDrivers'] : (isset($activeDrivers) ? $activeDrivers : 0); ?></h3>
                                   <small class="text-muted d-block">
                                       Total: <?php echo isset($stats['totalDrivers']) ? $stats['totalDrivers'] : (isset($totalDrivers) ? $totalDrivers : 0); ?>
                                   </small>
                               </div>
                           </div>
                       </div>
                   </div>
                   
                   <div class="row mt-3">
                       <!-- Booking Status -->
                       <div class="col-md-4 mb-3">
                           <div class="card border-danger shadow-sm h-100">
                               <div class="card-body text-center">
                                   <div class="mb-2">
                                       <i class="fas fa-clock text-danger" style="font-size: 2rem;"></i>
                                   </div>
                                   <h6 class="text-muted mb-2">Pending Bookings</h6>
                                   <h3 class="text-danger"><?php echo isset($stats['pendingDeliveries']) ? $stats['pendingDeliveries'] : 0; ?></h3>
                               </div>
                           </div>
                       </div>
                       <div class="col-md-4 mb-3">
                           <div class="card border-success shadow-sm h-100">
                               <div class="card-body text-center">
                                   <div class="mb-2">
                                       <i class="fas fa-check-circle text-success" style="font-size: 2rem;"></i>
                                   </div>
                                   <h6 class="text-muted mb-2">Completed Bookings</h6>
                                   <h3 class="text-success"><?php echo isset($stats['completedDeliveries']) ? $stats['completedDeliveries'] : 0; ?></h3>
                               </div>
                           </div>
                       </div>
                       <div class="col-md-4 mb-3">
                           <div class="card border-secondary shadow-sm h-100">
                               <div class="card-body text-center">
                                   <div class="mb-2">
                                       <i class="fas fa-chart-pie text-secondary" style="font-size: 2rem;"></i>
                                   </div>
                                   <h6 class="text-muted mb-3">Booking Overview</h6>
                                   <div class="row">
                                       <div class="col-6">
                                           <small class="text-muted d-block mb-1">Completed</small>
                                           <h5 class="text-success mb-0"><?php echo isset($stats['completedBookings']) ? $stats['completedBookings'] : (isset($completedBookings) ? $completedBookings : 0); ?></h5>
                                       </div>
                                       <div class="col-6">
                                           <small class="text-muted d-block mb-1">Pending</small>
                                           <h5 class="text-warning mb-0"><?php echo isset($stats['pendingBookings']) ? $stats['pendingBookings'] : (isset($pendingBookings) ? $pendingBookings : 0); ?></h5>
                                       </div>
                                   </div>
                               </div>
                           </div>
                       </div>
                   </div>
                   
                   <!-- Revenue by City -->
                   <?php if (!empty($stats['revenueByCity'])): ?>
                   <div class="row mt-3">
                       <div class="col-md-12">
                           <h6 class="mb-3"><i class="fas fa-map-marker-alt me-2"></i>Bookings & Revenue by City</h6>
                           <div class="table-responsive">
                               <table class="table table-hover table-sm">
                                   <thead class="table-light">
                                       <tr>
                                           <th><i class="fas fa-city me-1"></i>City</th>
                                           <th class="text-center"><i class="fas fa-calendar-check me-1"></i>Bookings</th>
                                           <th class="text-end"><i class="fas fa-dollar-sign me-1"></i>Revenue</th>
                                           <th class="text-center"><i class="fas fa-car me-1"></i>Active Drivers</th>
                                       </tr>
                                   </thead>
                                   <tbody>
                                       <?php foreach ($stats['revenueByCity'] as $cityName => $revenue): ?>
                                       <tr>
                                           <td><strong><?php echo htmlspecialchars($cityName); ?></strong></td>
                                           <td class="text-center"><?php echo isset($stats['ordersByCity'][$cityName]) ? $stats['ordersByCity'][$cityName] : 0; ?></td>
                                           <td class="text-end"><strong>$<?php echo number_format($revenue, 2); ?></strong></td>
                                           <td class="text-center"><?php echo isset($stats['driversByCity'][$cityName]) ? $stats['driversByCity'][$cityName] : 0; ?></td>
                                       </tr>
                                       <?php endforeach; ?>
                                   </tbody>
                               </table>
                           </div>
                       </div>
                   </div>
                   <?php endif; ?>
               </div>
           </div>
       </div>
   </div>
   <?php endif; ?>

   <!-- Recent Bookings Chart -->

   <!-- Booking Trends Chart -->
   <div class="row my-4">
       <div class="col-md-12">
           <div class="card shadow-sm">
               <div class="card-header bg-gradient-primary text-white d-flex justify-content-between align-items-center">
                   <h5 class="mb-0"><i class="fas fa-chart-area me-2"></i>Booking Trends (Last 7 Days)</h5>
                   <div class="dropdown">
                       <button class="btn btn-sm btn-light dropdown-toggle" type="button" data-bs-toggle="dropdown"
                           aria-expanded="false">
                           <i class="fas fa-filter me-1"></i>Filter
                       </button>
                       <ul class="dropdown-menu dropdown-menu-end">
                           <li><a class="dropdown-item" href="#" onclick="updateChartPeriod('7'); return false;"><i class="fas fa-calendar-week me-2"></i>Last 7 Days</a></li>
                           <li><a class="dropdown-item" href="#" onclick="updateChartPeriod('30'); return false;"><i class="fas fa-calendar-alt me-2"></i>Last 30 Days</a></li>
                           <li><a class="dropdown-item" href="#" onclick="updateChartPeriod('custom'); return false;"><i class="fas fa-calendar-check me-2"></i>Custom Range</a></li>
                       </ul>
                   </div>
               </div>
               <div class="card-body">
                   <div id="bookingChart"></div>
               </div>
           </div>
       </div>
   </div>

   <!-- Custom Date Range Modal -->
   <div class="modal fade" id="dateRangeModal" tabindex="-1" aria-labelledby="dateRangeModalLabel"
       aria-hidden="true">
       <div class="modal-dialog">
           <div class="modal-content">
               <div class="modal-header">
                   <h5 class="modal-title" id="dateRangeModalLabel"><i class="fas fa-calendar-alt me-2"></i>Select Custom Date Range</h5>
                   <button type="button" class="btn-close" data-bs-dismiss="modal"
                       aria-label="Close"></button>
               </div>
               <div class="modal-body">
                   <label class="form-label">Date Range</label>
                   <input class="form-control" type="text" id="dateRangePicker">
               </div>
               <div class="modal-footer">
                   <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                   <button type="button" class="btn btn-primary" onclick="applyCustomDateRange();">Apply Filter</button>
               </div>
           </div>
       </div>
   </div>
   <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
   <script>
       // Booking chart data
       var dateArray = <?php echo isset($datearray) && !empty($datearray) ? json_encode(array_reverse($datearray)) : '[]'; ?>;
       var bookingCompleteArray = <?php echo isset($bookingcomplete) && !empty($bookingcomplete) ? json_encode($bookingcomplete) : '{}'; ?>;
       var totalsaleArray = <?php echo isset($totalsale) && !empty($totalsale) ? json_encode($totalsale) : '{}'; ?>;
       
       // Prepare data arrays in chronological order (oldest to newest)
       var bookingCompleteValues = [];
       var revenueValues = [];
       var formattedDates = [];
       
       // Sort dates chronologically and extract values
       if (dateArray && dateArray.length > 0) {
           // dateArray is already reversed to be chronological (oldest to newest)
           dateArray.forEach(function(date) {
               // Format date for display
               var d = new Date(date + 'T00:00:00'); // Add time to ensure correct timezone handling
               formattedDates.push(d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }));
               
               // Get values for this date
               bookingCompleteValues.push(bookingCompleteArray[date] || 0);
               revenueValues.push(parseFloat(totalsaleArray[date]) || 0);
           });
       }

       // Initialize booking trends chart
       var bookingChartOptions = {
           series: [{
               name: 'Completed Bookings',
               type: 'column',
               data: bookingCompleteValues.length > 0 ? bookingCompleteValues : [0],
               color: '#667eea'
           }, {
               name: 'Revenue ($)',
               type: 'line',
               data: revenueValues.length > 0 ? revenueValues : [0],
               color: '#48bb78'
           }],
           chart: {
               height: 380,
               type: 'line',
               toolbar: {
                   show: true,
                   tools: {
                       download: true,
                       selection: false,
                       zoom: true,
                       zoomin: true,
                       zoomout: true,
                       pan: false,
                       reset: true
                   }
               },
               fontFamily: 'Inter, sans-serif'
           },
           stroke: {
               width: [0, 3],
               curve: ['straight', 'smooth']
           },
           plotOptions: {
               bar: {
                   columnWidth: '60%',
                   borderRadius: 6,
                   dataLabels: {
                       position: 'top'
                   }
               }
           },
           dataLabels: {
               enabled: true,
               enabledOnSeries: [0],
               formatter: function(val) {
                   return val > 0 ? val : '';
               },
               offsetY: -20,
               style: {
                   fontSize: '12px',
                   colors: ['#667eea']
               }
           },
           labels: formattedDates,
           xaxis: {
               type: 'category',
               categories: formattedDates,
               labels: {
                   style: {
                       fontSize: '12px',
                       fontFamily: 'Inter, sans-serif'
                   }
               }
           },
           yaxis: [{
               title: {
                   text: 'Bookings',
                   style: {
                       color: '#667eea',
                       fontSize: '14px',
                       fontFamily: 'Inter, sans-serif',
                       fontWeight: 600
                   }
               },
               labels: {
                   style: {
                       colors: '#667eea'
                   }
               }
           }, {
               opposite: true,
               title: {
                   text: 'Revenue ($)',
                   style: {
                       color: '#48bb78',
                       fontSize: '14px',
                       fontFamily: 'Inter, sans-serif',
                       fontWeight: 600
                   }
               },
               labels: {
                   style: {
                       colors: '#48bb78'
                   },
                   formatter: function(val) {
                       return '$' + val.toFixed(0);
                   }
               }
           }],
           legend: {
               position: 'top',
               horizontalAlign: 'right',
               fontSize: '14px',
               fontFamily: 'Inter, sans-serif',
               markers: {
                   width: 12,
                   height: 12,
                   radius: 6
               }
           },
           grid: {
               borderColor: '#e5e7eb',
               strokeDashArray: 4,
               xaxis: {
                   lines: {
                       show: false
                   }
               },
               yaxis: {
                   lines: {
                       show: true
                   }
               }
           },
           tooltip: {
               shared: true,
               intersect: false,
               style: {
                   fontSize: '13px',
                   fontFamily: 'Inter, sans-serif'
               },
               y: {
                   formatter: function(val, { seriesIndex }) {
                       if (seriesIndex === 0) {
                           return val + ' bookings';
                       } else {
                           return '$' + val.toFixed(2);
                       }
                   }
               }
           }
       };

       // Initialize chart only if we have data
       var bookingChart;
       if (formattedDates.length > 0) {
           bookingChart = new ApexCharts(document.querySelector("#bookingChart"), bookingChartOptions);
           bookingChart.render();
       } else {
           // Show message if no data available
           document.querySelector("#bookingChart").innerHTML = '<div class="text-center p-5"><i class="fas fa-chart-line fa-3x text-muted mb-3"></i><p class="text-muted">No booking data available for the selected period</p></div>';
       }

       // Date range picker initialization (requires moment.js and daterangepicker)
       $(function() {
           if ($.fn.daterangepicker && typeof moment !== 'undefined') {
               $('#dateRangePicker').daterangepicker({
                   opens: 'left',
                   locale: {
                       format: 'YYYY-MM-DD'
                   },
                   startDate: moment().subtract(6, 'days'),
                   endDate: moment()
               });
           }
       });

       // Update chart period
       function updateChartPeriod(period) {
           if (period === 'custom') {
               $('#dateRangeModal').modal('show');
               return;
           }
           // Update chart with new period
           // This would typically make an AJAX call to fetch new data
           console.log('Updating chart for period: ' + period);
       }

       // Apply custom date range
       function applyCustomDateRange() {
           var dates = $('#dateRangePicker').data('daterangepicker');
           var startDate = dates.startDate.format('YYYY-MM-DD');
           var endDate = dates.endDate.format('YYYY-MM-DD');
           // Update chart with custom date range
           // This would typically make an AJAX call to fetch new data
           console.log('Applying custom date range:', startDate, 'to', endDate);
           $('#dateRangeModal').modal('hide');
       }
   </script>

   <style>
       .bg-gradient-primary {
           background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
       }
       #bookingChart .apexcharts-toolbar {
           display: flex;
       }
   </style>