<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Manage Cafe Orders</title>
  <style>
    :root {
      --primary-color: #00674F;
      --secondary-color: #28a745;
      --danger-color: #dc3545;
      --warning-color: #ffc107;
      --light-bg: #f8f9fa;
      --white: #ffffff;
      --text-dark: #2c3e50;
      --text-light: #6c757d;
      --border-color: #e9ecef;
      --shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      --shadow-hover: 0 4px 20px rgba(0, 0, 0, 0.15);
    }

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
      min-height: 100vh;
      color: var(--text-dark);
      line-height: 1.6;
    }

    .header {
      background: var(--white);
      padding: 2rem 0;
      box-shadow: var(--shadow);
      text-align: center;
    }

    h1 {
      color: var(--primary-color);
      font-size: 2.5rem;
      font-weight: 700;
      margin-bottom: 0.5rem;
    }

    .subtitle {
      color: var(--text-light);
      font-size: 1.1rem;
    }

    .container {
      max-width: 1200px;
      margin: 2rem auto;
      padding: 0 1rem;
    }

    .card {
      background: var(--white);
      border-radius: 16px;
      box-shadow: var(--shadow);
      padding: 2rem;
      margin-bottom: 2rem;
      transition: transform 0.3s ease, box-shadow 0.3s ease;
    }

    .card:hover {
      transform: translateY(-2px);
      box-shadow: var(--shadow-hover);
    }

    .quick-buttons {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
      gap: 1rem;
      margin-bottom: 2rem;
    }

    .quick-btn {
      background: var(--white);
      color: var(--text-dark);
      border: 2px solid var(--border-color);
      padding: 1rem;
      font-size: 0.9rem;
      font-weight: 600;
      border-radius: 12px;
      cursor: pointer;
      transition: all 0.3s ease;
      text-align: center;
      position: relative;
      overflow: hidden;
    }

    .quick-btn::before {
      content: '';
      position: absolute;
      top: 0;
      left: -100%;
      width: 100%;
      height: 100%;
      background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
      transition: left 0.5s;
    }

    .quick-btn:hover::before {
      left: 100%;
    }

    .quick-btn:hover {
      border-color: var(--primary-color);
      color: var(--primary-color);
      transform: translateY(-2px);
      box-shadow: var(--shadow);
    }

    .quick-btn.active {
      background: var(--primary-color);
      color: var(--white);
      border-color: var(--primary-color);
      box-shadow: 0 4px 15px rgba(0, 103, 79, 0.3);
    }

    .date-section {
      background: var(--light-bg);
      border-radius: 12px;
      padding: 1.5rem;
      margin-bottom: 2rem;
    }

    .filters {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 1.5rem;
      align-items: end;
    }

    .filter-group {
      display: flex;
      flex-direction: column;
    }

    .filter-group label {
      font-weight: 600;
      color: var(--text-dark);
      margin-bottom: 0.5rem;
      font-size: 0.9rem;
    }

    .filter-group input {
      padding: 0.75rem 1rem;
      font-size: 1rem;
      border: 2px solid var(--border-color);
      border-radius: 8px;
      transition: border-color 0.3s ease;
      background: var(--white);
    }

    .filter-group input:focus {
      outline: none;
      border-color: var(--primary-color);
      box-shadow: 0 0 0 3px rgba(0, 103, 79, 0.1);
    }

    .fetch-btn {
      background: var(--secondary-color);
      color: var(--white);
      border: none;
      padding: 0.75rem 2rem;
      font-size: 1rem;
      font-weight: 600;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.3s ease;
      height: fit-content;
    }

    .fetch-btn:hover {
      background: #218838;
      transform: translateY(-1px);
      box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
    }

    .orders-section {
      background: var(--white);
      border-radius: 12px;
      padding: 1.5rem;
      margin-bottom: 2rem;
    }

    .orders-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 1.5rem;
      padding-bottom: 1rem;
      border-bottom: 2px solid var(--border-color);
    }

    .orders-title {
      font-size: 1.5rem;
      font-weight: 700;
      color: var(--text-dark);
    }

    .orders-count {
      background: var(--primary-color);
      color: var(--white);
      padding: 0.5rem 1rem;
      border-radius: 20px;
      font-weight: 600;
      font-size: 0.9rem;
    }

    .orders-list {
      list-style: none;
      display: grid;
      gap: 1rem;
    }

    .orders-list li {
      background: var(--light-bg);
      border: 2px solid var(--border-color);
      border-radius: 12px;
      padding: 1.5rem;
      transition: all 0.3s ease;
      position: relative;
      overflow: hidden;
    }

    .orders-list li::before {
      content: '';
      position: absolute;
      left: 0;
      top: 0;
      bottom: 0;
      width: 4px;
      background: var(--primary-color);
    }

    .orders-list li:hover {
      border-color: var(--primary-color);
      transform: translateX(4px);
      box-shadow: var(--shadow);
    }

    .order-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-wrap: wrap;
      gap: 1rem;
    }

    .order-details {
      flex: 1;
      min-width: 200px;
    }

    .order-number {
      font-size: 1.2rem;
      font-weight: 700;
      color: var(--primary-color);
      margin-bottom: 0.5rem;
    }

    .order-status {
      display: inline-block;
      padding: 0.4rem 1rem;
      border-radius: 20px;
      font-size: 0.8rem;
      font-weight: 600;
      text-transform: uppercase;
      letter-spacing: 0.5px;
    }

    .status-paid {
      background: #d4edda;
      color: #155724;
    }

    .status-pending {
      background: #fff3cd;
      color: #856404;
    }

    .status-cancelled {
      background: #f8d7da;
      color: #721c24;
    }

    .delete-section {
      background: var(--white);
      border-radius: 12px;
      padding: 1.5rem;
      text-align: center;
      border: 2px dashed var(--danger-color);
    }

    .delete-btn {
      background: var(--danger-color);
      color: var(--white);
      border: none;
      padding: 1rem 2rem;
      font-size: 1rem;
      font-weight: 600;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.3s ease;
      position: relative;
      overflow: hidden;
    }

    .delete-btn::before {
      content: '';
      position: absolute;
      top: 0;
      left: -100%;
      width: 100%;
      height: 100%;
      background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
      transition: left 0.5s;
    }

    .delete-btn:hover::before {
      left: 100%;
    }

    .delete-btn:hover {
      background: #c82333;
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(220, 53, 69, 0.3);
    }

    .delete-btn:disabled {
      background: var(--text-light);
      cursor: not-allowed;
      transform: none;
      box-shadow: none;
    }

    .spinner {
      display: none;
      border: 4px solid var(--border-color);
      border-top: 4px solid var(--primary-color);
      border-radius: 50%;
      width: 50px;
      height: 50px;
      animation: spin 1s linear infinite;
      margin: 2rem auto;
    }

    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }

    .loading-text {
      text-align: center;
      font-weight: 600;
      color: var(--primary-color);
      font-size: 1.1rem;
      margin-top: 1rem;
    }

    .empty-state {
      text-align: center;
      padding: 3rem;
      color: var(--text-light);
    }

    .empty-state-icon {
      font-size: 4rem;
      margin-bottom: 1rem;
      opacity: 0.5;
    }

    .empty-state-text {
      font-size: 1.2rem;
      font-weight: 600;
    }

    @media (max-width: 768px) {
      .container {
        padding: 0 0.5rem;
      }

      .card {
        padding: 1.5rem;
      }

      .quick-buttons {
        grid-template-columns: repeat(2, 1fr);
        gap: 0.5rem;
      }

      .filters {
        grid-template-columns: 1fr;
        gap: 1rem;
      }

      .order-info {
        flex-direction: column;
        align-items: flex-start;
      }

      h1 {
        font-size: 2rem;
      }
    }
  </style>
