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

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Dashboard - Items</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="/admin-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="/admin/add-customer" class="nav-item"><i class="fa-solid fa-user"></i><span>Add Customer</span></a>
    </nav>

    <div class="premium-box">
      <h3>Facing problem need Assistance!</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">Good afternoon, Alex,</p>
        <h1 class="welcome-title">Add Customers</h1>
      </div>

      <div class="header-right">
        <div class="search-bar">
          <form method="get" action="/add-items" style="display:flex;">
            <i class="fas fa-search" style="color:#666; margin-right:8px;"></i>
            <input type="text" name="search" placeholder="name, email, phone, fullLicenseKey "
              value="<%= search || '' %>" aria-label="Search" id="customerSearch" />
          </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="/register">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">

        <!-- Orders table (full width, same line-up as cards) -->
        <section class="card">
          <div class="card-header">
            <h2 class="section-title">Add New Customers</h2>
          </div>

          <div class="card-body form-wrapper">
            <%- include ("./partials/messages"); %>
              <form class="add-item-form" action="/admin/add-customer" method="POST">
                <div class="form-row">
                  <div class="form-group">
                    <input type="text" id="name" name="name" placeholder="Enter Customer Name" required>
                  </div>
                  <div class="form-group">
                    <input type="email" id="email" name="email" placeholder="Enter Email" required>
                  </div>
                </div>

                <div class="form-row">
                  <div class="form-group">
                    <input type="tel" id="phone" name="phone" placeholder="Enter Mobile No." required>
                  </div>
                  <div class="form-group">
                    <input type="text" id="fullLicenseKey" name="fullLicenseKey" readonly
                      placeholder="License key">
                  </div>
                  <div class="form-group">
                    <input type="number" id="price" name="price" placeholder="Enter Price">
                  </div>
                </div>

                <div class="form-group">
                  <input type="number" id="renewal" name="renewal" placeholder="Enter Renewal" required>
                </div>

                <div class="form-row">
                  <button type="submit" class="btn btn-primary">Add Customer</button>
                </div>
              </form>

          </div>
        </section>

        <!--List Item-->
        <section class="card">
          <div class="card-header">
            <h2 class="section-title">Customer List</h2>
            <div class="table-actions">
              <i class="fas fa-plus-circle"></i>
            </div>
          </div>

          <div class="table-responsive" id="customerTable">
            <% if (customers.length> 0) { %>
              <table class="table">
                <thead>
                  <tr>
                    <th style="text-align: center;">Action</th>
                    <th style="text-align: center;">Name</th>
                    <th style="text-align: center;">Email</th>
                    <th style="text-align: center;">Phone</th>
                    <th style="text-align: center;">License Key</th>
                    <th style="text-align: center;">Price</th>
                    <th style="text-align: center;">Renewal</th>
                  </tr>
                </thead>
                <tbody>
                  <% customers.forEach((row, index)=> { %>
                    <tr>
                      <td style="text-align: center;">
                        <div style="display: flex; justify-content: center; gap: 5px;">
                          <!-- This button just opens the modal -->
                          <button class="btn btn-sm btn-primary" onclick="openEditModal('<%= row._id %>')"><i
                              class="fas fa-edit"></i></button>
                          <form action="/admin/delete/<%= row._id %>" method="POST" style="display:inline-block;">
                            <button type="submit" class="btn btn-sm btn-light"
                              onclick="return confirm('Are you sure you want to delete this item?')">
                              <i class="fas fa-trash"></i>
                            </button>
                          </form>
                        </div>
                      </td>
                      <td style="text-align: center;">
                        <%= row.name %>
                      </td>
                      <td style="text-align: center;">
                        <%= row.email %>
                      </td>
                      <td style="text-align: center;">
                        <%= row.phone %>
                      </td>
                      <td style="text-align: center;">
                        <%= row.fullLicenseKey %>
                      </td>
                      <td style="text-align: center;">
                        <%= row.price %>
                      </td>
                      <td style="text-align: center;">
                        <%= row.renewal %>
                      </td>
                    </tr>
                    <% }) %>
                </tbody>
              </table>
              <% } else { %>
                <div style="text-align: center; margin-bottom: 50px;">
                  <h1>No Customer found</h1>
                </div>
                <% } %>
          </div>
        </section>
      </section>
    </div>



    <% customers.forEach((row)=> { %>
      <!-- Edit Modal for this row -->
      <div id="editModal-<%= row._id %>" class="custom-modal">
        <div class="modal-content">
          <span class="close-modal" onclick="closeModal('<%= row._id %>')">&times;</span>
          <h3>Edit Customer</h3>

          <!-- Updated form action includes /admin -->
          <form action="/admin/update/<%= row._id %>" method="POST">
            <div class="form-group">
              <input type="text" name="name" value="<%= row.name %>" required>
            </div>

            <div class="form-group">
              <input type="email" name="email" value="<%= row.email %>" required>
            </div>

            <div class="form-group">
              <input type="tel" name="phone" value="<%= row.phone %>" required>
            </div>

            <div class="form-group">
              <input type="text" name="fullLicenseKey" value="<%= row.fullLicenseKey %>" required>
            </div>

            <div class="form-group">
              <input type="number" name="price" value="<%= row.price %>" step="0.01" required>
            </div>

            <div class="form-group">
              <input type="number" name="renewal" value="<%= row.renewal %>" step="1" required>
            </div>

            <div class="form-group">
              <button type="submit" class="btn-submit">Save Changes</button>
            </div>
          </form>
        </div>
      </div>
      <% }); %>


        <script>
          function openEditModal(id) {
            document.getElementById('editModal-' + id).style.display = 'block';
          }

          function closeModal(id) {
            document.getElementById('editModal-' + id).style.display = 'none';
          }

          // Optional: Close modal when clicking outside
          window.onclick = function (event) {
            const modals = document.querySelectorAll('.modal');
            modals.forEach(modal => {
              if (event.target === modal) {
                modal.style.display = "none";
              }
            });
          };
        </script>




  </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>
    const fileInput = document.getElementById("fileInput");
    const fileName = document.getElementById("fileName");

    fileInput.addEventListener("change", function () {
      fileName.textContent = this.files.length > 0
        ? this.files[0].name
        : "No file chosen";
    });
  </script>

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

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

        fetch("/add-customer?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("#customerTable");

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


  <!--Auto Generated-->
  <script>
    const licenseInput = document.getElementById('fullLicenseKey');

    licenseInput.addEventListener('focus', async () => {
      try {
        const res = await fetch('/admin/generate-license'); // secure server route
        if (!res.ok) throw new Error('Failed to generate license key');

        const data = await res.json();
        licenseInput.value = data.key;
      } catch (err) {
        console.error(err);
        alert('Error generating license key. Please try again.');
      }
    });
  </script>


</body>

</html>