<div class="min-h-screen bg-gray-50 p-4 md:p-6">
  <div class="max-w-7xl mx-auto">
    <div class="flex flex-col lg:flex-row gap-6">
      <!-- Left Column - Order Items Data -->
      <!--<div class="w-full lg:w-1/2 bg-white rounded-xl shadow-md overflow-hidden">-->
      <!--  <div class="p-6">-->
      <!--    <h1 class="text-2xl font-bold text-gray-800 mb-6">Order Items Analytics</h1>-->
          
          <!-- Tabs Navigation -->
      <!--    <div class="flex justify-center space-x-2 mb-6">-->
      <!--      <button class="tab-button active px-4 py-2 rounded-lg font-medium transition-all" data-tab="types">-->
      <!--        Item Types-->
      <!--      </button>-->
      <!--      <button class="tab-button px-4 py-2 rounded-lg font-medium transition-all" data-tab="names">-->
      <!--        Item Names-->
      <!--      </button>-->
      <!--    </div>-->
          
          <!-- Tab Contents -->
      <!--    <div class="space-y-8">-->
            <!-- Types Tab -->
      <!--      <div id="types" class="tab-content active">-->
      <!--        <div class="space-y-6">-->
      <!--          <h2 class="text-xl font-semibold text-gray-700 text-center">Item Types Distribution</h2>-->
      <!--          <div class="relative h-80 md:h-96">-->
      <!--            <canvas id="itemTypesChart"></canvas>-->
      <!--          </div>-->
                
      <!--          <div class="space-y-4">-->
      <!--            <h2 class="text-xl font-semibold text-gray-700 text-center">Item Types Data</h2>-->
      <!--            <div class="overflow-x-auto">-->
      <!--              <table id="itemTypesTable" class="w-full border-collapse">-->
      <!--                <thead>-->
      <!--                  <tr class="bg-gray-100">-->
      <!--                    <th class="p-3 text-left text-gray-700 font-medium">Type</th>-->
      <!--                    <th class="p-3 text-left text-gray-700 font-medium">Total Quantity</th>-->
      <!--                  </tr>-->
      <!--                </thead>-->
      <!--                <tbody class="divide-y divide-gray-200">-->
                        <!-- Data will be inserted here -->
      <!--                </tbody>-->
      <!--              </table>-->
      <!--            </div>-->
      <!--            <div id="paginationTypes" class="flex justify-center space-x-2 mt-4">-->
                    <!-- Pagination will be generated here -->
      <!--            </div>-->
      <!--          </div>-->
      <!--        </div>-->
      <!--      </div>-->
            
            <!-- Names Tab -->
      <!--      <div id="names" class="tab-content hidden">-->
      <!--        <div class="space-y-6">-->
      <!--          <h2 class="text-xl font-semibold text-gray-700 text-center">Item Names Distribution</h2>-->
      <!--          <div class="relative h-80 md:h-96">-->
      <!--            <canvas id="itemNamesChart"></canvas>-->
      <!--          </div>-->
                
      <!--          <div class="space-y-4">-->
      <!--            <h2 class="text-xl font-semibold text-gray-700 text-center">Item Names Data</h2>-->
      <!--            <div class="overflow-x-auto">-->
      <!--              <table id="itemNamesTable" class="w-full border-collapse">-->
      <!--                <thead>-->
      <!--                  <tr class="bg-gray-100">-->
      <!--                    <th class="p-3 text-left text-gray-700 font-medium">Name</th>-->
      <!--                    <th class="p-3 text-left text-gray-700 font-medium">Total Quantity</th>-->
      <!--                  </tr>-->
      <!--                </thead>-->
      <!--                <tbody class="divide-y divide-gray-200">-->
                        <!-- Data will be inserted here -->
      <!--                </tbody>-->
      <!--              </table>-->
      <!--            </div>-->
      <!--            <div id="paginationNames" class="flex justify-center space-x-2 mt-4">-->
                    <!-- Pagination will be generated here -->
      <!--            </div>-->
      <!--          </div>-->
      <!--        </div>-->
      <!--      </div>-->
      <!--    </div>-->
      <!--  </div>-->
      <!--</div>-->
      
      <!-- Right Column - Order Active Hours -->
      <div class="w-full lg:w-1/2 bg-white rounded-xl shadow-md overflow-hidden">
        <div class="p-6">
          <h1 class="text-2xl font-bold text-gray-800 mb-6">Order Activity Timeline</h1>
          
          <div class="space-y-6">
            <!-- Filters -->
            <div class="flex flex-col sm:flex-row items-center gap-4 mb-6">
              <div class="flex items-center">
                <label for="yearSelect" class="mr-2 text-gray-700 font-medium">Year:</label>
                <select id="yearSelect" class="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                  <!-- Options will be populated dynamically -->
                </select>
              </div>
              
              <div class="flex items-center">
                <label for="monthSelect" class="mr-2 text-gray-700 font-medium">Month:</label>
                <select id="monthSelect" class="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                  <option value="0">January</option>
                  <option value="1">February</option>
                  <option value="2">March</option>
                  <option value="3">April</option>
                  <option value="4">May</option>
                  <option value="5">June</option>
                  <option value="6">July</option>
                  <option value="7">August</option>
                  <option value="8">September</option>
                  <option value="9">October</option>
                  <option value="10">November</option>
                  <option value="11">December</option>
                </select>
              </div>
              
              <button id="filterButton" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
                Filter
              </button>
            </div>
            
            <!-- Peak Hours Info -->
            <div id="highestOrdersHeading" class="text-center p-4 bg-blue-50 rounded-lg border border-blue-100 text-blue-800 font-medium">
              <!-- Peak hours info will be inserted here -->
            </div>
            
            <!-- Chart -->
            <div class="relative h-80 md:h-96">
              <canvas id="activeHoursChart"></canvas>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Loading Indicator -->
