<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Dashboard</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" />
  <link rel="stylesheet" href="/css/dashstyle.css" />

  <style>
    body>script+div[style^="text"] {
      display: none
    }

    html,
    body {
      overflow-x: hidden !important
    }
  </style>
</head>

<body>
  <!-- Sidebar -->
  <aside class="sidebar" id="sidebar">
    <div class="logo">
      <a href="/dashboard" style="font-size: 30px; font-weight: bold; text-decoration: none; color: orangered;">Dashboard</a>
    </div>

    <nav class="nav-menu" aria-label="Main navigation">
      <a href="/" class="nav-item active"><i class="fas fa-table"></i><span>Orders</span></a>
      <a href="/edit-reservations" class="nav-item"><i class="fa-solid fa-clipboard"></i><span>Table Bookings</span></a>
      <a href="/add-items" class="nav-item"><i class="fa-solid fa-bowl-food"></i><span>Add Items</span></a>
      <a href="/edit-reviews" class="nav-item"><i class="fa-solid fa-comment"></i><span>Edit Reviews</span></a>
      <a href="/qr-form" class="nav-item"><i class="fa-solid fa-qrcode"></i><span>Barcode</span></a>
    </nav>

    <div class="premium-box">
      <h3>Facing problem..! Call : 9026257744</h3>
      <button class="premium-btn"><a href="tel:+919026257744" style="text-decoration: none; color: orangered;">Call Now</a></button>
    </div>
  </aside>

  <!-- Main Content -->
  <main class="main-content">
    <!-- Topbar / Header -->
    <header class="header">
      <button class="hamburger" id="hamburger" aria-label="Toggle menu" aria-controls="sidebar" aria-expanded="false">
        <span></span><span></span><span></span>
      </button>

      <div class="welcome-section">
        <p class="greeting">👋 <%= greeting %>, <%= customerName %>!</p>
        <h1 class="welcome-title">Daily Overview</h1>
      </div>

      <div class="header-right">
        <div class="search-bar">
         <form method="get" action="/dashboard" style="display:flex;">
                <i class="fas fa-search" style="color:#666; margin-right:8px;"></i>
                <input type="text" name="search" placeholder="Table Number, Total, Item Name" value="<%= search || '' %>"  aria-label="Search" id="orderSearch" />
            </form>
        </div>

        <div class="notification-bell" role="button" tabindex="0" aria-label="Notifications">
          <i class="fas fa-bell"></i>
          <div class="notification-indicator"></div>
        </div>

        <a class="btn btn-light" href="/logout">Logout</a>
        <a class="btn btn-primary" href="/user-profile">Settings</a>

        <div class="user-profile" title="Alex Morgan">
          <img src="https://i.pravatar.cc/100?img=8" alt="Alex Morgan" class="profile-pic" />
        </div>
      </div>
    </header>

    <!-- Dashboard Container -->
    <div class="dashboard-container">
      <!-- Main Dashboard Content -->
      <section class="dashboard-main">
        <!-- 4 cards in one row -->
        <div class="transfer-cards">
          <div class="transfer-card">
            <div class="card-icon"><i class="fas fa-money-check-alt"></i></div>
            <p class="card-title">Today's Earning</p>
            <h2 class="card-amount"><%= todayEarnings.toFixed(2) %></h2>
            <span class="<%= earningsChangePercent >= 0 ? 'text-success' : 'text-danger' %>" style="color: orangered;" >
    (<%= earningsChangePercent %>% <%= earningsChangePercent >= 0 ? '↑' : '↓' %>)
  </span>
          </div>
          <div class="transfer-card">
            <div class="card-icon"><i class="fas fa-exchange-alt"></i></div>
            <p class="card-title">Today's Orders</p>
            <h2 class="card-amount">
              <%= totalOrdersToday %>
            </h2>
            <span class="<%= ordersChangePercent >= 0 ? 'text-success' : 'text-danger' %>" style="color: orangered;">
    (<%= ordersChangePercent %>% <%= ordersChangePercent >= 0 ? '↑' : '↓' %>)
  </span>
          </div>
          <div class="transfer-card">
            <div class="card-icon"><i class="fas fa-briefcase"></i></div>
            <p class="card-title">Today's Bookings</p>
            <h2 class="card-amount">
              <%= totalReservationsToday %>
            </h2>
          </div>
          <div class="transfer-card">
            <div class="card-icon"><i class="fas fa-user"></i></div>
            <p class="card-title">Today's Reviews</p>
            <h2 class="card-amount">
              <%= totalReviewsToday %>
            </h2>
          </div>
        </div>

        <!-- Orders table (full width, same line-up as cards) -->
        <section class="card">
          <div class="card-header">
            <h2 class="section-title">Your Orders</h2>
            <div class="table-actions">
              <a href="/download/orders" style="color: black;"><i class="fas fa-file-excel"
                  style="cursor: pointer; font-size: 20px; padding: 5px;"></i></a>
              <a href="#" style="color: black;"><i class="fa-brands fa-whatsapp"
                  style="cursor: pointer; font-size: 20px; padding: 5px;"></i></a>
            </div>
          </div>

          <div class="table-responsive" id="ordersTable">
            <% if (orders.length> 0) { %>
              <table class="table" id="ordersTable">
                <thead>
                  <tr>
                    <th>Table</th>
                    <th>Offer</th>
                    <th>Items</th>
                    <th>Subtotal</th>
                    <th>Tax</th>
                    <th>Total</th>
                    <th>Created At</th>
                    <th class="text-right">Action</th>
                  </tr>
                </thead>
                <% const whatsappNumber="919807679767" ; %>

                  <tbody>
                    <% orders.forEach(order=> {
                      const message = `
                      *New Order*

                      *Table Number:* ${order.tableNumber}

                      *Items:*
                      ${order.items.map(item => `- ${item.name} x${item.quantity}`).join('\n')}

                      *Time:* ${new Date(order.createdAt).toLocaleString()}
                      `.trim();

                      const encodedMessage = encodeURIComponent(message);
                      %>
                      <tr>
                        <td data-label="Customer">
                          <%= order.tableNumber %>
                          
                        </td>
                        <td data-label="Total">
                          <%= order.offer %>
                        </td>
                        <td>
                          <ul>
                            <% order.items.forEach(item=> { %>
                              <li>
                                <strong>
                                  <%= item.name %>
                                </strong> -
                                Qty: <%= item.quantity %>,
                                  ₹<%= item.price %> <br />

                              </li>
                              <% }) %>
                          </ul>
                        </td>
                        <td>₹<%= order.subtotal %>
                        </td>
                        <td>₹<%= order.tax %>
                        </td>
                        <td>₹<%= order.total %>
                        </td>
                        <td>
                          <%= new Date(order.created_at).toLocaleString() %>
                        </td>
                        <td style="text-align: center;">
                          <div style="display: flex; justify-content: center; gap: 5px;">
                            <button class="btn btn-sm btn-primary">
                              <i class="fas fa-bell"></i>
                            </button>

                            <a href="https://wa.me/<%= whatsappNumber %>?text=<%= encodedMessage %>"
                              class="btn btn-sm btn-light" style="color: green;" target="_blank"
                              title="Send via WhatsApp">
                              <i class="fa-brands fa-whatsapp" style="cursor: pointer; font-size: 20px;"></i>
                            </a>

                            <a href="#" onclick="const printWindow = window.open('/bill/<%= order._id %>', '_blank', 'width=400,height=600');
                              printWindow.onload = function() {printWindow.print();};"
                              class="btn btn-sm btn-light" style="color: green;" target="_blank"
                              title="Generate Bill">
                              <i class="fas fa-money-bill" style="cursor: pointer; font-size: 20px;"></i>
                            </a>
                            
                            <a href="/orders/delete/<%= order._id %>" class="btn btn-sm btn-light"
                              onclick="return confirm('Are you sure you want to delete this item?')">
                              <i class="fas fa-trash"></i>
                            </a>
                            
                          </div>
                        </td>
                      </tr>
                      <% }) %>
                  </tbody>
              </table>
              <% } else { %>
                <div style="text-align: center; margin-bottom: 50px;">
                  <h1>No Orders Found</h1>
                </div>
                <% } %>
          </div>
        </section>

      </section>
    </div>
  </main>

  <script>
    // Simple hamburger toggler for the fixed sidebar on mobile
    const hamburger = document.getElementById('hamburger');
    const sidebar = document.getElementById('sidebar');
    if (hamburger && sidebar) {
      hamburger.addEventListener('click', () => {
        const open = sidebar.classList.toggle('open');
        hamburger.setAttribute('aria-expanded', String(open));
      });
    }
  </script>

  <script>
    // Get user's timezone automatically
    //const userTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;

    // Redirect or fetch dashboard data including timezone param
    // If your dashboard page itself loads data on server render, redirect with tz param:

    //if (!window.location.search.includes('tz=')) {
     // const url = new URL(window.location.href);
     // url.searchParams.set('tz', userTimezone);
     // window.location.replace(url.toString());
    //}

    // Alternatively, if you want to fetch JSON data asynchronously, do:
    /*
    fetch('/dashboard?tz=' + encodeURIComponent(userTimezone))
      .then(res => res.json())
      .then(data => {
        // Update dashboard UI dynamically here
        console.log(data);
      });
    */
  </script>

  <!-----I used this script to hide time zone from addressbar & read it from cookie and hide above script -->
    <script>
    (function () {
      const cookies = document.cookie;
      const hasTimezone = cookies.includes('timezone=');

      if (!hasTimezone) {
        const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
        document.cookie = `timezone=${tz}; path=/`;
        location.reload(); // Page will reload after setting cookie
      }
    })();
    </script>

    <!--Ajax Search Script-->
  <script>
    const searchBox = document.getElementById("orderSearch");
    let typingTimer;

    searchBox.addEventListener("input", function () {
      clearTimeout(typingTimer);
      typingTimer = setTimeout(() => {
        const value = searchBox.value.trim();

        fetch("/dashboard?search=" + encodeURIComponent(value), {
          headers: { "X-Requested-With": "XMLHttpRequest" }
        })
        .then(res => res.text())
        .then(html => {
          // Parse the returned HTML and extract the table part only
          const parser = new DOMParser();
          const doc = parser.parseFromString(html, "text/html");
          const newTable = doc.querySelector("#ordersTable"); 

          // Replace only the table, not the whole page
          document.querySelector("#ordersTable").innerHTML = newTable.innerHTML;
        });
      }, 400); // triggers after user stops typing for 0.4s
    });
  </script>
   
    
</body>
</html>