</head>
<body>
  <div class="header">
  <h1>Manage Cafe Orders</h1>
    <p class="subtitle">View and manage orders by date range</p>
  </div>

  <div class="container">
    <!-- Quick Date Range Buttons -->
    <div class="card">
      <div class="quick-buttons">
        <button class="quick-btn" onclick="setQuickDateRange('yesterday')">📅 Yesterday</button>
        <button class="quick-btn" onclick="setQuickDateRange('week')">📆 Last Week</button>
        <button class="quick-btn" onclick="setQuickDateRange('month')">🗓️ Last Month</button>
        <button class="quick-btn" onclick="setQuickDateRange('3months')">📊 Last 3 Months</button>
        <button class="quick-btn" onclick="setQuickDateRange('custom')">⚙️ Custom Range</button>
      </div>
    </div>

    <!-- Date Selection Section -->
    <div class="card date-section">
    <div class="filters">
        <div class="filter-group">
          <label for="start-date">📅 Start Date</label>
        <input type="date" id="start-date">
      </div>
        <div class="filter-group">
          <label for="end-date">📅 End Date</label>
        <input type="date" id="end-date">
        </div>
        <button id="fetch-orders" class="fetch-btn">🔍 Fetch Orders</button>
      </div>
    </div>

    <!-- Orders Section -->
    <div class="card orders-section">
      <div class="orders-header">
        <h2 class="orders-title">📋 Orders Found</h2>
        <div class="orders-count" id="orders-count">0 orders</div>
    </div>

    <ul id="orders-list" class="orders-list">
      <!-- Orders will be dynamically added here -->
    </ul>
    </div>

    <!-- Delete Section -->
    <div class="card delete-section">
      <h3 style="color: var(--danger-color); margin-bottom: 1rem;">⚠️ Danger Zone</h3>
      <p style="color: var(--text-light); margin-bottom: 1.5rem;">This will permanently delete all orders in the selected date range</p>
      <button id="delete-all-orders" class="delete-btn" disabled>🗑️ Delete All Orders</button>
    </div>
  </div>

  <div id="loading-spinner" class="spinner"></div>
  <p id="loading-text" class="loading-text"></p>

  <script>
    const fetchOrdersButton = document.getElementById('fetch-orders');
    const deleteAllOrdersButton = document.getElementById('delete-all-orders');
    const ordersList = document.getElementById('orders-list');
    const loadingSpinner = document.getElementById('loading-spinner');
    const loadingText = document.getElementById('loading-text');
    const startDateInput = document.getElementById('start-date');
    const endDateInput = document.getElementById('end-date');
    const ordersCount = document.getElementById('orders-count');

    let fetchedOrders = []; // Store fetched orders
    let currentQuickRange = null; // Track current quick range selection

    // Show spinner and loading text
    function showLoading(message) {
      loadingSpinner.style.display = 'block';
      loadingText.innerText = message;
    }

    // Hide spinner and loading text
    function hideLoading() {
      loadingSpinner.style.display = 'none';
      loadingText.innerText = '';
    }

    // Automatically set startDate (10 days ago) and endDate (today)
    function setDefaultDates() {
      const today = new Date();
      const tenDaysAgo = new Date();
      tenDaysAgo.setDate(today.getDate() - 10);

      startDateInput.value = formatDate(tenDaysAgo);
      endDateInput.value = formatDate(today);
    }

    // Format a Date object as YYYY-MM-DD
    function formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    }

    // Set quick date ranges and fetch orders automatically
    function setQuickDateRange(range) {
      const today = new Date();
      let startDate, endDate;

      // Clear previous active state
      document.querySelectorAll('.quick-btn').forEach(btn => btn.classList.remove('active'));
      
      // Set the active button
      event.target.classList.add('active');
      currentQuickRange = range;

      switch (range) {
        case 'yesterday':
          const yesterday = new Date(today);
          yesterday.setDate(today.getDate() - 1);
          startDate = yesterday;
          endDate = yesterday;
          break;

        case 'week':
          const weekAgo = new Date(today);
          weekAgo.setDate(today.getDate() - 7);
          startDate = weekAgo;
          endDate = today;
          break;

        case 'month':
          const monthAgo = new Date(today);
          monthAgo.setMonth(today.getMonth() - 1);
          startDate = monthAgo;
          endDate = today;
          break;

        case '3months':
          const threeMonthsAgo = new Date(today);
          threeMonthsAgo.setMonth(today.getMonth() - 3);
          startDate = threeMonthsAgo;
          endDate = today;
          break;

        case 'custom':
          // Don't set dates for custom range, let user select manually
          currentQuickRange = null;
          return;
      }

      // Set the date inputs
      startDateInput.value = formatDate(startDate);
      endDateInput.value = formatDate(endDate);

      // Automatically fetch orders for the selected range
      fetchOrders();
    }

    // Fetch orders by time interval
    async function fetchOrders() {
      const startDate = startDateInput.value;
      const endDate = endDateInput.value;

      if (!startDate || !endDate) {
        alert('Please select both start and end dates.');
        return;
      }

      // Clear existing data immediately for better UX
      ordersList.innerHTML = '';
      fetchedOrders = [];

      try {
        showLoading('Fetching orders...');
        const response = await fetch(`/api/cafeorder/get-orders-admin?startDate=${startDate}&endDate=${endDate}`);
        const data = await response.json();

        if (data.success) {
          fetchedOrders = data.data; // Store fetched orders
          renderOrders(fetchedOrders);
          deleteAllOrdersButton.disabled = fetchedOrders.length === 0; // Enable delete button if orders exist
        } else {
          alert('Failed to fetch orders: ' + data.message);
        }
      } catch (error) {
        console.error('Error fetching orders:', error);
        alert('An error occurred while fetching orders.');
      } finally {
        hideLoading();
      }
    }

    // Render fetched orders
    function renderOrders(orders) {
      ordersList.innerHTML = ''; // Clear previous orders

      // Update orders count
      const count = orders.length;
      ordersCount.textContent = `${count} order${count !== 1 ? 's' : ''}`;

      if (orders.length === 0) {
        ordersList.innerHTML = `
          <div class="empty-state">
            <div class="empty-state-icon">📭</div>
            <div class="empty-state-text">No orders found for the selected date range</div>
          </div>
        `;
        return;
      }

      orders.forEach(order => {
        const orderItem = document.createElement('li');
        const statusClass = `status-${order.status.toLowerCase()}`;
        orderItem.innerHTML = `
          <div class="order-info">
            <div class="order-details">
              <div class="order-number">Order #${order.orderNo}</div>
              <span class="order-status ${statusClass}">${order.status}</span>
            </div>
          </div>
        `;
        ordersList.appendChild(orderItem);
      });
    }

    // Delete all orders and their details
    async function deleteAllOrders() {
  const startDate = startDateInput.value;
  const endDate = endDateInput.value;

  if (!startDate || !endDate) {
    alert('Please select both start and end dates.');
    return;
  }

  if (!confirm('Are you sure you want to delete all orders within the selected date range? This action cannot be undone.')) {
    return;
  }

  try {
    showLoading('Deleting all orders...');
    const response = await fetch(`/api/cafeorder/delete-all-orders`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ startDate, endDate }),
    });

    const data = await response.json();

    if (data.success) {
      alert('All orders and related details deleted successfully!');
      fetchedOrders = []; // Clear fetched orders
      renderOrders(fetchedOrders); // Re-render empty list
      deleteAllOrdersButton.disabled = true; // Disable delete button
    } else {
      alert('Failed to delete orders: ' + data.message);
    }
  } catch (error) {
    console.error('Error deleting orders:', error);
    alert('An error occurred while deleting orders.');
  } finally {
    hideLoading();
  }
}


    // Automatically fetch orders when the page loads
    document.addEventListener('DOMContentLoaded', () => {
      setDefaultDates();
      // Mark the default range as active (10 days ago to today is closest to "week")
      document.querySelectorAll('.quick-btn').forEach(btn => {
        if (btn.textContent === 'Last Week') {
          btn.classList.add('active');
          currentQuickRange = 'week';
        }
      });
      fetchOrders();
    });

    // Event listeners
    fetchOrdersButton.addEventListener('click', fetchOrders);
    deleteAllOrdersButton.addEventListener('click', deleteAllOrders);
    
    // Clear quick range selection when manually changing dates
    startDateInput.addEventListener('change', () => {
      document.querySelectorAll('.quick-btn').forEach(btn => btn.classList.remove('active'));
      currentQuickRange = null;
    });
    
    endDateInput.addEventListener('change', () => {
      document.querySelectorAll('.quick-btn').forEach(btn => btn.classList.remove('active'));
      currentQuickRange = null;
    });
  </script>
</body>
</html>