<div id="loadingIndicator" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
  <div class="bg-white p-6 rounded-lg shadow-xl flex flex-col items-center">
    <div class="w-12 h-12 border-4 border-blue-500 border-t-transparent rounded-full animate-spin mb-4"></div>
    <p class="text-gray-700 font-medium">Loading data...</p>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  // Enhanced JavaScript with proper styling and functionality
  document.addEventListener('DOMContentLoaded', function() {
    // Tab functionality
    const tabButtons = document.querySelectorAll('.tab-button');
    tabButtons.forEach(button => {
      button.addEventListener('click', function() {
        const tabId = this.dataset.tab;
        
        // Update active tab button
        tabButtons.forEach(btn => btn.classList.remove('active', 'bg-blue-600', 'text-white'));
        this.classList.add('active', 'bg-blue-600', 'text-white');
        
        // Show the selected tab content
        document.querySelectorAll('.tab-content').forEach(content => {
          content.classList.add('hidden');
          content.classList.remove('active');
        });
        document.getElementById(tabId).classList.remove('hidden');
        document.getElementById(tabId).classList.add('active');
      });
    });

    // Initialize the first tab as active
    document.querySelector('.tab-button').click();
  });

  // Order Items Data Script
  const ITEMS_PER_PAGE = 5;

  async function fetchData() {
    try {
      showLoading();
      const response = await fetch('https://drycleaneo.com/admin/order_api');
      const data = await response.json();

      if (data.success) {
        const { typeCounts, nameCounts } = countItems(data);
        displayCharts(typeCounts, nameCounts);
        displayTables(typeCounts, nameCounts);
      } else {
        showError('Failed to fetch data from server');
      }
    } catch (error) {
      showError('Network error occurred. Please try again.');
      console.error('Error fetching data:', error);
    } finally {
      hideLoading();
    }
  }

  function countItems(apiData) {
    const typeCounts = {};
    const nameCounts = {};

    if (Array.isArray(apiData.allOrders)) {
      apiData.allOrders.forEach(order => {
        if (Array.isArray(order.Items)) {
          order.Items.forEach(item => {
            // Count item types
            typeCounts[item.type] = (typeCounts[item.type] || 0) + 1;

            // Count item names
            nameCounts[item.name] = (nameCounts[item.name] || 0) + item.quantity;
          });
        }
      });
    }

    return { typeCounts, nameCounts };
  }

  function generateColors(count) {
    const colors = [];
    const baseColors = [
      '#3B82F6', '#EF4444', '#10B981', '#F59E0B', '#6366F1', 
      '#EC4899', '#14B8A6', '#F97316', '#8B5CF6', '#F43F5E'
    ];
    for (let i = 0; i < count; i++) {
      colors.push(baseColors[i % baseColors.length]);
    }
    return colors;
  }

  function displayCharts(typeCounts, nameCounts) {
    const typeColors = generateColors(Object.keys(typeCounts).length);
    const nameColors = generateColors(Object.keys(nameCounts).length);

    // Item Types Chart
    const ctxTypes = document.getElementById('itemTypesChart').getContext('2d');
    new Chart(ctxTypes, {
      type: 'doughnut',
      data: {
        labels: Object.keys(typeCounts),
        datasets: [{
          data: Object.values(typeCounts),
          backgroundColor: typeColors,
          borderWidth: 1,
          hoverOffset: 10
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            position: 'right',
            labels: {
              font: {
                size: 12
              },
              padding: 20
            }
          },
          tooltip: {
            callbacks: {
              label: function(context) {
                return `${context.label}: ${context.raw} items`;
              }
            }
          }
        },
        cutout: '60%',
        animation: {
          animateScale: true,
          animateRotate: true
        }
      }
    });

    // Item Names Chart
    const ctxNames = document.getElementById('itemNamesChart').getContext('2d');
    new Chart(ctxNames, {
      type: 'doughnut',
      data: {
        labels: Object.keys(nameCounts),
        datasets: [{
          data: Object.values(nameCounts),
          backgroundColor: nameColors,
          borderWidth: 1,
          hoverOffset: 10
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            position: 'right',
            labels: {
              font: {
                size: 12
              },
              padding: 20
            }
          },
          tooltip: {
            callbacks: {
              label: function(context) {
                return `${context.label}: ${context.raw} items`;
              }
            }
          }
        },
        cutout: '60%',
        animation: {
          animateScale: true,
          animateRotate: true
        }
      }
    });
  }

  function displayTables(typeCounts, nameCounts) {
    populateTable('#itemTypesTable', typeCounts);
    paginateTable('#itemTypesTable', '#paginationTypes');

    populateTable('#itemNamesTable', nameCounts);
    paginateTable('#itemNamesTable', '#paginationNames');
  }

  function populateTable(tableSelector, data) {
    const tableBody = document.querySelector(`${tableSelector} tbody`);
    tableBody.innerHTML = '';
    
    Object.entries(data).forEach(([key, value]) => {
      const row = document.createElement('tr');
      row.className = 'hover:bg-gray-50';
      row.innerHTML = `
        <td class="p-3 text-gray-700">${key}</td>
        <td class="p-3 text-gray-700 font-medium">${value}</td>
      `;
      tableBody.appendChild(row);
    });
  }

  function paginateTable(tableSelector, paginationSelector) {
    const rows = document.querySelectorAll(`${tableSelector} tbody tr`);
    const totalPages = Math.ceil(rows.length / ITEMS_PER_PAGE);
    const paginationContainer = document.querySelector(paginationSelector);
    paginationContainer.innerHTML = '';

    for (let i = 1; i <= totalPages; i++) {
      const button = document.createElement('button');
      button.className = 'px-3 py-1 rounded-md border border-gray-300 hover:bg-gray-100';
      button.textContent = i;
      button.dataset.page = i;
      
      button.addEventListener('click', function() {
        changePage(i, tableSelector);
        
        // Update active pagination button
        document.querySelectorAll(`${paginationSelector} button`).forEach(btn => {
          btn.classList.remove('bg-blue-600', 'text-white');
        });
        this.classList.add('bg-blue-600', 'text-white');
      });
      
      if (i === 1) {
        button.classList.add('bg-blue-600', 'text-white');
      }
      
      paginationContainer.appendChild(button);
    }

    changePage(1, tableSelector);
  }

  function changePage(pageNumber, tableSelector) {
    const rows = document.querySelectorAll(`${tableSelector} tbody tr`);
    const start = (pageNumber - 1) * ITEMS_PER_PAGE;
    const end = start + ITEMS_PER_PAGE;

    rows.forEach((row, index) => {
      row.classList.toggle('hidden', index < start || index >= end);
    });
  }

  // Order Active Hours Script
  $(document).ready(function() {
    let orders = [];
    let ctx = document.getElementById('activeHoursChart').getContext('2d');
    let chart = new Chart(ctx, {
      type: 'line',
      data: {
        labels: ['12AM-3AM', '3AM-6AM', '6AM-9AM', '9AM-12PM', '12PM-3PM', '3PM-6PM', '6PM-9PM', '9PM-12AM'],
        datasets: [{
          label: 'Number of Orders',
          data: Array(8).fill(0),
          backgroundColor: 'rgba(59, 130, 246, 0.1)',
          borderColor: '#3B82F6',
          borderWidth: 2,
          tension: 0.3,
          fill: true,
          pointBackgroundColor: '#3B82F6',
          pointBorderColor: '#fff',
          pointRadius: 5,
          pointHoverRadius: 7,
          pointHoverBackgroundColor: '#fff',
          pointHoverBorderColor: '#3B82F6',
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
          y: {
            beginAtZero: true,
            grid: {
              color: 'rgba(229, 231, 235, 1)'
            },
            title: {
              display: true,
              text: 'Number of Orders',
              font: {
                weight: 'bold'
              }
            }
          },
          x: {
            grid: {
              display: false
            },
            title: {
              display: true,
              text: 'Time of Day',
              font: {
                weight: 'bold'
              }
            }
          }
        },
        plugins: {
          legend: {
            display: true,
            position: 'top',
            labels: {
              font: {
                size: 14,
                weight: 'bold'
              }
            }
          },
          tooltip: {
            callbacks: {
              label: function(context) {
                return `Orders: ${context.raw}`;
              }
            }
          }
        }
      }
    });

    // Set current date as default
    const now = new Date().toLocaleString("en-US", { timeZone: "Asia/Kolkata" });
    const currentDate = new Date(now);
    const currentYear = currentDate.getFullYear();
    const currentMonth = currentDate.getMonth();

    // Initialize data
    $.ajax({
      url: 'https://drycleaneo.com/admin/order_api',
      method: 'GET',
      dataType: 'json',
      beforeSend: function() {
        showLoading();
      },
      success: function(response) {
        if (response.success) {
          orders = response.allOrders;
          populateYearSelect();
          filterAndDisplayData();
        } else {
          showError('Failed to load order data');
        }
      },
      error: function() {
        showError('Network error loading order data');
      },
      complete: function() {
        hideLoading();
      }
    });

    function populateYearSelect() {
      const years = new Set();
      orders.forEach(order => {
        const date = new Date(order.created_at);
        years.add(date.getFullYear());
      });
      
      const yearSelect = $('#yearSelect');
      yearSelect.empty();
      
      Array.from(years).sort().forEach(year => {
        yearSelect.append(new Option(year, year));
      });
      
      yearSelect.val(currentYear);
      $('#monthSelect').val(currentMonth);
    }

    function filterAndDisplayData() {
      const selectedYear = parseInt($('#yearSelect').val());
      const selectedMonth = parseInt($('#monthSelect').val());
      
      const filteredOrders = orders.filter(order => {
        const date = new Date(order.created_at);
        return date.getFullYear() === selectedYear && date.getMonth() === selectedMonth;
      });

      const intervals = new Array(8).fill(0);
      filteredOrders.forEach(order => {
        const date = new Date(order.created_at);
        const hour = date.getHours();
        const index = Math.floor(hour / 3);
        intervals[index]++;
      });

      chart.data.datasets[0].data = intervals;
      chart.update();

      const maxOrders = Math.max(...intervals);
      const maxIndex = intervals.indexOf(maxOrders);
      const timeIntervals = [
        '12:00 AM - 3:00 AM', '3:00 AM - 6:00 AM', '6:00 AM - 9:00 AM', 
        '9:00 AM - 12:00 PM', '12:00 PM - 3:00 PM', '3:00 PM - 6:00 PM', 
        '6:00 PM - 9:00 PM', '9:00 PM - 12:00 AM'
      ];
      
      $('#highestOrdersHeading').html(`
        <span class="font-bold">Peak Order Time:</span> 
        ${maxOrders} orders were placed between ${timeIntervals[maxIndex]}
      `);
    }

    // Event handlers
    $('#filterButton, #yearSelect, #monthSelect').on('click change', filterAndDisplayData);
  });

  // Utility functions
  function showLoading() {
    document.getElementById('loadingIndicator').classList.remove('hidden');
  }

  function hideLoading() {
    document.getElementById('loadingIndicator').classList.add('hidden');
  }

  function showError(message) {
    const errorDiv = document.createElement('div');
    errorDiv.className = 'fixed top-4 right-4 p-4 bg-red-100 border-l-4 border-red-500 text-red-700 z-50 rounded-lg shadow-lg';
    errorDiv.innerHTML = `
      <div class="flex items-center">
        <svg class="w-6 h-6 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
        </svg>
        <span>${message}</span>
      </div>
    `;
    document.body.appendChild(errorDiv);
    
    setTimeout(() => {
      errorDiv.remove();
    }, 5000);
  }

  // Initialize the dashboard
  fetchData();
</script><?php /**PATH /home/u152672654/domains/drycleaneo.com/public_html/admin/resources/views/components/ana_sale.blade.php ENDPATH**/ ?>